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
Yelp/yelp-android
src/test/java/com/yelp/clientlib/entities/SpanTest.java
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException;
package com.yelp.clientlib.entities; public class SpanTest { @Test public void testDeserializeFromJson() throws IOException {
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // } // Path: src/test/java/com/yelp/clientlib/entities/SpanTest.java import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; package com.yelp.clientlib.entities; public class SpanTest { @Test public void testDeserializeFromJson() throws IOException {
JsonNode spanNode = JsonTestUtils.getSearchResponseJsonNode().path("region").path("span");
Yelp/yelp-android
src/test/java/com/yelp/clientlib/entities/SpanTest.java
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException;
package com.yelp.clientlib.entities; public class SpanTest { @Test public void testDeserializeFromJson() throws IOException { JsonNode spanNode = JsonTestUtils.getSearchResponseJsonNode().path("region").path("span"); Span span = JsonTestUtils.deserializeJson(spanNode.toString(), Span.class); Assert.assertEquals(new Double(spanNode.path("latitude_delta").asDouble()), span.latitudeDelta()); Assert.assertEquals(new Double(spanNode.path("longitude_delta").asDouble()), span.longitudeDelta()); } @Test public void testSerializable() throws IOException, ClassNotFoundException { JsonNode spanNode = JsonTestUtils.getSearchResponseJsonNode().path("region").path("span"); Span span = JsonTestUtils.deserializeJson(spanNode.toString(), Span.class);
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // } // Path: src/test/java/com/yelp/clientlib/entities/SpanTest.java import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; package com.yelp.clientlib.entities; public class SpanTest { @Test public void testDeserializeFromJson() throws IOException { JsonNode spanNode = JsonTestUtils.getSearchResponseJsonNode().path("region").path("span"); Span span = JsonTestUtils.deserializeJson(spanNode.toString(), Span.class); Assert.assertEquals(new Double(spanNode.path("latitude_delta").asDouble()), span.latitudeDelta()); Assert.assertEquals(new Double(spanNode.path("longitude_delta").asDouble()), span.longitudeDelta()); } @Test public void testSerializable() throws IOException, ClassNotFoundException { JsonNode spanNode = JsonTestUtils.getSearchResponseJsonNode().path("region").path("span"); Span span = JsonTestUtils.deserializeJson(spanNode.toString(), Span.class);
byte[] bytes = SerializationTestUtils.serialize(span);
Yelp/yelp-android
src/test/java/com/yelp/clientlib/entities/BusinessTest.java
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // }
import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException;
package com.yelp.clientlib.entities; public class BusinessTest { @Test public void testDeserializeFromJson() throws IOException {
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // } // Path: src/test/java/com/yelp/clientlib/entities/BusinessTest.java import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; package com.yelp.clientlib.entities; public class BusinessTest { @Test public void testDeserializeFromJson() throws IOException {
JsonNode businessNode = JsonTestUtils.getBusinessResponseJsonNode();
Yelp/yelp-android
src/test/java/com/yelp/clientlib/entities/BusinessTest.java
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // }
import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException;
@Test public void testDeserializationWithUTF8Characters() throws IOException { String businessJsonString = "{\"name\":\"Gööd Füsiön Fööd\", \"id\":\"gööd-füsiön-fööd-san-francisco\"}"; Business business = JsonTestUtils.deserializeJson(businessJsonString, Business.class); Assert.assertEquals("Gööd Füsiön Fööd", business.name()); Assert.assertEquals("gööd-füsiön-fööd-san-francisco", business.id()); } @Test public void testDeserializationWithNoReviewBusinessHasNullForReview() throws IOException { JsonNode businessNode = JsonTestUtils.getJsonNodeFromFile("noReviewBusinessResponse.json"); Business business = JsonTestUtils.deserializeJson(businessNode.toString(), Business.class); Assert.assertNull(business.reviews()); Assert.assertEquals(new Integer(0), business.reviewCount()); Assert.assertEquals(businessNode.path("id").textValue(), business.id()); Assert.assertEquals(businessNode.path("rating_img_url").textValue(), business.ratingImgUrl()); Assert.assertEquals(businessNode.path("rating_img_url_small").textValue(), business.ratingImgUrlSmall()); } @Test(expected = JsonMappingException.class) public void testDeserializationFailedWithMissingAttributes() throws IOException { String businessJsonString = "{\"name\":\"Yelp\"}"; JsonTestUtils.deserializeJson(businessJsonString, Business.class); } @Test public void testSerializable() throws IOException, ClassNotFoundException { JsonNode businessNode = JsonTestUtils.getBusinessResponseJsonNode(); Business business = JsonTestUtils.deserializeJson(businessNode.toString(), Business.class);
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // } // Path: src/test/java/com/yelp/clientlib/entities/BusinessTest.java import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; @Test public void testDeserializationWithUTF8Characters() throws IOException { String businessJsonString = "{\"name\":\"Gööd Füsiön Fööd\", \"id\":\"gööd-füsiön-fööd-san-francisco\"}"; Business business = JsonTestUtils.deserializeJson(businessJsonString, Business.class); Assert.assertEquals("Gööd Füsiön Fööd", business.name()); Assert.assertEquals("gööd-füsiön-fööd-san-francisco", business.id()); } @Test public void testDeserializationWithNoReviewBusinessHasNullForReview() throws IOException { JsonNode businessNode = JsonTestUtils.getJsonNodeFromFile("noReviewBusinessResponse.json"); Business business = JsonTestUtils.deserializeJson(businessNode.toString(), Business.class); Assert.assertNull(business.reviews()); Assert.assertEquals(new Integer(0), business.reviewCount()); Assert.assertEquals(businessNode.path("id").textValue(), business.id()); Assert.assertEquals(businessNode.path("rating_img_url").textValue(), business.ratingImgUrl()); Assert.assertEquals(businessNode.path("rating_img_url_small").textValue(), business.ratingImgUrlSmall()); } @Test(expected = JsonMappingException.class) public void testDeserializationFailedWithMissingAttributes() throws IOException { String businessJsonString = "{\"name\":\"Yelp\"}"; JsonTestUtils.deserializeJson(businessJsonString, Business.class); } @Test public void testSerializable() throws IOException, ClassNotFoundException { JsonNode businessNode = JsonTestUtils.getBusinessResponseJsonNode(); Business business = JsonTestUtils.deserializeJson(businessNode.toString(), Business.class);
byte[] bytes = SerializationTestUtils.serialize(business);
Yelp/yelp-android
src/test/java/com/yelp/clientlib/entities/GiftCertificateOptionTest.java
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException;
package com.yelp.clientlib.entities; public class GiftCertificateOptionTest { @Test public void testDeserializeFromJson() throws IOException {
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // } // Path: src/test/java/com/yelp/clientlib/entities/GiftCertificateOptionTest.java import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; package com.yelp.clientlib.entities; public class GiftCertificateOptionTest { @Test public void testDeserializeFromJson() throws IOException {
JsonNode giftCertificateOptionNode = JsonTestUtils.getBusinessResponseJsonNode()
Yelp/yelp-android
src/test/java/com/yelp/clientlib/entities/GiftCertificateOptionTest.java
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException;
package com.yelp.clientlib.entities; public class GiftCertificateOptionTest { @Test public void testDeserializeFromJson() throws IOException { JsonNode giftCertificateOptionNode = JsonTestUtils.getBusinessResponseJsonNode() .path("gift_certificates").get(0).path("options").get(0); GiftCertificateOption giftCertificateOption = JsonTestUtils.deserializeJson( giftCertificateOptionNode.toString(), GiftCertificateOption.class ); Assert.assertEquals( giftCertificateOptionNode.path("formatted_price").textValue(), giftCertificateOption.formattedPrice() ); Assert.assertEquals( new Integer(giftCertificateOptionNode.path("price").asInt()), giftCertificateOption.price() ); } @Test public void testSerializable() throws IOException, ClassNotFoundException { JsonNode giftCertificateOptionNode = JsonTestUtils.getBusinessResponseJsonNode() .path("gift_certificates").get(0).path("options").get(0); GiftCertificateOption giftCertificateOption = JsonTestUtils.deserializeJson( giftCertificateOptionNode.toString(), GiftCertificateOption.class );
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // } // Path: src/test/java/com/yelp/clientlib/entities/GiftCertificateOptionTest.java import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; package com.yelp.clientlib.entities; public class GiftCertificateOptionTest { @Test public void testDeserializeFromJson() throws IOException { JsonNode giftCertificateOptionNode = JsonTestUtils.getBusinessResponseJsonNode() .path("gift_certificates").get(0).path("options").get(0); GiftCertificateOption giftCertificateOption = JsonTestUtils.deserializeJson( giftCertificateOptionNode.toString(), GiftCertificateOption.class ); Assert.assertEquals( giftCertificateOptionNode.path("formatted_price").textValue(), giftCertificateOption.formattedPrice() ); Assert.assertEquals( new Integer(giftCertificateOptionNode.path("price").asInt()), giftCertificateOption.price() ); } @Test public void testSerializable() throws IOException, ClassNotFoundException { JsonNode giftCertificateOptionNode = JsonTestUtils.getBusinessResponseJsonNode() .path("gift_certificates").get(0).path("options").get(0); GiftCertificateOption giftCertificateOption = JsonTestUtils.deserializeJson( giftCertificateOptionNode.toString(), GiftCertificateOption.class );
byte[] bytes = SerializationTestUtils.serialize(giftCertificateOption);
Yelp/yelp-android
src/test/java/com/yelp/clientlib/exception/ErrorHandlingInterceptorTest.java
// Path: src/main/java/com/yelp/clientlib/exception/exceptions/BusinessUnavailable.java // public class BusinessUnavailable extends YelpAPIError { // public BusinessUnavailable(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/InternalError.java // public class InternalError extends YelpAPIError { // public InternalError(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/InvalidParameter.java // public class InvalidParameter extends YelpAPIError { // public InvalidParameter(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/UnexpectedAPIError.java // public class UnexpectedAPIError extends YelpAPIError { // public UnexpectedAPIError(int code, String message) { // this(code, message, null, null); // } // // public UnexpectedAPIError(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/ErrorTestUtils.java // public class ErrorTestUtils { // // /** // * Verify a {@link YelpAPIError} contains correct information. // * // * @param error The YelpAPIError to be verified. // * @param expectCode Expected error code. // * @param expectMessage Expected error message. // * @param expectId Expected error Id. // * @param expectText Expected error text. // */ // public static void verifyErrorContent( // YelpAPIError error, // int expectCode, // String expectMessage, // String expectId, // String expectText // ) { // Assert.assertEquals(expectCode, error.getCode()); // Assert.assertEquals(expectMessage, error.getMessage()); // Assert.assertEquals(expectId, error.getErrorId()); // Assert.assertEquals(expectText, error.getText()); // } // }
import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.Protocol; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; import com.yelp.clientlib.exception.exceptions.BusinessUnavailable; import com.yelp.clientlib.exception.exceptions.InternalError; import com.yelp.clientlib.exception.exceptions.InvalidParameter; import com.yelp.clientlib.exception.exceptions.UnexpectedAPIError; import com.yelp.clientlib.utils.ErrorTestUtils; import org.easymock.EasyMock; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException;
package com.yelp.clientlib.exception; @RunWith(PowerMockRunner.class) @PrepareForTest({Request.class, Response.class, Protocol.class}) public class ErrorHandlingInterceptorTest { Interceptor errorHandlingInterceptor; @Before public void setUp() { this.errorHandlingInterceptor = new ErrorHandlingInterceptor(); } /** * Ensure the interceptor does nothing besides proceeding the request if the request is done successfully. */ @Test public void testSuccessfulRequestNotDoingAnythingExceptProceedingRequests() throws IOException { Request mockRequest = PowerMock.createMock(Request.class); Response mockResponse = PowerMock.createMock(Response.class); Interceptor.Chain mockChain = PowerMock.createMock(Interceptor.Chain.class); EasyMock.expect(mockChain.request()).andReturn(mockRequest); EasyMock.expect(mockChain.proceed(mockRequest)).andReturn(mockResponse); EasyMock.expect(mockResponse.isSuccessful()).andReturn(true); PowerMock.replay(mockRequest, mockResponse, mockChain); Response returnedResponse = errorHandlingInterceptor.intercept(mockChain); PowerMock.verify(mockChain); Assert.assertEquals(mockResponse, returnedResponse); } @Test public void testParseNullResponseBody() throws IOException { int errorCode = 500; String errorMessage = "Internal Server Error"; Interceptor.Chain mockChain = mockChainWithErrorResponse(errorCode, errorMessage, null); try { errorHandlingInterceptor.intercept(mockChain);
// Path: src/main/java/com/yelp/clientlib/exception/exceptions/BusinessUnavailable.java // public class BusinessUnavailable extends YelpAPIError { // public BusinessUnavailable(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/InternalError.java // public class InternalError extends YelpAPIError { // public InternalError(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/InvalidParameter.java // public class InvalidParameter extends YelpAPIError { // public InvalidParameter(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/UnexpectedAPIError.java // public class UnexpectedAPIError extends YelpAPIError { // public UnexpectedAPIError(int code, String message) { // this(code, message, null, null); // } // // public UnexpectedAPIError(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/ErrorTestUtils.java // public class ErrorTestUtils { // // /** // * Verify a {@link YelpAPIError} contains correct information. // * // * @param error The YelpAPIError to be verified. // * @param expectCode Expected error code. // * @param expectMessage Expected error message. // * @param expectId Expected error Id. // * @param expectText Expected error text. // */ // public static void verifyErrorContent( // YelpAPIError error, // int expectCode, // String expectMessage, // String expectId, // String expectText // ) { // Assert.assertEquals(expectCode, error.getCode()); // Assert.assertEquals(expectMessage, error.getMessage()); // Assert.assertEquals(expectId, error.getErrorId()); // Assert.assertEquals(expectText, error.getText()); // } // } // Path: src/test/java/com/yelp/clientlib/exception/ErrorHandlingInterceptorTest.java import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.Protocol; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; import com.yelp.clientlib.exception.exceptions.BusinessUnavailable; import com.yelp.clientlib.exception.exceptions.InternalError; import com.yelp.clientlib.exception.exceptions.InvalidParameter; import com.yelp.clientlib.exception.exceptions.UnexpectedAPIError; import com.yelp.clientlib.utils.ErrorTestUtils; import org.easymock.EasyMock; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException; package com.yelp.clientlib.exception; @RunWith(PowerMockRunner.class) @PrepareForTest({Request.class, Response.class, Protocol.class}) public class ErrorHandlingInterceptorTest { Interceptor errorHandlingInterceptor; @Before public void setUp() { this.errorHandlingInterceptor = new ErrorHandlingInterceptor(); } /** * Ensure the interceptor does nothing besides proceeding the request if the request is done successfully. */ @Test public void testSuccessfulRequestNotDoingAnythingExceptProceedingRequests() throws IOException { Request mockRequest = PowerMock.createMock(Request.class); Response mockResponse = PowerMock.createMock(Response.class); Interceptor.Chain mockChain = PowerMock.createMock(Interceptor.Chain.class); EasyMock.expect(mockChain.request()).andReturn(mockRequest); EasyMock.expect(mockChain.proceed(mockRequest)).andReturn(mockResponse); EasyMock.expect(mockResponse.isSuccessful()).andReturn(true); PowerMock.replay(mockRequest, mockResponse, mockChain); Response returnedResponse = errorHandlingInterceptor.intercept(mockChain); PowerMock.verify(mockChain); Assert.assertEquals(mockResponse, returnedResponse); } @Test public void testParseNullResponseBody() throws IOException { int errorCode = 500; String errorMessage = "Internal Server Error"; Interceptor.Chain mockChain = mockChainWithErrorResponse(errorCode, errorMessage, null); try { errorHandlingInterceptor.intercept(mockChain);
} catch (UnexpectedAPIError error) {
Yelp/yelp-android
src/test/java/com/yelp/clientlib/exception/ErrorHandlingInterceptorTest.java
// Path: src/main/java/com/yelp/clientlib/exception/exceptions/BusinessUnavailable.java // public class BusinessUnavailable extends YelpAPIError { // public BusinessUnavailable(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/InternalError.java // public class InternalError extends YelpAPIError { // public InternalError(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/InvalidParameter.java // public class InvalidParameter extends YelpAPIError { // public InvalidParameter(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/UnexpectedAPIError.java // public class UnexpectedAPIError extends YelpAPIError { // public UnexpectedAPIError(int code, String message) { // this(code, message, null, null); // } // // public UnexpectedAPIError(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/ErrorTestUtils.java // public class ErrorTestUtils { // // /** // * Verify a {@link YelpAPIError} contains correct information. // * // * @param error The YelpAPIError to be verified. // * @param expectCode Expected error code. // * @param expectMessage Expected error message. // * @param expectId Expected error Id. // * @param expectText Expected error text. // */ // public static void verifyErrorContent( // YelpAPIError error, // int expectCode, // String expectMessage, // String expectId, // String expectText // ) { // Assert.assertEquals(expectCode, error.getCode()); // Assert.assertEquals(expectMessage, error.getMessage()); // Assert.assertEquals(expectId, error.getErrorId()); // Assert.assertEquals(expectText, error.getText()); // } // }
import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.Protocol; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; import com.yelp.clientlib.exception.exceptions.BusinessUnavailable; import com.yelp.clientlib.exception.exceptions.InternalError; import com.yelp.clientlib.exception.exceptions.InvalidParameter; import com.yelp.clientlib.exception.exceptions.UnexpectedAPIError; import com.yelp.clientlib.utils.ErrorTestUtils; import org.easymock.EasyMock; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException;
package com.yelp.clientlib.exception; @RunWith(PowerMockRunner.class) @PrepareForTest({Request.class, Response.class, Protocol.class}) public class ErrorHandlingInterceptorTest { Interceptor errorHandlingInterceptor; @Before public void setUp() { this.errorHandlingInterceptor = new ErrorHandlingInterceptor(); } /** * Ensure the interceptor does nothing besides proceeding the request if the request is done successfully. */ @Test public void testSuccessfulRequestNotDoingAnythingExceptProceedingRequests() throws IOException { Request mockRequest = PowerMock.createMock(Request.class); Response mockResponse = PowerMock.createMock(Response.class); Interceptor.Chain mockChain = PowerMock.createMock(Interceptor.Chain.class); EasyMock.expect(mockChain.request()).andReturn(mockRequest); EasyMock.expect(mockChain.proceed(mockRequest)).andReturn(mockResponse); EasyMock.expect(mockResponse.isSuccessful()).andReturn(true); PowerMock.replay(mockRequest, mockResponse, mockChain); Response returnedResponse = errorHandlingInterceptor.intercept(mockChain); PowerMock.verify(mockChain); Assert.assertEquals(mockResponse, returnedResponse); } @Test public void testParseNullResponseBody() throws IOException { int errorCode = 500; String errorMessage = "Internal Server Error"; Interceptor.Chain mockChain = mockChainWithErrorResponse(errorCode, errorMessage, null); try { errorHandlingInterceptor.intercept(mockChain); } catch (UnexpectedAPIError error) {
// Path: src/main/java/com/yelp/clientlib/exception/exceptions/BusinessUnavailable.java // public class BusinessUnavailable extends YelpAPIError { // public BusinessUnavailable(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/InternalError.java // public class InternalError extends YelpAPIError { // public InternalError(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/InvalidParameter.java // public class InvalidParameter extends YelpAPIError { // public InvalidParameter(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/UnexpectedAPIError.java // public class UnexpectedAPIError extends YelpAPIError { // public UnexpectedAPIError(int code, String message) { // this(code, message, null, null); // } // // public UnexpectedAPIError(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/ErrorTestUtils.java // public class ErrorTestUtils { // // /** // * Verify a {@link YelpAPIError} contains correct information. // * // * @param error The YelpAPIError to be verified. // * @param expectCode Expected error code. // * @param expectMessage Expected error message. // * @param expectId Expected error Id. // * @param expectText Expected error text. // */ // public static void verifyErrorContent( // YelpAPIError error, // int expectCode, // String expectMessage, // String expectId, // String expectText // ) { // Assert.assertEquals(expectCode, error.getCode()); // Assert.assertEquals(expectMessage, error.getMessage()); // Assert.assertEquals(expectId, error.getErrorId()); // Assert.assertEquals(expectText, error.getText()); // } // } // Path: src/test/java/com/yelp/clientlib/exception/ErrorHandlingInterceptorTest.java import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.Protocol; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; import com.yelp.clientlib.exception.exceptions.BusinessUnavailable; import com.yelp.clientlib.exception.exceptions.InternalError; import com.yelp.clientlib.exception.exceptions.InvalidParameter; import com.yelp.clientlib.exception.exceptions.UnexpectedAPIError; import com.yelp.clientlib.utils.ErrorTestUtils; import org.easymock.EasyMock; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException; package com.yelp.clientlib.exception; @RunWith(PowerMockRunner.class) @PrepareForTest({Request.class, Response.class, Protocol.class}) public class ErrorHandlingInterceptorTest { Interceptor errorHandlingInterceptor; @Before public void setUp() { this.errorHandlingInterceptor = new ErrorHandlingInterceptor(); } /** * Ensure the interceptor does nothing besides proceeding the request if the request is done successfully. */ @Test public void testSuccessfulRequestNotDoingAnythingExceptProceedingRequests() throws IOException { Request mockRequest = PowerMock.createMock(Request.class); Response mockResponse = PowerMock.createMock(Response.class); Interceptor.Chain mockChain = PowerMock.createMock(Interceptor.Chain.class); EasyMock.expect(mockChain.request()).andReturn(mockRequest); EasyMock.expect(mockChain.proceed(mockRequest)).andReturn(mockResponse); EasyMock.expect(mockResponse.isSuccessful()).andReturn(true); PowerMock.replay(mockRequest, mockResponse, mockChain); Response returnedResponse = errorHandlingInterceptor.intercept(mockChain); PowerMock.verify(mockChain); Assert.assertEquals(mockResponse, returnedResponse); } @Test public void testParseNullResponseBody() throws IOException { int errorCode = 500; String errorMessage = "Internal Server Error"; Interceptor.Chain mockChain = mockChainWithErrorResponse(errorCode, errorMessage, null); try { errorHandlingInterceptor.intercept(mockChain); } catch (UnexpectedAPIError error) {
ErrorTestUtils.verifyErrorContent(error, errorCode, errorMessage, null, null);
Yelp/yelp-android
src/test/java/com/yelp/clientlib/exception/ErrorHandlingInterceptorTest.java
// Path: src/main/java/com/yelp/clientlib/exception/exceptions/BusinessUnavailable.java // public class BusinessUnavailable extends YelpAPIError { // public BusinessUnavailable(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/InternalError.java // public class InternalError extends YelpAPIError { // public InternalError(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/InvalidParameter.java // public class InvalidParameter extends YelpAPIError { // public InvalidParameter(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/UnexpectedAPIError.java // public class UnexpectedAPIError extends YelpAPIError { // public UnexpectedAPIError(int code, String message) { // this(code, message, null, null); // } // // public UnexpectedAPIError(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/ErrorTestUtils.java // public class ErrorTestUtils { // // /** // * Verify a {@link YelpAPIError} contains correct information. // * // * @param error The YelpAPIError to be verified. // * @param expectCode Expected error code. // * @param expectMessage Expected error message. // * @param expectId Expected error Id. // * @param expectText Expected error text. // */ // public static void verifyErrorContent( // YelpAPIError error, // int expectCode, // String expectMessage, // String expectId, // String expectText // ) { // Assert.assertEquals(expectCode, error.getCode()); // Assert.assertEquals(expectMessage, error.getMessage()); // Assert.assertEquals(expectId, error.getErrorId()); // Assert.assertEquals(expectText, error.getText()); // } // }
import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.Protocol; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; import com.yelp.clientlib.exception.exceptions.BusinessUnavailable; import com.yelp.clientlib.exception.exceptions.InternalError; import com.yelp.clientlib.exception.exceptions.InvalidParameter; import com.yelp.clientlib.exception.exceptions.UnexpectedAPIError; import com.yelp.clientlib.utils.ErrorTestUtils; import org.easymock.EasyMock; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException;
Assert.assertEquals(mockResponse, returnedResponse); } @Test public void testParseNullResponseBody() throws IOException { int errorCode = 500; String errorMessage = "Internal Server Error"; Interceptor.Chain mockChain = mockChainWithErrorResponse(errorCode, errorMessage, null); try { errorHandlingInterceptor.intercept(mockChain); } catch (UnexpectedAPIError error) { ErrorTestUtils.verifyErrorContent(error, errorCode, errorMessage, null, null); return; } Assert.fail("Expected failure not returned."); } @Test public void testParseBusinessUnavailable() throws IOException { int errorCode = 400; String errorMessage = "Bad Request"; String errorId = "BUSINESS_UNAVAILABLE"; String errorText = "Business information is unavailable"; String errorJsonBody = generateErrorJsonString(errorId, errorText); Interceptor.Chain mockChain = mockChainWithErrorResponse(errorCode, errorMessage, errorJsonBody); try { errorHandlingInterceptor.intercept(mockChain);
// Path: src/main/java/com/yelp/clientlib/exception/exceptions/BusinessUnavailable.java // public class BusinessUnavailable extends YelpAPIError { // public BusinessUnavailable(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/InternalError.java // public class InternalError extends YelpAPIError { // public InternalError(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/InvalidParameter.java // public class InvalidParameter extends YelpAPIError { // public InvalidParameter(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/UnexpectedAPIError.java // public class UnexpectedAPIError extends YelpAPIError { // public UnexpectedAPIError(int code, String message) { // this(code, message, null, null); // } // // public UnexpectedAPIError(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/ErrorTestUtils.java // public class ErrorTestUtils { // // /** // * Verify a {@link YelpAPIError} contains correct information. // * // * @param error The YelpAPIError to be verified. // * @param expectCode Expected error code. // * @param expectMessage Expected error message. // * @param expectId Expected error Id. // * @param expectText Expected error text. // */ // public static void verifyErrorContent( // YelpAPIError error, // int expectCode, // String expectMessage, // String expectId, // String expectText // ) { // Assert.assertEquals(expectCode, error.getCode()); // Assert.assertEquals(expectMessage, error.getMessage()); // Assert.assertEquals(expectId, error.getErrorId()); // Assert.assertEquals(expectText, error.getText()); // } // } // Path: src/test/java/com/yelp/clientlib/exception/ErrorHandlingInterceptorTest.java import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.Protocol; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; import com.yelp.clientlib.exception.exceptions.BusinessUnavailable; import com.yelp.clientlib.exception.exceptions.InternalError; import com.yelp.clientlib.exception.exceptions.InvalidParameter; import com.yelp.clientlib.exception.exceptions.UnexpectedAPIError; import com.yelp.clientlib.utils.ErrorTestUtils; import org.easymock.EasyMock; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException; Assert.assertEquals(mockResponse, returnedResponse); } @Test public void testParseNullResponseBody() throws IOException { int errorCode = 500; String errorMessage = "Internal Server Error"; Interceptor.Chain mockChain = mockChainWithErrorResponse(errorCode, errorMessage, null); try { errorHandlingInterceptor.intercept(mockChain); } catch (UnexpectedAPIError error) { ErrorTestUtils.verifyErrorContent(error, errorCode, errorMessage, null, null); return; } Assert.fail("Expected failure not returned."); } @Test public void testParseBusinessUnavailable() throws IOException { int errorCode = 400; String errorMessage = "Bad Request"; String errorId = "BUSINESS_UNAVAILABLE"; String errorText = "Business information is unavailable"; String errorJsonBody = generateErrorJsonString(errorId, errorText); Interceptor.Chain mockChain = mockChainWithErrorResponse(errorCode, errorMessage, errorJsonBody); try { errorHandlingInterceptor.intercept(mockChain);
} catch (BusinessUnavailable error) {
Yelp/yelp-android
src/test/java/com/yelp/clientlib/exception/ErrorHandlingInterceptorTest.java
// Path: src/main/java/com/yelp/clientlib/exception/exceptions/BusinessUnavailable.java // public class BusinessUnavailable extends YelpAPIError { // public BusinessUnavailable(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/InternalError.java // public class InternalError extends YelpAPIError { // public InternalError(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/InvalidParameter.java // public class InvalidParameter extends YelpAPIError { // public InvalidParameter(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/UnexpectedAPIError.java // public class UnexpectedAPIError extends YelpAPIError { // public UnexpectedAPIError(int code, String message) { // this(code, message, null, null); // } // // public UnexpectedAPIError(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/ErrorTestUtils.java // public class ErrorTestUtils { // // /** // * Verify a {@link YelpAPIError} contains correct information. // * // * @param error The YelpAPIError to be verified. // * @param expectCode Expected error code. // * @param expectMessage Expected error message. // * @param expectId Expected error Id. // * @param expectText Expected error text. // */ // public static void verifyErrorContent( // YelpAPIError error, // int expectCode, // String expectMessage, // String expectId, // String expectText // ) { // Assert.assertEquals(expectCode, error.getCode()); // Assert.assertEquals(expectMessage, error.getMessage()); // Assert.assertEquals(expectId, error.getErrorId()); // Assert.assertEquals(expectText, error.getText()); // } // }
import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.Protocol; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; import com.yelp.clientlib.exception.exceptions.BusinessUnavailable; import com.yelp.clientlib.exception.exceptions.InternalError; import com.yelp.clientlib.exception.exceptions.InvalidParameter; import com.yelp.clientlib.exception.exceptions.UnexpectedAPIError; import com.yelp.clientlib.utils.ErrorTestUtils; import org.easymock.EasyMock; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException;
@Test public void testParseBusinessUnavailable() throws IOException { int errorCode = 400; String errorMessage = "Bad Request"; String errorId = "BUSINESS_UNAVAILABLE"; String errorText = "Business information is unavailable"; String errorJsonBody = generateErrorJsonString(errorId, errorText); Interceptor.Chain mockChain = mockChainWithErrorResponse(errorCode, errorMessage, errorJsonBody); try { errorHandlingInterceptor.intercept(mockChain); } catch (BusinessUnavailable error) { ErrorTestUtils.verifyErrorContent(error, errorCode, errorMessage, errorId, errorText); return; } Assert.fail("Expected failure not returned."); } @Test public void testParseInternalError() throws IOException { int errorCode = 500; String errorMessage = "Internal Server Error"; String errorId = "INTERNAL_ERROR"; String errorText = "Some internal error happened"; String errorJsonBody = generateErrorJsonString(errorId, errorText); Interceptor.Chain mockChain = mockChainWithErrorResponse(errorCode, errorMessage, errorJsonBody); try { errorHandlingInterceptor.intercept(mockChain);
// Path: src/main/java/com/yelp/clientlib/exception/exceptions/BusinessUnavailable.java // public class BusinessUnavailable extends YelpAPIError { // public BusinessUnavailable(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/InternalError.java // public class InternalError extends YelpAPIError { // public InternalError(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/InvalidParameter.java // public class InvalidParameter extends YelpAPIError { // public InvalidParameter(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/UnexpectedAPIError.java // public class UnexpectedAPIError extends YelpAPIError { // public UnexpectedAPIError(int code, String message) { // this(code, message, null, null); // } // // public UnexpectedAPIError(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/ErrorTestUtils.java // public class ErrorTestUtils { // // /** // * Verify a {@link YelpAPIError} contains correct information. // * // * @param error The YelpAPIError to be verified. // * @param expectCode Expected error code. // * @param expectMessage Expected error message. // * @param expectId Expected error Id. // * @param expectText Expected error text. // */ // public static void verifyErrorContent( // YelpAPIError error, // int expectCode, // String expectMessage, // String expectId, // String expectText // ) { // Assert.assertEquals(expectCode, error.getCode()); // Assert.assertEquals(expectMessage, error.getMessage()); // Assert.assertEquals(expectId, error.getErrorId()); // Assert.assertEquals(expectText, error.getText()); // } // } // Path: src/test/java/com/yelp/clientlib/exception/ErrorHandlingInterceptorTest.java import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.Protocol; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; import com.yelp.clientlib.exception.exceptions.BusinessUnavailable; import com.yelp.clientlib.exception.exceptions.InternalError; import com.yelp.clientlib.exception.exceptions.InvalidParameter; import com.yelp.clientlib.exception.exceptions.UnexpectedAPIError; import com.yelp.clientlib.utils.ErrorTestUtils; import org.easymock.EasyMock; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException; @Test public void testParseBusinessUnavailable() throws IOException { int errorCode = 400; String errorMessage = "Bad Request"; String errorId = "BUSINESS_UNAVAILABLE"; String errorText = "Business information is unavailable"; String errorJsonBody = generateErrorJsonString(errorId, errorText); Interceptor.Chain mockChain = mockChainWithErrorResponse(errorCode, errorMessage, errorJsonBody); try { errorHandlingInterceptor.intercept(mockChain); } catch (BusinessUnavailable error) { ErrorTestUtils.verifyErrorContent(error, errorCode, errorMessage, errorId, errorText); return; } Assert.fail("Expected failure not returned."); } @Test public void testParseInternalError() throws IOException { int errorCode = 500; String errorMessage = "Internal Server Error"; String errorId = "INTERNAL_ERROR"; String errorText = "Some internal error happened"; String errorJsonBody = generateErrorJsonString(errorId, errorText); Interceptor.Chain mockChain = mockChainWithErrorResponse(errorCode, errorMessage, errorJsonBody); try { errorHandlingInterceptor.intercept(mockChain);
} catch (InternalError error) {
Yelp/yelp-android
src/test/java/com/yelp/clientlib/exception/ErrorHandlingInterceptorTest.java
// Path: src/main/java/com/yelp/clientlib/exception/exceptions/BusinessUnavailable.java // public class BusinessUnavailable extends YelpAPIError { // public BusinessUnavailable(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/InternalError.java // public class InternalError extends YelpAPIError { // public InternalError(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/InvalidParameter.java // public class InvalidParameter extends YelpAPIError { // public InvalidParameter(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/UnexpectedAPIError.java // public class UnexpectedAPIError extends YelpAPIError { // public UnexpectedAPIError(int code, String message) { // this(code, message, null, null); // } // // public UnexpectedAPIError(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/ErrorTestUtils.java // public class ErrorTestUtils { // // /** // * Verify a {@link YelpAPIError} contains correct information. // * // * @param error The YelpAPIError to be verified. // * @param expectCode Expected error code. // * @param expectMessage Expected error message. // * @param expectId Expected error Id. // * @param expectText Expected error text. // */ // public static void verifyErrorContent( // YelpAPIError error, // int expectCode, // String expectMessage, // String expectId, // String expectText // ) { // Assert.assertEquals(expectCode, error.getCode()); // Assert.assertEquals(expectMessage, error.getMessage()); // Assert.assertEquals(expectId, error.getErrorId()); // Assert.assertEquals(expectText, error.getText()); // } // }
import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.Protocol; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; import com.yelp.clientlib.exception.exceptions.BusinessUnavailable; import com.yelp.clientlib.exception.exceptions.InternalError; import com.yelp.clientlib.exception.exceptions.InvalidParameter; import com.yelp.clientlib.exception.exceptions.UnexpectedAPIError; import com.yelp.clientlib.utils.ErrorTestUtils; import org.easymock.EasyMock; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException;
int errorCode = 500; String errorMessage = "Internal Server Error"; String errorId = "INTERNAL_ERROR"; String errorText = "Some internal error happened"; String errorJsonBody = generateErrorJsonString(errorId, errorText); Interceptor.Chain mockChain = mockChainWithErrorResponse(errorCode, errorMessage, errorJsonBody); try { errorHandlingInterceptor.intercept(mockChain); } catch (InternalError error) { ErrorTestUtils.verifyErrorContent(error, errorCode, errorMessage, errorId, errorText); return; } Assert.fail("Expected failure not returned."); } @Test public void testParseErrorWithField() throws IOException { int errorCode = 400; String errorMessage = "Bad Request"; String errorId = "INVALID_PARAMETER"; String errorText = "One or more parameters are invalid in request"; String errorField = "phone"; String expectedErrorText = String.format("%s: %s", errorText, errorField); String errorJsonBody = generateErrorJsonString(errorId, errorText, errorField); Interceptor.Chain mockChain = mockChainWithErrorResponse(errorCode, errorMessage, errorJsonBody); try { errorHandlingInterceptor.intercept(mockChain);
// Path: src/main/java/com/yelp/clientlib/exception/exceptions/BusinessUnavailable.java // public class BusinessUnavailable extends YelpAPIError { // public BusinessUnavailable(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/InternalError.java // public class InternalError extends YelpAPIError { // public InternalError(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/InvalidParameter.java // public class InvalidParameter extends YelpAPIError { // public InvalidParameter(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/main/java/com/yelp/clientlib/exception/exceptions/UnexpectedAPIError.java // public class UnexpectedAPIError extends YelpAPIError { // public UnexpectedAPIError(int code, String message) { // this(code, message, null, null); // } // // public UnexpectedAPIError(int code, String message, String id, String text) { // super(code, message, id, text); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/ErrorTestUtils.java // public class ErrorTestUtils { // // /** // * Verify a {@link YelpAPIError} contains correct information. // * // * @param error The YelpAPIError to be verified. // * @param expectCode Expected error code. // * @param expectMessage Expected error message. // * @param expectId Expected error Id. // * @param expectText Expected error text. // */ // public static void verifyErrorContent( // YelpAPIError error, // int expectCode, // String expectMessage, // String expectId, // String expectText // ) { // Assert.assertEquals(expectCode, error.getCode()); // Assert.assertEquals(expectMessage, error.getMessage()); // Assert.assertEquals(expectId, error.getErrorId()); // Assert.assertEquals(expectText, error.getText()); // } // } // Path: src/test/java/com/yelp/clientlib/exception/ErrorHandlingInterceptorTest.java import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.Protocol; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; import com.yelp.clientlib.exception.exceptions.BusinessUnavailable; import com.yelp.clientlib.exception.exceptions.InternalError; import com.yelp.clientlib.exception.exceptions.InvalidParameter; import com.yelp.clientlib.exception.exceptions.UnexpectedAPIError; import com.yelp.clientlib.utils.ErrorTestUtils; import org.easymock.EasyMock; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException; int errorCode = 500; String errorMessage = "Internal Server Error"; String errorId = "INTERNAL_ERROR"; String errorText = "Some internal error happened"; String errorJsonBody = generateErrorJsonString(errorId, errorText); Interceptor.Chain mockChain = mockChainWithErrorResponse(errorCode, errorMessage, errorJsonBody); try { errorHandlingInterceptor.intercept(mockChain); } catch (InternalError error) { ErrorTestUtils.verifyErrorContent(error, errorCode, errorMessage, errorId, errorText); return; } Assert.fail("Expected failure not returned."); } @Test public void testParseErrorWithField() throws IOException { int errorCode = 400; String errorMessage = "Bad Request"; String errorId = "INVALID_PARAMETER"; String errorText = "One or more parameters are invalid in request"; String errorField = "phone"; String expectedErrorText = String.format("%s: %s", errorText, errorField); String errorJsonBody = generateErrorJsonString(errorId, errorText, errorField); Interceptor.Chain mockChain = mockChainWithErrorResponse(errorCode, errorMessage, errorJsonBody); try { errorHandlingInterceptor.intercept(mockChain);
} catch (InvalidParameter error) {
Yelp/yelp-android
src/test/java/com/yelp/clientlib/entities/LocationTest.java
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException;
package com.yelp.clientlib.entities; public class LocationTest { @Test public void testDeserializeFromJson() throws IOException {
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // } // Path: src/test/java/com/yelp/clientlib/entities/LocationTest.java import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; package com.yelp.clientlib.entities; public class LocationTest { @Test public void testDeserializeFromJson() throws IOException {
JsonNode locationNode = JsonTestUtils.getBusinessResponseJsonNode().path("location");
Yelp/yelp-android
src/test/java/com/yelp/clientlib/entities/LocationTest.java
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException;
package com.yelp.clientlib.entities; public class LocationTest { @Test public void testDeserializeFromJson() throws IOException { JsonNode locationNode = JsonTestUtils.getBusinessResponseJsonNode().path("location"); Location location = JsonTestUtils.deserializeJson(locationNode.toString(), Location.class); Assert.assertEquals(1, location.address().size()); Assert.assertEquals(locationNode.path("city").textValue(), location.city()); Assert.assertNotNull(location.coordinate()); Assert.assertEquals(locationNode.path("country_code").textValue(), location.countryCode()); Assert.assertEquals(locationNode.path("cross_streets").textValue(), location.crossStreets()); Assert.assertEquals(3, location.displayAddress().size()); Assert.assertEquals(new Double(locationNode.path("geo_accuracy").asDouble()), location.geoAccuracy()); Assert.assertEquals(2, location.neighborhoods().size()); Assert.assertEquals(locationNode.path("postal_code").textValue(), location.postalCode()); Assert.assertEquals(locationNode.path("state_code").textValue(), location.stateCode()); } @Test public void testSerializable() throws IOException, ClassNotFoundException { JsonNode locationNode = JsonTestUtils.getBusinessResponseJsonNode().path("location"); Location location = JsonTestUtils.deserializeJson(locationNode.toString(), Location.class);
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // } // Path: src/test/java/com/yelp/clientlib/entities/LocationTest.java import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; package com.yelp.clientlib.entities; public class LocationTest { @Test public void testDeserializeFromJson() throws IOException { JsonNode locationNode = JsonTestUtils.getBusinessResponseJsonNode().path("location"); Location location = JsonTestUtils.deserializeJson(locationNode.toString(), Location.class); Assert.assertEquals(1, location.address().size()); Assert.assertEquals(locationNode.path("city").textValue(), location.city()); Assert.assertNotNull(location.coordinate()); Assert.assertEquals(locationNode.path("country_code").textValue(), location.countryCode()); Assert.assertEquals(locationNode.path("cross_streets").textValue(), location.crossStreets()); Assert.assertEquals(3, location.displayAddress().size()); Assert.assertEquals(new Double(locationNode.path("geo_accuracy").asDouble()), location.geoAccuracy()); Assert.assertEquals(2, location.neighborhoods().size()); Assert.assertEquals(locationNode.path("postal_code").textValue(), location.postalCode()); Assert.assertEquals(locationNode.path("state_code").textValue(), location.stateCode()); } @Test public void testSerializable() throws IOException, ClassNotFoundException { JsonNode locationNode = JsonTestUtils.getBusinessResponseJsonNode().path("location"); Location location = JsonTestUtils.deserializeJson(locationNode.toString(), Location.class);
byte[] bytes = SerializationTestUtils.serialize(location);
Yelp/yelp-android
src/test/java/com/yelp/clientlib/entities/GiftCertificateTest.java
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException;
package com.yelp.clientlib.entities; public class GiftCertificateTest { @Test public void testDeserializeFromJson() throws IOException {
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // } // Path: src/test/java/com/yelp/clientlib/entities/GiftCertificateTest.java import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; package com.yelp.clientlib.entities; public class GiftCertificateTest { @Test public void testDeserializeFromJson() throws IOException {
JsonNode giftCertificatesNode = JsonTestUtils.getBusinessResponseJsonNode().path("gift_certificates").get(0);
Yelp/yelp-android
src/test/java/com/yelp/clientlib/entities/GiftCertificateTest.java
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException;
package com.yelp.clientlib.entities; public class GiftCertificateTest { @Test public void testDeserializeFromJson() throws IOException { JsonNode giftCertificatesNode = JsonTestUtils.getBusinessResponseJsonNode().path("gift_certificates").get(0); GiftCertificate giftCertificate = JsonTestUtils.deserializeJson( giftCertificatesNode.toString(), GiftCertificate.class ); Assert.assertEquals(giftCertificatesNode.path("id").textValue(), giftCertificate.id()); Assert.assertEquals(giftCertificatesNode.path("url").textValue(), giftCertificate.url()); Assert.assertEquals(giftCertificatesNode.path("image_url").textValue(), giftCertificate.imageUrl()); Assert.assertEquals(giftCertificatesNode.path("currency_code").textValue(), giftCertificate.currencyCode()); Assert.assertEquals(giftCertificatesNode.path("unused_balances").textValue(), giftCertificate.unusedBalances()); // GiftCertificateOption is tested in it's own test. Assert.assertNotNull(giftCertificate.options().get(0)); } @Test public void testSerializable() throws IOException, ClassNotFoundException { JsonNode giftCertificatesNode = JsonTestUtils.getBusinessResponseJsonNode().path("gift_certificates").get(0); GiftCertificate giftCertificate = JsonTestUtils.deserializeJson( giftCertificatesNode.toString(), GiftCertificate.class );
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // } // Path: src/test/java/com/yelp/clientlib/entities/GiftCertificateTest.java import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; package com.yelp.clientlib.entities; public class GiftCertificateTest { @Test public void testDeserializeFromJson() throws IOException { JsonNode giftCertificatesNode = JsonTestUtils.getBusinessResponseJsonNode().path("gift_certificates").get(0); GiftCertificate giftCertificate = JsonTestUtils.deserializeJson( giftCertificatesNode.toString(), GiftCertificate.class ); Assert.assertEquals(giftCertificatesNode.path("id").textValue(), giftCertificate.id()); Assert.assertEquals(giftCertificatesNode.path("url").textValue(), giftCertificate.url()); Assert.assertEquals(giftCertificatesNode.path("image_url").textValue(), giftCertificate.imageUrl()); Assert.assertEquals(giftCertificatesNode.path("currency_code").textValue(), giftCertificate.currencyCode()); Assert.assertEquals(giftCertificatesNode.path("unused_balances").textValue(), giftCertificate.unusedBalances()); // GiftCertificateOption is tested in it's own test. Assert.assertNotNull(giftCertificate.options().get(0)); } @Test public void testSerializable() throws IOException, ClassNotFoundException { JsonNode giftCertificatesNode = JsonTestUtils.getBusinessResponseJsonNode().path("gift_certificates").get(0); GiftCertificate giftCertificate = JsonTestUtils.deserializeJson( giftCertificatesNode.toString(), GiftCertificate.class );
byte[] bytes = SerializationTestUtils.serialize(giftCertificate);
Yelp/yelp-android
src/test/java/com/yelp/clientlib/entities/CoordinateTest.java
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException;
package com.yelp.clientlib.entities; public class CoordinateTest { @Test public void testDeserializeFromJson() throws IOException {
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // } // Path: src/test/java/com/yelp/clientlib/entities/CoordinateTest.java import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; package com.yelp.clientlib.entities; public class CoordinateTest { @Test public void testDeserializeFromJson() throws IOException {
JsonNode coordinateNode = JsonTestUtils.getBusinessResponseJsonNode().path("location").path("coordinate");
Yelp/yelp-android
src/test/java/com/yelp/clientlib/entities/CoordinateTest.java
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException;
package com.yelp.clientlib.entities; public class CoordinateTest { @Test public void testDeserializeFromJson() throws IOException { JsonNode coordinateNode = JsonTestUtils.getBusinessResponseJsonNode().path("location").path("coordinate"); Coordinate coordinate = JsonTestUtils.deserializeJson(coordinateNode.toString(), Coordinate.class); Assert.assertEquals(new Double(coordinateNode.path("latitude").asDouble()), coordinate.latitude()); Assert.assertEquals(new Double(coordinateNode.path("longitude").asDouble()), coordinate.longitude()); } @Test public void testSerializable() throws IOException, ClassNotFoundException { JsonNode coordinateNode = JsonTestUtils.getBusinessResponseJsonNode().path("location").path("coordinate"); Coordinate coordinate = JsonTestUtils.deserializeJson(coordinateNode.toString(), Coordinate.class);
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // } // Path: src/test/java/com/yelp/clientlib/entities/CoordinateTest.java import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; package com.yelp.clientlib.entities; public class CoordinateTest { @Test public void testDeserializeFromJson() throws IOException { JsonNode coordinateNode = JsonTestUtils.getBusinessResponseJsonNode().path("location").path("coordinate"); Coordinate coordinate = JsonTestUtils.deserializeJson(coordinateNode.toString(), Coordinate.class); Assert.assertEquals(new Double(coordinateNode.path("latitude").asDouble()), coordinate.latitude()); Assert.assertEquals(new Double(coordinateNode.path("longitude").asDouble()), coordinate.longitude()); } @Test public void testSerializable() throws IOException, ClassNotFoundException { JsonNode coordinateNode = JsonTestUtils.getBusinessResponseJsonNode().path("location").path("coordinate"); Coordinate coordinate = JsonTestUtils.deserializeJson(coordinateNode.toString(), Coordinate.class);
byte[] bytes = SerializationTestUtils.serialize(coordinate);
Yelp/yelp-android
src/test/java/com/yelp/clientlib/entities/UserTest.java
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException;
package com.yelp.clientlib.entities; public class UserTest { @Test public void testDeserializeFromJson() throws IOException {
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // } // Path: src/test/java/com/yelp/clientlib/entities/UserTest.java import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; package com.yelp.clientlib.entities; public class UserTest { @Test public void testDeserializeFromJson() throws IOException {
JsonNode userNode = JsonTestUtils.getBusinessResponseJsonNode().path("reviews").get(0).path("user");
Yelp/yelp-android
src/test/java/com/yelp/clientlib/entities/UserTest.java
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException;
package com.yelp.clientlib.entities; public class UserTest { @Test public void testDeserializeFromJson() throws IOException { JsonNode userNode = JsonTestUtils.getBusinessResponseJsonNode().path("reviews").get(0).path("user"); User user = JsonTestUtils.deserializeJson(userNode.toString(), User.class); Assert.assertEquals(userNode.path("id").textValue(), user.id()); Assert.assertEquals(userNode.path("image_url").textValue(), user.imageUrl()); Assert.assertEquals(userNode.path("name").textValue(), user.name()); } @Test public void testSerializable() throws IOException, ClassNotFoundException { JsonNode userNode = JsonTestUtils.getBusinessResponseJsonNode().path("reviews").get(0).path("user"); User user = JsonTestUtils.deserializeJson(userNode.toString(), User.class);
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // } // Path: src/test/java/com/yelp/clientlib/entities/UserTest.java import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; package com.yelp.clientlib.entities; public class UserTest { @Test public void testDeserializeFromJson() throws IOException { JsonNode userNode = JsonTestUtils.getBusinessResponseJsonNode().path("reviews").get(0).path("user"); User user = JsonTestUtils.deserializeJson(userNode.toString(), User.class); Assert.assertEquals(userNode.path("id").textValue(), user.id()); Assert.assertEquals(userNode.path("image_url").textValue(), user.imageUrl()); Assert.assertEquals(userNode.path("name").textValue(), user.name()); } @Test public void testSerializable() throws IOException, ClassNotFoundException { JsonNode userNode = JsonTestUtils.getBusinessResponseJsonNode().path("reviews").get(0).path("user"); User user = JsonTestUtils.deserializeJson(userNode.toString(), User.class);
byte[] bytes = SerializationTestUtils.serialize(user);
Yelp/yelp-android
src/main/java/com/yelp/clientlib/connection/YelpAPIFactory.java
// Path: src/main/java/com/yelp/clientlib/exception/ErrorHandlingInterceptor.java // public class ErrorHandlingInterceptor implements Interceptor { // // private static final ObjectMapper objectMapper = new ObjectMapper(); // // /** // * Intercept HTTP responses and raise a {@link YelpAPIError} if the response code is not 2xx. // * // * @param chain {@link okhttp3.Interceptor.Chain} object for sending the HTTP request. // * @return response // * @throws IOException {@link YelpAPIError} generated depends on the response error id. // */ // @Override // public Response intercept(Chain chain) throws IOException { // Response response = chain.proceed(chain.request()); // // if (!response.isSuccessful()) { // throw parseError( // response.code(), // response.message(), // response.body() != null ? response.body().string() : null // ); // } // return response; // } // // private YelpAPIError parseError(int code, String message, String responseBody) throws IOException { // if (responseBody == null) { // return new UnexpectedAPIError(code, message); // } // // JsonNode errorJsonNode = objectMapper.readTree(responseBody).path("error"); // String errorId = errorJsonNode.path("id").asText(); // String errorText = errorJsonNode.path("text").asText(); // // if (errorJsonNode.has("field")) { // errorText += ": " + errorJsonNode.path("field").asText(); // } // // switch (errorId) { // case "AREA_TOO_LARGE": // return new AreaTooLarge(code, message, errorId, errorText); // case "BAD_CATEGORY": // return new BadCategory(code, message, errorId, errorText); // case "BUSINESS_UNAVAILABLE": // return new BusinessUnavailable(code, message, errorId, errorText); // case "EXCEEDED_REQS": // return new ExceededReqs(code, message, errorId, errorText); // case "INTERNAL_ERROR": // return new InternalError(code, message, errorId, errorText); // case "INVALID_OAUTH_CREDENTIALS": // return new InvalidOAuthCredentials(code, message, errorId, errorText); // case "INVALID_OAUTH_USER": // return new InvalidOAuthUser(code, message, errorId, errorText); // case "INVALID_PARAMETER": // return new InvalidParameter(code, message, errorId, errorText); // case "INVALID_SIGNATURE": // return new InvalidSignature(code, message, errorId, errorText); // case "MISSING_PARAMETER": // return new MissingParameter(code, message, errorId, errorText); // case "MULTIPLE_LOCATIONS": // return new MultipleLocations(code, message, errorId, errorText); // case "SSL_REQUIRED": // return new SSLRequired(code, message, errorId, errorText); // case "UNAVAILABLE_FOR_LOCATION": // return new UnavailableForLocation(code, message, errorId, errorText); // case "UNSPECIFIED_LOCATION": // return new UnspecifiedLocation(code, message, errorId, errorText); // default: // return new UnexpectedAPIError(code, message, errorId, errorText); // } // } // }
import okhttp3.OkHttpClient; import com.yelp.clientlib.exception.ErrorHandlingInterceptor; import retrofit2.converter.jackson.JacksonConverterFactory; import retrofit2.Retrofit; import se.akerfeldt.okhttp.signpost.OkHttpOAuthConsumer; import se.akerfeldt.okhttp.signpost.SigningInterceptor;
package com.yelp.clientlib.connection; /** * Util class to create YelpAPI as the stub to use Yelp API. This is the entry point to use this clientlib. * <p> * Example:<br> * YelpAPIFactory apiFactory = new YelpAPIFactory(consumerKey, consumerSecret, token, tokenSecret);<br> * YelpAPI yelpAPI = apiFactory.createAPI();<br> * Business business = yelpAPI.getBusiness(businessId).execute(); * </p> */ public class YelpAPIFactory { private static final String YELP_API_BASE_URL = "https://api.yelp.com"; private OkHttpClient httpClient; /** * Construct a new {@code YelpAPIFactory}. * * @param consumerKey the consumer key. * @param consumerSecret the consumer secret. * @param token the access token. * @param tokenSecret the token secret. * @see <a href="https://www.yelp.com/developers/manage_api_keys">https://www.yelp.com/developers/manage_api_keys</a> */ public YelpAPIFactory(String consumerKey, String consumerSecret, String token, String tokenSecret) { OkHttpOAuthConsumer consumer = new OkHttpOAuthConsumer(consumerKey, consumerSecret); consumer.setTokenWithSecret(token, tokenSecret); this.httpClient = new OkHttpClient.Builder() .addInterceptor(new SigningInterceptor(consumer))
// Path: src/main/java/com/yelp/clientlib/exception/ErrorHandlingInterceptor.java // public class ErrorHandlingInterceptor implements Interceptor { // // private static final ObjectMapper objectMapper = new ObjectMapper(); // // /** // * Intercept HTTP responses and raise a {@link YelpAPIError} if the response code is not 2xx. // * // * @param chain {@link okhttp3.Interceptor.Chain} object for sending the HTTP request. // * @return response // * @throws IOException {@link YelpAPIError} generated depends on the response error id. // */ // @Override // public Response intercept(Chain chain) throws IOException { // Response response = chain.proceed(chain.request()); // // if (!response.isSuccessful()) { // throw parseError( // response.code(), // response.message(), // response.body() != null ? response.body().string() : null // ); // } // return response; // } // // private YelpAPIError parseError(int code, String message, String responseBody) throws IOException { // if (responseBody == null) { // return new UnexpectedAPIError(code, message); // } // // JsonNode errorJsonNode = objectMapper.readTree(responseBody).path("error"); // String errorId = errorJsonNode.path("id").asText(); // String errorText = errorJsonNode.path("text").asText(); // // if (errorJsonNode.has("field")) { // errorText += ": " + errorJsonNode.path("field").asText(); // } // // switch (errorId) { // case "AREA_TOO_LARGE": // return new AreaTooLarge(code, message, errorId, errorText); // case "BAD_CATEGORY": // return new BadCategory(code, message, errorId, errorText); // case "BUSINESS_UNAVAILABLE": // return new BusinessUnavailable(code, message, errorId, errorText); // case "EXCEEDED_REQS": // return new ExceededReqs(code, message, errorId, errorText); // case "INTERNAL_ERROR": // return new InternalError(code, message, errorId, errorText); // case "INVALID_OAUTH_CREDENTIALS": // return new InvalidOAuthCredentials(code, message, errorId, errorText); // case "INVALID_OAUTH_USER": // return new InvalidOAuthUser(code, message, errorId, errorText); // case "INVALID_PARAMETER": // return new InvalidParameter(code, message, errorId, errorText); // case "INVALID_SIGNATURE": // return new InvalidSignature(code, message, errorId, errorText); // case "MISSING_PARAMETER": // return new MissingParameter(code, message, errorId, errorText); // case "MULTIPLE_LOCATIONS": // return new MultipleLocations(code, message, errorId, errorText); // case "SSL_REQUIRED": // return new SSLRequired(code, message, errorId, errorText); // case "UNAVAILABLE_FOR_LOCATION": // return new UnavailableForLocation(code, message, errorId, errorText); // case "UNSPECIFIED_LOCATION": // return new UnspecifiedLocation(code, message, errorId, errorText); // default: // return new UnexpectedAPIError(code, message, errorId, errorText); // } // } // } // Path: src/main/java/com/yelp/clientlib/connection/YelpAPIFactory.java import okhttp3.OkHttpClient; import com.yelp.clientlib.exception.ErrorHandlingInterceptor; import retrofit2.converter.jackson.JacksonConverterFactory; import retrofit2.Retrofit; import se.akerfeldt.okhttp.signpost.OkHttpOAuthConsumer; import se.akerfeldt.okhttp.signpost.SigningInterceptor; package com.yelp.clientlib.connection; /** * Util class to create YelpAPI as the stub to use Yelp API. This is the entry point to use this clientlib. * <p> * Example:<br> * YelpAPIFactory apiFactory = new YelpAPIFactory(consumerKey, consumerSecret, token, tokenSecret);<br> * YelpAPI yelpAPI = apiFactory.createAPI();<br> * Business business = yelpAPI.getBusiness(businessId).execute(); * </p> */ public class YelpAPIFactory { private static final String YELP_API_BASE_URL = "https://api.yelp.com"; private OkHttpClient httpClient; /** * Construct a new {@code YelpAPIFactory}. * * @param consumerKey the consumer key. * @param consumerSecret the consumer secret. * @param token the access token. * @param tokenSecret the token secret. * @see <a href="https://www.yelp.com/developers/manage_api_keys">https://www.yelp.com/developers/manage_api_keys</a> */ public YelpAPIFactory(String consumerKey, String consumerSecret, String token, String tokenSecret) { OkHttpOAuthConsumer consumer = new OkHttpOAuthConsumer(consumerKey, consumerSecret); consumer.setTokenWithSecret(token, tokenSecret); this.httpClient = new OkHttpClient.Builder() .addInterceptor(new SigningInterceptor(consumer))
.addInterceptor(new ErrorHandlingInterceptor())
Yelp/yelp-android
src/test/java/com/yelp/clientlib/entities/DealOptionTest.java
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException;
package com.yelp.clientlib.entities; public class DealOptionTest { @Test public void testDeserializeFromJson() throws IOException {
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // } // Path: src/test/java/com/yelp/clientlib/entities/DealOptionTest.java import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; package com.yelp.clientlib.entities; public class DealOptionTest { @Test public void testDeserializeFromJson() throws IOException {
JsonNode dealOptionNode = JsonTestUtils.getBusinessResponseJsonNode()
Yelp/yelp-android
src/test/java/com/yelp/clientlib/entities/DealOptionTest.java
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException;
package com.yelp.clientlib.entities; public class DealOptionTest { @Test public void testDeserializeFromJson() throws IOException { JsonNode dealOptionNode = JsonTestUtils.getBusinessResponseJsonNode() .path("deals").get(0).path("options").get(0); DealOption dealOption = JsonTestUtils.deserializeJson(dealOptionNode.toString(), DealOption.class); Assert.assertEquals( dealOptionNode.path("formatted_original_price").textValue(), dealOption.formattedOriginalPrice() ); Assert.assertEquals(dealOptionNode.path("formatted_price").textValue(), dealOption.formattedPrice()); Assert.assertEquals(dealOptionNode.path("is_quantity_limited").asBoolean(), dealOption.isQuantityLimited()); Assert.assertEquals(new Integer(dealOptionNode.path("original_price").asInt()), dealOption.originalPrice()); Assert.assertEquals(new Integer(dealOptionNode.path("price").asInt()), dealOption.price()); Assert.assertEquals(dealOptionNode.path("purchase_url").textValue(), dealOption.purchaseUrl()); Assert.assertEquals(new Integer(dealOptionNode.path("remaining_count").asInt()), dealOption.remainingCount()); Assert.assertEquals(dealOptionNode.path("title").textValue(), dealOption.title()); } @Test public void testSerializable() throws IOException, ClassNotFoundException { JsonNode dealOptionNode = JsonTestUtils.getBusinessResponseJsonNode() .path("deals").get(0).path("options").get(0); DealOption dealOption = JsonTestUtils.deserializeJson(dealOptionNode.toString(), DealOption.class);
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // } // Path: src/test/java/com/yelp/clientlib/entities/DealOptionTest.java import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; package com.yelp.clientlib.entities; public class DealOptionTest { @Test public void testDeserializeFromJson() throws IOException { JsonNode dealOptionNode = JsonTestUtils.getBusinessResponseJsonNode() .path("deals").get(0).path("options").get(0); DealOption dealOption = JsonTestUtils.deserializeJson(dealOptionNode.toString(), DealOption.class); Assert.assertEquals( dealOptionNode.path("formatted_original_price").textValue(), dealOption.formattedOriginalPrice() ); Assert.assertEquals(dealOptionNode.path("formatted_price").textValue(), dealOption.formattedPrice()); Assert.assertEquals(dealOptionNode.path("is_quantity_limited").asBoolean(), dealOption.isQuantityLimited()); Assert.assertEquals(new Integer(dealOptionNode.path("original_price").asInt()), dealOption.originalPrice()); Assert.assertEquals(new Integer(dealOptionNode.path("price").asInt()), dealOption.price()); Assert.assertEquals(dealOptionNode.path("purchase_url").textValue(), dealOption.purchaseUrl()); Assert.assertEquals(new Integer(dealOptionNode.path("remaining_count").asInt()), dealOption.remainingCount()); Assert.assertEquals(dealOptionNode.path("title").textValue(), dealOption.title()); } @Test public void testSerializable() throws IOException, ClassNotFoundException { JsonNode dealOptionNode = JsonTestUtils.getBusinessResponseJsonNode() .path("deals").get(0).path("options").get(0); DealOption dealOption = JsonTestUtils.deserializeJson(dealOptionNode.toString(), DealOption.class);
byte[] bytes = SerializationTestUtils.serialize(dealOption);
Yelp/yelp-android
src/test/java/com/yelp/clientlib/utils/ErrorTestUtils.java
// Path: src/main/java/com/yelp/clientlib/exception/exceptions/YelpAPIError.java // public abstract class YelpAPIError extends IOException { // private int code; // private String message; // private String text; // private String errorId; // // public int getCode() { // return code; // } // // @Override // public String getMessage() { // return message; // } // // public String getText() { // return text; // } // // public String getErrorId() { // return errorId; // } // // public YelpAPIError(int code, String message, String errorId, String text) { // this.code = code; // this.message = message; // this.errorId = errorId; // this.text = text; // } // }
import com.yelp.clientlib.exception.exceptions.YelpAPIError; import org.junit.Assert;
package com.yelp.clientlib.utils; public class ErrorTestUtils { /** * Verify a {@link YelpAPIError} contains correct information. * * @param error The YelpAPIError to be verified. * @param expectCode Expected error code. * @param expectMessage Expected error message. * @param expectId Expected error Id. * @param expectText Expected error text. */ public static void verifyErrorContent(
// Path: src/main/java/com/yelp/clientlib/exception/exceptions/YelpAPIError.java // public abstract class YelpAPIError extends IOException { // private int code; // private String message; // private String text; // private String errorId; // // public int getCode() { // return code; // } // // @Override // public String getMessage() { // return message; // } // // public String getText() { // return text; // } // // public String getErrorId() { // return errorId; // } // // public YelpAPIError(int code, String message, String errorId, String text) { // this.code = code; // this.message = message; // this.errorId = errorId; // this.text = text; // } // } // Path: src/test/java/com/yelp/clientlib/utils/ErrorTestUtils.java import com.yelp.clientlib.exception.exceptions.YelpAPIError; import org.junit.Assert; package com.yelp.clientlib.utils; public class ErrorTestUtils { /** * Verify a {@link YelpAPIError} contains correct information. * * @param error The YelpAPIError to be verified. * @param expectCode Expected error code. * @param expectMessage Expected error message. * @param expectId Expected error Id. * @param expectText Expected error text. */ public static void verifyErrorContent(
YelpAPIError error,
Yelp/yelp-android
src/test/java/com/yelp/clientlib/entities/RegionTest.java
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException;
package com.yelp.clientlib.entities; public class RegionTest { @Test public void testDeserializeFromJson() throws IOException {
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // } // Path: src/test/java/com/yelp/clientlib/entities/RegionTest.java import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; package com.yelp.clientlib.entities; public class RegionTest { @Test public void testDeserializeFromJson() throws IOException {
JsonNode regionNode = JsonTestUtils.getSearchResponseJsonNode().path("region");
Yelp/yelp-android
src/test/java/com/yelp/clientlib/entities/RegionTest.java
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException;
package com.yelp.clientlib.entities; public class RegionTest { @Test public void testDeserializeFromJson() throws IOException { JsonNode regionNode = JsonTestUtils.getSearchResponseJsonNode().path("region"); Region region = JsonTestUtils.deserializeJson(regionNode.toString(), Region.class); // Coordinate and Span are tested in their own tests. Assert.assertNotNull(region.center()); Assert.assertNotNull(region.span()); } @Test public void testSerializable() throws IOException, ClassNotFoundException { JsonNode regionNode = JsonTestUtils.getSearchResponseJsonNode().path("region"); Region region = JsonTestUtils.deserializeJson(regionNode.toString(), Region.class);
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // } // Path: src/test/java/com/yelp/clientlib/entities/RegionTest.java import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; package com.yelp.clientlib.entities; public class RegionTest { @Test public void testDeserializeFromJson() throws IOException { JsonNode regionNode = JsonTestUtils.getSearchResponseJsonNode().path("region"); Region region = JsonTestUtils.deserializeJson(regionNode.toString(), Region.class); // Coordinate and Span are tested in their own tests. Assert.assertNotNull(region.center()); Assert.assertNotNull(region.span()); } @Test public void testSerializable() throws IOException, ClassNotFoundException { JsonNode regionNode = JsonTestUtils.getSearchResponseJsonNode().path("region"); Region region = JsonTestUtils.deserializeJson(regionNode.toString(), Region.class);
byte[] bytes = SerializationTestUtils.serialize(region);
Yelp/yelp-android
src/test/java/com/yelp/clientlib/entities/DealTest.java
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException;
package com.yelp.clientlib.entities; public class DealTest { @Test public void testDeserializeFromJson() throws IOException {
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // } // Path: src/test/java/com/yelp/clientlib/entities/DealTest.java import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; package com.yelp.clientlib.entities; public class DealTest { @Test public void testDeserializeFromJson() throws IOException {
JsonNode dealNode = JsonTestUtils.getBusinessResponseJsonNode().path("deals").get(0);
Yelp/yelp-android
src/test/java/com/yelp/clientlib/entities/DealTest.java
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException;
package com.yelp.clientlib.entities; public class DealTest { @Test public void testDeserializeFromJson() throws IOException { JsonNode dealNode = JsonTestUtils.getBusinessResponseJsonNode().path("deals").get(0); Deal deal = JsonTestUtils.deserializeJson(dealNode.toString(), Deal.class); Assert.assertNull(deal.additionalRestrictions()); Assert.assertEquals(dealNode.path("currency_code").textValue(), deal.currencyCode()); Assert.assertNull(deal.id()); Assert.assertEquals(dealNode.path("image_url").textValue(), deal.imageUrl()); Assert.assertNull(deal.importantRestrictions()); Assert.assertEquals(dealNode.path("is_popular").asBoolean(), deal.isPopular()); Assert.assertNotNull(deal.options().get(0)); Assert.assertNull(deal.timeEnd()); Assert.assertEquals(new Long(dealNode.path("time_start").asLong()), deal.timeStart()); Assert.assertEquals(dealNode.path("title").textValue(), deal.title()); Assert.assertEquals(dealNode.path("url").textValue(), deal.url()); Assert.assertNull(deal.whatYouGet()); } @Test public void testSerializable() throws IOException, ClassNotFoundException { JsonNode dealNode = JsonTestUtils.getBusinessResponseJsonNode().path("deals").get(0); Deal deal = JsonTestUtils.deserializeJson(dealNode.toString(), Deal.class);
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // } // Path: src/test/java/com/yelp/clientlib/entities/DealTest.java import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; package com.yelp.clientlib.entities; public class DealTest { @Test public void testDeserializeFromJson() throws IOException { JsonNode dealNode = JsonTestUtils.getBusinessResponseJsonNode().path("deals").get(0); Deal deal = JsonTestUtils.deserializeJson(dealNode.toString(), Deal.class); Assert.assertNull(deal.additionalRestrictions()); Assert.assertEquals(dealNode.path("currency_code").textValue(), deal.currencyCode()); Assert.assertNull(deal.id()); Assert.assertEquals(dealNode.path("image_url").textValue(), deal.imageUrl()); Assert.assertNull(deal.importantRestrictions()); Assert.assertEquals(dealNode.path("is_popular").asBoolean(), deal.isPopular()); Assert.assertNotNull(deal.options().get(0)); Assert.assertNull(deal.timeEnd()); Assert.assertEquals(new Long(dealNode.path("time_start").asLong()), deal.timeStart()); Assert.assertEquals(dealNode.path("title").textValue(), deal.title()); Assert.assertEquals(dealNode.path("url").textValue(), deal.url()); Assert.assertNull(deal.whatYouGet()); } @Test public void testSerializable() throws IOException, ClassNotFoundException { JsonNode dealNode = JsonTestUtils.getBusinessResponseJsonNode().path("deals").get(0); Deal deal = JsonTestUtils.deserializeJson(dealNode.toString(), Deal.class);
byte[] bytes = SerializationTestUtils.serialize(deal);
kapelner/bartMachine
src/bartMachine/bartMachineRegressionMultThread.java
// Path: src/OpenSourceExtensions/UnorderedPair.java // public final class UnorderedPair<E extends Comparable<E>> implements Comparable<UnorderedPair<E>> { // private final E first; // private final E second; // // /** // * Creates an unordered pair of the specified elements. The order of the arguments is irrelevant, // * so the first argument is not guaranteed to be returned by {@link #getFirst()}, for example. // * @param a one element of the pair. Must not be <tt>null</tt>. // * @param b one element of the pair. Must not be <tt>null</tt>. May be the same as <tt>a</tt>. // */ // public UnorderedPair(E a, E b) { // if (a.compareTo(b) < 0) { // this.first = a; // this.second = b; // } else { // this.first = b; // this.second = a; // } // } // // /** // * Gets the smallest element of the pair (according to its {@link Comparable} implementation). // * @return an element of the pair. <tt>null</tt> is never returned. // */ // public E getFirst() { // return first; // } // // /** // * Gets the largest element of the pair (according to its {@link Comparable} implementation). // * @return an element of the pair. <tt>null</tt> is never returned. // */ // public E getSecond() { // return second; // } // // @Override // public int hashCode() { // return 31 * first.hashCode() + 173 * second.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // UnorderedPair<?> other = (UnorderedPair<?>) obj; // if (!first.equals(other.first)) // return false; // if (!second.equals(other.second)) // return false; // return true; // } // // public int compareTo(UnorderedPair<E> o) { // int firstCmp = first.compareTo(o.first); // if (firstCmp != 0) // return firstCmp; // return second.compareTo(o.second); // } // // @Override // public String toString() { // return "(" + first + "," + second + ")"; // } // }
import gnu.trove.list.array.TDoubleArrayList; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import OpenSourceExtensions.UnorderedPair;
* Return the proportion of times each of the attributes were used (count over total number of splits) * during the construction of the sum-of-trees by Gibbs sample. * * @param type Either "splits" or "trees" ("splits" means total number and "trees" means sum of binary values of whether or not it has appeared in the tree) * @return The proportion of splits for all Gibbs samples further indexed by the attribute 1, ..., p */ public double[] getAttributeProps(final String type) { int[][] variable_counts_all_gibbs = getCountsForAllAttribute(type); double[] attribute_counts = new double[p]; for (int g = 0; g < num_gibbs_total_iterations - num_gibbs_burn_in; g++){ attribute_counts = Tools.add_arrays(attribute_counts, variable_counts_all_gibbs[g]); } Tools.normalize_array(attribute_counts); //will turn it into proportions return attribute_counts; } /** * For all Gibbs samples after burn in, calculate the set of interaction counts (consider a split on x_j * and a daughter node splits on x_k and that would be considered an "interaction") * * @return A matrix of size p x p where the row is top split and the column is a bottom split. It is recommended to triangularize the matrix after ignoring the order. */ public int[][] getInteractionCounts(){ int[][] interaction_count_matrix = new int[p][p]; for (int g = 0; g < gibbs_samples_of_bart_trees_after_burn_in.length; g++){ bartMachineTreeNode[] trees = gibbs_samples_of_bart_trees_after_burn_in[g]; for (bartMachineTreeNode tree : trees){ //get the set of pairs of interactions
// Path: src/OpenSourceExtensions/UnorderedPair.java // public final class UnorderedPair<E extends Comparable<E>> implements Comparable<UnorderedPair<E>> { // private final E first; // private final E second; // // /** // * Creates an unordered pair of the specified elements. The order of the arguments is irrelevant, // * so the first argument is not guaranteed to be returned by {@link #getFirst()}, for example. // * @param a one element of the pair. Must not be <tt>null</tt>. // * @param b one element of the pair. Must not be <tt>null</tt>. May be the same as <tt>a</tt>. // */ // public UnorderedPair(E a, E b) { // if (a.compareTo(b) < 0) { // this.first = a; // this.second = b; // } else { // this.first = b; // this.second = a; // } // } // // /** // * Gets the smallest element of the pair (according to its {@link Comparable} implementation). // * @return an element of the pair. <tt>null</tt> is never returned. // */ // public E getFirst() { // return first; // } // // /** // * Gets the largest element of the pair (according to its {@link Comparable} implementation). // * @return an element of the pair. <tt>null</tt> is never returned. // */ // public E getSecond() { // return second; // } // // @Override // public int hashCode() { // return 31 * first.hashCode() + 173 * second.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // UnorderedPair<?> other = (UnorderedPair<?>) obj; // if (!first.equals(other.first)) // return false; // if (!second.equals(other.second)) // return false; // return true; // } // // public int compareTo(UnorderedPair<E> o) { // int firstCmp = first.compareTo(o.first); // if (firstCmp != 0) // return firstCmp; // return second.compareTo(o.second); // } // // @Override // public String toString() { // return "(" + first + "," + second + ")"; // } // } // Path: src/bartMachine/bartMachineRegressionMultThread.java import gnu.trove.list.array.TDoubleArrayList; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import OpenSourceExtensions.UnorderedPair; * Return the proportion of times each of the attributes were used (count over total number of splits) * during the construction of the sum-of-trees by Gibbs sample. * * @param type Either "splits" or "trees" ("splits" means total number and "trees" means sum of binary values of whether or not it has appeared in the tree) * @return The proportion of splits for all Gibbs samples further indexed by the attribute 1, ..., p */ public double[] getAttributeProps(final String type) { int[][] variable_counts_all_gibbs = getCountsForAllAttribute(type); double[] attribute_counts = new double[p]; for (int g = 0; g < num_gibbs_total_iterations - num_gibbs_burn_in; g++){ attribute_counts = Tools.add_arrays(attribute_counts, variable_counts_all_gibbs[g]); } Tools.normalize_array(attribute_counts); //will turn it into proportions return attribute_counts; } /** * For all Gibbs samples after burn in, calculate the set of interaction counts (consider a split on x_j * and a daughter node splits on x_k and that would be considered an "interaction") * * @return A matrix of size p x p where the row is top split and the column is a bottom split. It is recommended to triangularize the matrix after ignoring the order. */ public int[][] getInteractionCounts(){ int[][] interaction_count_matrix = new int[p][p]; for (int g = 0; g < gibbs_samples_of_bart_trees_after_burn_in.length; g++){ bartMachineTreeNode[] trees = gibbs_samples_of_bart_trees_after_burn_in[g]; for (bartMachineTreeNode tree : trees){ //get the set of pairs of interactions
HashSet<UnorderedPair<Integer>> set_of_interaction_pairs = new HashSet<UnorderedPair<Integer>>(p * p);
nooone/gdx-vr
gdx-vr/src/com/badlogic/gdx/vr/VirtualRealityRenderer.java
// Path: gdx-vr/src/com/badlogic/gdx/vr/SplitViewport.java // public static class SizeInformation { // /** Determines, how the size should be interpreted. */ // public SizeType sizeType; // // /** // * The size to be used. Is ignored in case {@link SizeType} REST is // * used. // */ // public float size; // // public SizeInformation(SizeType sizeType, float size) { // this.sizeType = sizeType; // this.size = size; // } // } // // Path: gdx-vr/src/com/badlogic/gdx/vr/SplitViewport.java // public enum SizeType { // /** // * The size will be fixed and will have exactly the given size all the // * time. // */ // ABSOLUTE, // // /** // * The given size needs to be in [0, 1]. It is relative to the "root" // * viewport. // */ // RELATIVE, // // /** // * If this type is chosen, the given size will be ignored. Instead all // * cells with this type will share the rest amount of the "root" // * viewport that is still left after all other parts have been // * subtracted. // */ // REST // } // // Path: gdx-vr/src/com/badlogic/gdx/vr/SplitViewport.java // public static class SubView { // /** The size information for this sub view. */ // public SizeInformation sizeInformation; // // /** The {@link Viewport} for this sub view. */ // public Viewport viewport; // // public SubView(SizeInformation sizeInformation, Viewport viewport) { // this.sizeInformation = sizeInformation; // this.viewport = viewport; // } // // }
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.glutils.FrameBuffer; import com.badlogic.gdx.math.Quaternion; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.viewport.ScreenViewport; import com.badlogic.gdx.utils.viewport.Viewport; import com.badlogic.gdx.vr.SplitViewport.SizeInformation; import com.badlogic.gdx.vr.SplitViewport.SizeType; import com.badlogic.gdx.vr.SplitViewport.SubView;
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.vr; /** * @author Daniel Holderbaum */ public class VirtualRealityRenderer { public Array<VirtualRealityRenderListener> listeners = new Array<VirtualRealityRenderListener>(); private boolean distortionCorrected; private FrameBuffer leftFBO, rightFBO; private SplitViewport splitViewport = new SplitViewport(new ScreenViewport()); public VirtualRealityRenderer() {
// Path: gdx-vr/src/com/badlogic/gdx/vr/SplitViewport.java // public static class SizeInformation { // /** Determines, how the size should be interpreted. */ // public SizeType sizeType; // // /** // * The size to be used. Is ignored in case {@link SizeType} REST is // * used. // */ // public float size; // // public SizeInformation(SizeType sizeType, float size) { // this.sizeType = sizeType; // this.size = size; // } // } // // Path: gdx-vr/src/com/badlogic/gdx/vr/SplitViewport.java // public enum SizeType { // /** // * The size will be fixed and will have exactly the given size all the // * time. // */ // ABSOLUTE, // // /** // * The given size needs to be in [0, 1]. It is relative to the "root" // * viewport. // */ // RELATIVE, // // /** // * If this type is chosen, the given size will be ignored. Instead all // * cells with this type will share the rest amount of the "root" // * viewport that is still left after all other parts have been // * subtracted. // */ // REST // } // // Path: gdx-vr/src/com/badlogic/gdx/vr/SplitViewport.java // public static class SubView { // /** The size information for this sub view. */ // public SizeInformation sizeInformation; // // /** The {@link Viewport} for this sub view. */ // public Viewport viewport; // // public SubView(SizeInformation sizeInformation, Viewport viewport) { // this.sizeInformation = sizeInformation; // this.viewport = viewport; // } // // } // Path: gdx-vr/src/com/badlogic/gdx/vr/VirtualRealityRenderer.java import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.glutils.FrameBuffer; import com.badlogic.gdx.math.Quaternion; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.viewport.ScreenViewport; import com.badlogic.gdx.utils.viewport.Viewport; import com.badlogic.gdx.vr.SplitViewport.SizeInformation; import com.badlogic.gdx.vr.SplitViewport.SizeType; import com.badlogic.gdx.vr.SplitViewport.SubView; /******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.vr; /** * @author Daniel Holderbaum */ public class VirtualRealityRenderer { public Array<VirtualRealityRenderListener> listeners = new Array<VirtualRealityRenderListener>(); private boolean distortionCorrected; private FrameBuffer leftFBO, rightFBO; private SplitViewport splitViewport = new SplitViewport(new ScreenViewport()); public VirtualRealityRenderer() {
splitViewport.row(new SizeInformation(SizeType.RELATIVE, 1f));
nooone/gdx-vr
gdx-vr/src/com/badlogic/gdx/vr/VirtualRealityRenderer.java
// Path: gdx-vr/src/com/badlogic/gdx/vr/SplitViewport.java // public static class SizeInformation { // /** Determines, how the size should be interpreted. */ // public SizeType sizeType; // // /** // * The size to be used. Is ignored in case {@link SizeType} REST is // * used. // */ // public float size; // // public SizeInformation(SizeType sizeType, float size) { // this.sizeType = sizeType; // this.size = size; // } // } // // Path: gdx-vr/src/com/badlogic/gdx/vr/SplitViewport.java // public enum SizeType { // /** // * The size will be fixed and will have exactly the given size all the // * time. // */ // ABSOLUTE, // // /** // * The given size needs to be in [0, 1]. It is relative to the "root" // * viewport. // */ // RELATIVE, // // /** // * If this type is chosen, the given size will be ignored. Instead all // * cells with this type will share the rest amount of the "root" // * viewport that is still left after all other parts have been // * subtracted. // */ // REST // } // // Path: gdx-vr/src/com/badlogic/gdx/vr/SplitViewport.java // public static class SubView { // /** The size information for this sub view. */ // public SizeInformation sizeInformation; // // /** The {@link Viewport} for this sub view. */ // public Viewport viewport; // // public SubView(SizeInformation sizeInformation, Viewport viewport) { // this.sizeInformation = sizeInformation; // this.viewport = viewport; // } // // }
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.glutils.FrameBuffer; import com.badlogic.gdx.math.Quaternion; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.viewport.ScreenViewport; import com.badlogic.gdx.utils.viewport.Viewport; import com.badlogic.gdx.vr.SplitViewport.SizeInformation; import com.badlogic.gdx.vr.SplitViewport.SizeType; import com.badlogic.gdx.vr.SplitViewport.SubView;
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.vr; /** * @author Daniel Holderbaum */ public class VirtualRealityRenderer { public Array<VirtualRealityRenderListener> listeners = new Array<VirtualRealityRenderListener>(); private boolean distortionCorrected; private FrameBuffer leftFBO, rightFBO; private SplitViewport splitViewport = new SplitViewport(new ScreenViewport()); public VirtualRealityRenderer() {
// Path: gdx-vr/src/com/badlogic/gdx/vr/SplitViewport.java // public static class SizeInformation { // /** Determines, how the size should be interpreted. */ // public SizeType sizeType; // // /** // * The size to be used. Is ignored in case {@link SizeType} REST is // * used. // */ // public float size; // // public SizeInformation(SizeType sizeType, float size) { // this.sizeType = sizeType; // this.size = size; // } // } // // Path: gdx-vr/src/com/badlogic/gdx/vr/SplitViewport.java // public enum SizeType { // /** // * The size will be fixed and will have exactly the given size all the // * time. // */ // ABSOLUTE, // // /** // * The given size needs to be in [0, 1]. It is relative to the "root" // * viewport. // */ // RELATIVE, // // /** // * If this type is chosen, the given size will be ignored. Instead all // * cells with this type will share the rest amount of the "root" // * viewport that is still left after all other parts have been // * subtracted. // */ // REST // } // // Path: gdx-vr/src/com/badlogic/gdx/vr/SplitViewport.java // public static class SubView { // /** The size information for this sub view. */ // public SizeInformation sizeInformation; // // /** The {@link Viewport} for this sub view. */ // public Viewport viewport; // // public SubView(SizeInformation sizeInformation, Viewport viewport) { // this.sizeInformation = sizeInformation; // this.viewport = viewport; // } // // } // Path: gdx-vr/src/com/badlogic/gdx/vr/VirtualRealityRenderer.java import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.glutils.FrameBuffer; import com.badlogic.gdx.math.Quaternion; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.viewport.ScreenViewport; import com.badlogic.gdx.utils.viewport.Viewport; import com.badlogic.gdx.vr.SplitViewport.SizeInformation; import com.badlogic.gdx.vr.SplitViewport.SizeType; import com.badlogic.gdx.vr.SplitViewport.SubView; /******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.vr; /** * @author Daniel Holderbaum */ public class VirtualRealityRenderer { public Array<VirtualRealityRenderListener> listeners = new Array<VirtualRealityRenderListener>(); private boolean distortionCorrected; private FrameBuffer leftFBO, rightFBO; private SplitViewport splitViewport = new SplitViewport(new ScreenViewport()); public VirtualRealityRenderer() {
splitViewport.row(new SizeInformation(SizeType.RELATIVE, 1f));
nooone/gdx-vr
gdx-vr/src/com/badlogic/gdx/vr/VirtualRealityRenderer.java
// Path: gdx-vr/src/com/badlogic/gdx/vr/SplitViewport.java // public static class SizeInformation { // /** Determines, how the size should be interpreted. */ // public SizeType sizeType; // // /** // * The size to be used. Is ignored in case {@link SizeType} REST is // * used. // */ // public float size; // // public SizeInformation(SizeType sizeType, float size) { // this.sizeType = sizeType; // this.size = size; // } // } // // Path: gdx-vr/src/com/badlogic/gdx/vr/SplitViewport.java // public enum SizeType { // /** // * The size will be fixed and will have exactly the given size all the // * time. // */ // ABSOLUTE, // // /** // * The given size needs to be in [0, 1]. It is relative to the "root" // * viewport. // */ // RELATIVE, // // /** // * If this type is chosen, the given size will be ignored. Instead all // * cells with this type will share the rest amount of the "root" // * viewport that is still left after all other parts have been // * subtracted. // */ // REST // } // // Path: gdx-vr/src/com/badlogic/gdx/vr/SplitViewport.java // public static class SubView { // /** The size information for this sub view. */ // public SizeInformation sizeInformation; // // /** The {@link Viewport} for this sub view. */ // public Viewport viewport; // // public SubView(SizeInformation sizeInformation, Viewport viewport) { // this.sizeInformation = sizeInformation; // this.viewport = viewport; // } // // }
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.glutils.FrameBuffer; import com.badlogic.gdx.math.Quaternion; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.viewport.ScreenViewport; import com.badlogic.gdx.utils.viewport.Viewport; import com.badlogic.gdx.vr.SplitViewport.SizeInformation; import com.badlogic.gdx.vr.SplitViewport.SizeType; import com.badlogic.gdx.vr.SplitViewport.SubView;
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.vr; /** * @author Daniel Holderbaum */ public class VirtualRealityRenderer { public Array<VirtualRealityRenderListener> listeners = new Array<VirtualRealityRenderListener>(); private boolean distortionCorrected; private FrameBuffer leftFBO, rightFBO; private SplitViewport splitViewport = new SplitViewport(new ScreenViewport()); public VirtualRealityRenderer() { splitViewport.row(new SizeInformation(SizeType.RELATIVE, 1f));
// Path: gdx-vr/src/com/badlogic/gdx/vr/SplitViewport.java // public static class SizeInformation { // /** Determines, how the size should be interpreted. */ // public SizeType sizeType; // // /** // * The size to be used. Is ignored in case {@link SizeType} REST is // * used. // */ // public float size; // // public SizeInformation(SizeType sizeType, float size) { // this.sizeType = sizeType; // this.size = size; // } // } // // Path: gdx-vr/src/com/badlogic/gdx/vr/SplitViewport.java // public enum SizeType { // /** // * The size will be fixed and will have exactly the given size all the // * time. // */ // ABSOLUTE, // // /** // * The given size needs to be in [0, 1]. It is relative to the "root" // * viewport. // */ // RELATIVE, // // /** // * If this type is chosen, the given size will be ignored. Instead all // * cells with this type will share the rest amount of the "root" // * viewport that is still left after all other parts have been // * subtracted. // */ // REST // } // // Path: gdx-vr/src/com/badlogic/gdx/vr/SplitViewport.java // public static class SubView { // /** The size information for this sub view. */ // public SizeInformation sizeInformation; // // /** The {@link Viewport} for this sub view. */ // public Viewport viewport; // // public SubView(SizeInformation sizeInformation, Viewport viewport) { // this.sizeInformation = sizeInformation; // this.viewport = viewport; // } // // } // Path: gdx-vr/src/com/badlogic/gdx/vr/VirtualRealityRenderer.java import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.glutils.FrameBuffer; import com.badlogic.gdx.math.Quaternion; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.viewport.ScreenViewport; import com.badlogic.gdx.utils.viewport.Viewport; import com.badlogic.gdx.vr.SplitViewport.SizeInformation; import com.badlogic.gdx.vr.SplitViewport.SizeType; import com.badlogic.gdx.vr.SplitViewport.SubView; /******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.vr; /** * @author Daniel Holderbaum */ public class VirtualRealityRenderer { public Array<VirtualRealityRenderListener> listeners = new Array<VirtualRealityRenderListener>(); private boolean distortionCorrected; private FrameBuffer leftFBO, rightFBO; private SplitViewport splitViewport = new SplitViewport(new ScreenViewport()); public VirtualRealityRenderer() { splitViewport.row(new SizeInformation(SizeType.RELATIVE, 1f));
splitViewport.add(new SubView(new SizeInformation(SizeType.RELATIVE, 0.5f), VirtualReality.head.getLeftEye()));
nooone/gdx-vr
gdx-vr-simpleroom-core/src/com/badlogic/gdx/vr/simpleroom/SimpleRoom.java
// Path: gdx-vr/src/com/badlogic/gdx/vr/Stage3D.java // public class Stage3D extends Stage { // // private final Plane plane; // // // private final Vector2 offsetOnPlane; // // public Stage3D() { // super(); // this.plane = new Plane(new Vector3(0, 0, 1), Vector3.Zero); // } // // public Stage3D(Viewport viewport) { // super(viewport); // this.plane = new Plane(new Vector3(0, 0, 1), Vector3.Zero); // } // // public Stage3D(Viewport viewport, SpriteBatch batch) { // super(viewport, batch); // this.plane = new Plane(new Vector3(0, 0, 1), Vector3.Zero); // } // // public Stage3D(Plane plane, Viewport viewport, SpriteBatch batch) { // super(viewport, batch); // this.plane = plane; // } // // private static final Vector3 tmp = new Vector3(); // // @Override // public Vector2 screenToStageCoordinates(Vector2 screenCoords) { // Ray pickRay = getViewport().getPickRay(screenCoords.x, screenCoords.y); // Vector3 intersection = tmp; // if (Intersector.intersectRayPlane(pickRay, plane, intersection)) { // screenCoords.x = intersection.x; // screenCoords.y = intersection.y; // } else { // screenCoords.x = Float.MAX_VALUE; // screenCoords.y = Float.MAX_VALUE; // } // return screenCoords; // } // // @Override // public void calculateScissors(Rectangle localRect, Rectangle scissorRect) { // super.calculateScissors(localRect, scissorRect); // scissorRect.set(Float.MIN_VALUE, Float.MIN_VALUE, Float.MAX_VALUE, Float.MAX_VALUE); // } // // private static final Matrix4 transform = new Matrix4(); // // @Override // public void draw() { // transform.idt(); // transform.setToLookAt(plane.normal, Vector3.Z); // // TODO: no cpy() // transform.translate(plane.normal.cpy().nor().scl(plane.d)); // // getBatch().setTransformMatrix(transform); // // super.draw(); // } // // } // // Path: gdx-vr/src/com/badlogic/gdx/vr/VirtualReality.java // public class VirtualReality { // // public static HeadMountedDisplay headMountedDisplay; // // public static Head head; // // public static Body body; // // public static VirtualRealityRenderer renderer; // // static VirtualRealityImplementation implementation; // // static DistortionRenderer distortionRenderer; // // // TODO: remove from here and javadoc // public static void update(float deltaTime) { // implementation.update(deltaTime); // } // // } // // Path: gdx-vr/src/com/badlogic/gdx/vr/VirtualRealityRenderListener.java // public interface VirtualRealityRenderListener { // // /** // * This is called before any rendering is triggered. It can be implemented // * to clear the screen before each frame for example. // */ // void frameStarted(); // // /** // * This is called after the rendering of all eyes is finished. // */ // void frameEnded(); // // /** // * TODO: make this viewport, not camera. // * // * Called once or twice, depending on the settings of the renderer. // */ // void render(Camera camera); // // }
import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.shaders.DefaultShader; import com.badlogic.gdx.graphics.g3d.shaders.DefaultShader.Config; import com.badlogic.gdx.graphics.g3d.utils.DefaultShaderProvider; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.graphics.g3d.utils.ShaderProvider; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Quaternion; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.vr.Stage3D; import com.badlogic.gdx.vr.VirtualReality; import com.badlogic.gdx.vr.VirtualRealityRenderListener;
package com.badlogic.gdx.vr.simpleroom; public class SimpleRoom extends ApplicationAdapter implements VirtualRealityRenderListener { private ModelBatch modelBatch; private ModelInstance modelInstance; private ModelInstance ground; private AssetManager assets; private Environment environment;
// Path: gdx-vr/src/com/badlogic/gdx/vr/Stage3D.java // public class Stage3D extends Stage { // // private final Plane plane; // // // private final Vector2 offsetOnPlane; // // public Stage3D() { // super(); // this.plane = new Plane(new Vector3(0, 0, 1), Vector3.Zero); // } // // public Stage3D(Viewport viewport) { // super(viewport); // this.plane = new Plane(new Vector3(0, 0, 1), Vector3.Zero); // } // // public Stage3D(Viewport viewport, SpriteBatch batch) { // super(viewport, batch); // this.plane = new Plane(new Vector3(0, 0, 1), Vector3.Zero); // } // // public Stage3D(Plane plane, Viewport viewport, SpriteBatch batch) { // super(viewport, batch); // this.plane = plane; // } // // private static final Vector3 tmp = new Vector3(); // // @Override // public Vector2 screenToStageCoordinates(Vector2 screenCoords) { // Ray pickRay = getViewport().getPickRay(screenCoords.x, screenCoords.y); // Vector3 intersection = tmp; // if (Intersector.intersectRayPlane(pickRay, plane, intersection)) { // screenCoords.x = intersection.x; // screenCoords.y = intersection.y; // } else { // screenCoords.x = Float.MAX_VALUE; // screenCoords.y = Float.MAX_VALUE; // } // return screenCoords; // } // // @Override // public void calculateScissors(Rectangle localRect, Rectangle scissorRect) { // super.calculateScissors(localRect, scissorRect); // scissorRect.set(Float.MIN_VALUE, Float.MIN_VALUE, Float.MAX_VALUE, Float.MAX_VALUE); // } // // private static final Matrix4 transform = new Matrix4(); // // @Override // public void draw() { // transform.idt(); // transform.setToLookAt(plane.normal, Vector3.Z); // // TODO: no cpy() // transform.translate(plane.normal.cpy().nor().scl(plane.d)); // // getBatch().setTransformMatrix(transform); // // super.draw(); // } // // } // // Path: gdx-vr/src/com/badlogic/gdx/vr/VirtualReality.java // public class VirtualReality { // // public static HeadMountedDisplay headMountedDisplay; // // public static Head head; // // public static Body body; // // public static VirtualRealityRenderer renderer; // // static VirtualRealityImplementation implementation; // // static DistortionRenderer distortionRenderer; // // // TODO: remove from here and javadoc // public static void update(float deltaTime) { // implementation.update(deltaTime); // } // // } // // Path: gdx-vr/src/com/badlogic/gdx/vr/VirtualRealityRenderListener.java // public interface VirtualRealityRenderListener { // // /** // * This is called before any rendering is triggered. It can be implemented // * to clear the screen before each frame for example. // */ // void frameStarted(); // // /** // * This is called after the rendering of all eyes is finished. // */ // void frameEnded(); // // /** // * TODO: make this viewport, not camera. // * // * Called once or twice, depending on the settings of the renderer. // */ // void render(Camera camera); // // } // Path: gdx-vr-simpleroom-core/src/com/badlogic/gdx/vr/simpleroom/SimpleRoom.java import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.shaders.DefaultShader; import com.badlogic.gdx.graphics.g3d.shaders.DefaultShader.Config; import com.badlogic.gdx.graphics.g3d.utils.DefaultShaderProvider; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.graphics.g3d.utils.ShaderProvider; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Quaternion; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.vr.Stage3D; import com.badlogic.gdx.vr.VirtualReality; import com.badlogic.gdx.vr.VirtualRealityRenderListener; package com.badlogic.gdx.vr.simpleroom; public class SimpleRoom extends ApplicationAdapter implements VirtualRealityRenderListener { private ModelBatch modelBatch; private ModelInstance modelInstance; private ModelInstance ground; private AssetManager assets; private Environment environment;
private Stage3D stage;
nooone/gdx-vr
gdx-vr-simpleroom-ios/src/com/badlogic/gdx/vr/simpleroom/IOSLauncher.java
// Path: gdx-vr-simpleroom-core/src/com/badlogic/gdx/vr/simpleroom/SimpleRoom.java // public class SimpleRoom extends ApplicationAdapter implements VirtualRealityRenderListener { // // private ModelBatch modelBatch; // private ModelInstance modelInstance; // private ModelInstance ground; // private AssetManager assets; // private Environment environment; // private Stage3D stage; // // @Override // public void create() { // assets = new AssetManager(); // String model = "Bambo_House.g3db"; // assets.load(model, Model.class); // assets.finishLoading(); // modelInstance = new ModelInstance(assets.get(model, Model.class), new Matrix4().setToScaling(0.6f, 0.6f, 0.6f)); // // DefaultShader.Config config = new Config(); // config.defaultCullFace = GL20.GL_NONE; // ShaderProvider shaderProvider = new DefaultShaderProvider(config); // modelBatch = new ModelBatch(shaderProvider); // // ModelBuilder builder = new ModelBuilder(); // float groundSize = 1000f; // ground = new ModelInstance(builder.createRect(-groundSize, 0, groundSize, groundSize, 0, groundSize, groundSize, 0, -groundSize, -groundSize, 0, -groundSize, 0, // 1, 0, new Material(), Usage.Position | Usage.Normal), new Matrix4().setToTranslation(0, -0.01f, 0)); // environment = new Environment(); // environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); // environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); // // VirtualReality.renderer.listeners.add(this); // // VirtualReality.head.setCyclops(true); // } // // @Override // public void render() { // float deltaTime = Gdx.graphics.getDeltaTime(); // // if (Gdx.input.isKeyPressed(Input.Keys.W)) { // VirtualReality.body.position.add(new Vector3(0, 0, -2).mul(VirtualReality.body.orientation).scl(deltaTime)); // } // if (Gdx.input.isKeyPressed(Input.Keys.S)) { // VirtualReality.body.position.add(new Vector3(0, 0, 2).mul(VirtualReality.body.orientation).scl(deltaTime)); // } // if (Gdx.input.isKeyPressed(Input.Keys.A)) { // VirtualReality.body.orientation.mulLeft(new Quaternion(Vector3.Y, 90f * deltaTime)); // } // if (Gdx.input.isKeyPressed(Input.Keys.D)) { // VirtualReality.body.orientation.mulLeft(new Quaternion(Vector3.Y, -90f * deltaTime)); // } // // VirtualReality.update(Gdx.graphics.getDeltaTime()); // VirtualReality.renderer.render(); // } // // @Override // public void resize(int width, int height) { // // TODO: resize VirtualReality // } // // @Override // public void frameStarted() { // Gdx.gl.glClearColor(0, 0, 0, 1); // Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); // } // // @Override // public void frameEnded() { // } // // @Override // public void render(Camera camera) { // modelBatch.begin(camera); // modelBatch.render(ground, environment); // modelBatch.render(modelInstance, environment); // modelBatch.end(); // } // }
import org.robovm.apple.foundation.NSAutoreleasePool; import org.robovm.apple.uikit.UIApplication; import com.badlogic.gdx.backends.iosrobovm.IOSApplication; import com.badlogic.gdx.backends.iosrobovm.IOSApplicationConfiguration; import com.badlogic.gdx.vr.simpleroom.SimpleRoom;
package com.badlogic.gdx.vr.simpleroom; public class IOSLauncher extends IOSApplication.Delegate { @Override protected IOSApplication createApplication() { IOSApplicationConfiguration config = new IOSApplicationConfiguration();
// Path: gdx-vr-simpleroom-core/src/com/badlogic/gdx/vr/simpleroom/SimpleRoom.java // public class SimpleRoom extends ApplicationAdapter implements VirtualRealityRenderListener { // // private ModelBatch modelBatch; // private ModelInstance modelInstance; // private ModelInstance ground; // private AssetManager assets; // private Environment environment; // private Stage3D stage; // // @Override // public void create() { // assets = new AssetManager(); // String model = "Bambo_House.g3db"; // assets.load(model, Model.class); // assets.finishLoading(); // modelInstance = new ModelInstance(assets.get(model, Model.class), new Matrix4().setToScaling(0.6f, 0.6f, 0.6f)); // // DefaultShader.Config config = new Config(); // config.defaultCullFace = GL20.GL_NONE; // ShaderProvider shaderProvider = new DefaultShaderProvider(config); // modelBatch = new ModelBatch(shaderProvider); // // ModelBuilder builder = new ModelBuilder(); // float groundSize = 1000f; // ground = new ModelInstance(builder.createRect(-groundSize, 0, groundSize, groundSize, 0, groundSize, groundSize, 0, -groundSize, -groundSize, 0, -groundSize, 0, // 1, 0, new Material(), Usage.Position | Usage.Normal), new Matrix4().setToTranslation(0, -0.01f, 0)); // environment = new Environment(); // environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); // environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); // // VirtualReality.renderer.listeners.add(this); // // VirtualReality.head.setCyclops(true); // } // // @Override // public void render() { // float deltaTime = Gdx.graphics.getDeltaTime(); // // if (Gdx.input.isKeyPressed(Input.Keys.W)) { // VirtualReality.body.position.add(new Vector3(0, 0, -2).mul(VirtualReality.body.orientation).scl(deltaTime)); // } // if (Gdx.input.isKeyPressed(Input.Keys.S)) { // VirtualReality.body.position.add(new Vector3(0, 0, 2).mul(VirtualReality.body.orientation).scl(deltaTime)); // } // if (Gdx.input.isKeyPressed(Input.Keys.A)) { // VirtualReality.body.orientation.mulLeft(new Quaternion(Vector3.Y, 90f * deltaTime)); // } // if (Gdx.input.isKeyPressed(Input.Keys.D)) { // VirtualReality.body.orientation.mulLeft(new Quaternion(Vector3.Y, -90f * deltaTime)); // } // // VirtualReality.update(Gdx.graphics.getDeltaTime()); // VirtualReality.renderer.render(); // } // // @Override // public void resize(int width, int height) { // // TODO: resize VirtualReality // } // // @Override // public void frameStarted() { // Gdx.gl.glClearColor(0, 0, 0, 1); // Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); // } // // @Override // public void frameEnded() { // } // // @Override // public void render(Camera camera) { // modelBatch.begin(camera); // modelBatch.render(ground, environment); // modelBatch.render(modelInstance, environment); // modelBatch.end(); // } // } // Path: gdx-vr-simpleroom-ios/src/com/badlogic/gdx/vr/simpleroom/IOSLauncher.java import org.robovm.apple.foundation.NSAutoreleasePool; import org.robovm.apple.uikit.UIApplication; import com.badlogic.gdx.backends.iosrobovm.IOSApplication; import com.badlogic.gdx.backends.iosrobovm.IOSApplicationConfiguration; import com.badlogic.gdx.vr.simpleroom.SimpleRoom; package com.badlogic.gdx.vr.simpleroom; public class IOSLauncher extends IOSApplication.Delegate { @Override protected IOSApplication createApplication() { IOSApplicationConfiguration config = new IOSApplicationConfiguration();
return new IOSApplication(new SimpleRoom(), config);
SecUSo/privacy-friendly-pedometer
app/src/main/java/org/secuso/privacyfriendlyactivitytracker/persistence/TrainingPersistenceHelper.java
// Path: app/src/main/java/org/secuso/privacyfriendlyactivitytracker/models/Training.java // public class Training { // private long id; // private String name; // private String description; // private double steps; // private double distance; // private double calories; // private float feeling; // private long start; // private long end; // /** // * The view type for TrainingOverviewAdapter // */ // private int viewType = TrainingOverviewAdapter.VIEW_TYPE_TRAINING_SESSION; // // public static Training from(Cursor c) { // Training trainingSession = new Training(); // trainingSession.setId(c.getLong(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry._ID))); // trainingSession.setName(c.getString(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_NAME))); // trainingSession.setDescription(c.getString(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_DESCRIPTION))); // trainingSession.setSteps(c.getInt(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_STEPS))); // trainingSession.setDistance(c.getDouble(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_DISTANCE))); // trainingSession.setCalories(c.getDouble(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_CALORIES))); // trainingSession.setFeeling(c.getFloat(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_FEELING))); // trainingSession.setStart(c.getLong(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_START))); // trainingSession.setEnd(c.getLong(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_END))); // return trainingSession; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public double getSteps() { // return steps; // } // // public void setSteps(double steps) { // this.steps = steps; // } // // public double getDistance() { // return distance; // } // // public void setDistance(double distance) { // this.distance = distance; // } // // public double getCalories() { // return calories; // } // // public void setCalories(double calories) { // this.calories = calories; // } // // public float getFeeling() { // return feeling; // } // // public void setFeeling(float feeling) { // this.feeling = feeling; // } // // public long getStart() { // return start; // } // // public void setStart(long start) { // this.start = start; // } // // public long getEnd() { // return end; // } // // public void setEnd(long end) { // this.end = end; // } // // public int getViewType() { // return viewType; // } // // public void setViewType(int viewType) { // this.viewType = viewType; // } // // /** // * Returns the duration in seconds // * @return seconds // */ // public int getDuration(){ // long end = this.getEnd(); // if(end == 0){ // end = Calendar.getInstance().getTimeInMillis(); // } // return (Double.valueOf((end - this.getStart())/1000)).intValue(); // } // // /** // * Returns the velocity in meters per second // * @return m/s // */ // public double getVelocity(){ // if(this.getDuration() == 0){ // return 0; // } // return this.getDistance()/this.getDuration(); // } // // public ContentValues toContentValues() { // ContentValues values = new ContentValues(); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_NAME, this.getName()); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_DESCRIPTION, this.getDescription()); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_STEPS, this.getSteps()); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_DISTANCE, String.valueOf(this.getDistance())); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_CALORIES, String.valueOf(this.getCalories())); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_FEELING, String.valueOf(this.getFeeling())); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_START, String.valueOf(this.getStart())); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_END, String.valueOf(this.getEnd())); // return values; // } // }
import android.content.Context; import org.secuso.privacyfriendlyactivitytracker.models.Training; import java.util.List;
/* Privacy Friendly Pedometer is licensed under the GPLv3. Copyright (C) 2017 Tobias Neidig This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.secuso.privacyfriendlyactivitytracker.persistence; /** * Helper to save and restore training sessions from database. * * @author Tobias Neidig * @version 20170810 */ public class TrainingPersistenceHelper { public static final String LOG_CLASS = TrainingPersistenceHelper.class.getName(); /** * @deprecated Use {@link TrainingDbHelper#getAllTrainings()} instead. * * Gets all training sessions from database * * @param context The application context * @return a list of training sessions */
// Path: app/src/main/java/org/secuso/privacyfriendlyactivitytracker/models/Training.java // public class Training { // private long id; // private String name; // private String description; // private double steps; // private double distance; // private double calories; // private float feeling; // private long start; // private long end; // /** // * The view type for TrainingOverviewAdapter // */ // private int viewType = TrainingOverviewAdapter.VIEW_TYPE_TRAINING_SESSION; // // public static Training from(Cursor c) { // Training trainingSession = new Training(); // trainingSession.setId(c.getLong(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry._ID))); // trainingSession.setName(c.getString(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_NAME))); // trainingSession.setDescription(c.getString(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_DESCRIPTION))); // trainingSession.setSteps(c.getInt(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_STEPS))); // trainingSession.setDistance(c.getDouble(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_DISTANCE))); // trainingSession.setCalories(c.getDouble(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_CALORIES))); // trainingSession.setFeeling(c.getFloat(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_FEELING))); // trainingSession.setStart(c.getLong(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_START))); // trainingSession.setEnd(c.getLong(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_END))); // return trainingSession; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public double getSteps() { // return steps; // } // // public void setSteps(double steps) { // this.steps = steps; // } // // public double getDistance() { // return distance; // } // // public void setDistance(double distance) { // this.distance = distance; // } // // public double getCalories() { // return calories; // } // // public void setCalories(double calories) { // this.calories = calories; // } // // public float getFeeling() { // return feeling; // } // // public void setFeeling(float feeling) { // this.feeling = feeling; // } // // public long getStart() { // return start; // } // // public void setStart(long start) { // this.start = start; // } // // public long getEnd() { // return end; // } // // public void setEnd(long end) { // this.end = end; // } // // public int getViewType() { // return viewType; // } // // public void setViewType(int viewType) { // this.viewType = viewType; // } // // /** // * Returns the duration in seconds // * @return seconds // */ // public int getDuration(){ // long end = this.getEnd(); // if(end == 0){ // end = Calendar.getInstance().getTimeInMillis(); // } // return (Double.valueOf((end - this.getStart())/1000)).intValue(); // } // // /** // * Returns the velocity in meters per second // * @return m/s // */ // public double getVelocity(){ // if(this.getDuration() == 0){ // return 0; // } // return this.getDistance()/this.getDuration(); // } // // public ContentValues toContentValues() { // ContentValues values = new ContentValues(); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_NAME, this.getName()); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_DESCRIPTION, this.getDescription()); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_STEPS, this.getSteps()); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_DISTANCE, String.valueOf(this.getDistance())); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_CALORIES, String.valueOf(this.getCalories())); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_FEELING, String.valueOf(this.getFeeling())); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_START, String.valueOf(this.getStart())); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_END, String.valueOf(this.getEnd())); // return values; // } // } // Path: app/src/main/java/org/secuso/privacyfriendlyactivitytracker/persistence/TrainingPersistenceHelper.java import android.content.Context; import org.secuso.privacyfriendlyactivitytracker.models.Training; import java.util.List; /* Privacy Friendly Pedometer is licensed under the GPLv3. Copyright (C) 2017 Tobias Neidig This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.secuso.privacyfriendlyactivitytracker.persistence; /** * Helper to save and restore training sessions from database. * * @author Tobias Neidig * @version 20170810 */ public class TrainingPersistenceHelper { public static final String LOG_CLASS = TrainingPersistenceHelper.class.getName(); /** * @deprecated Use {@link TrainingDbHelper#getAllTrainings()} instead. * * Gets all training sessions from database * * @param context The application context * @return a list of training sessions */
public static List<Training> getAllItems(Context context) {
SecUSo/privacy-friendly-pedometer
app/src/main/java/org/secuso/privacyfriendlyactivitytracker/persistence/StepCountDbHelper.java
// Path: app/src/main/java/org/secuso/privacyfriendlyactivitytracker/models/StepCount.java // public class StepCount { // // // from https://github.com/bagilevi/android-pedometer/blob/master/src/name/bagi/levente/pedometer/CaloriesNotifier.java // private static double METRIC_RUNNING_FACTOR = 1.02784823; // private static double METRIC_WALKING_FACTOR = 0.708; // private static double METRIC_AVG_FACTOR = (METRIC_RUNNING_FACTOR + METRIC_WALKING_FACTOR) / 2; // // // private int stepCount; // private long startTime; // private long endTime; // private WalkingMode walkingMode; // // public int getStepCount() { // return stepCount; // } // // public void setStepCount(int stepCount) { // this.stepCount = stepCount; // } // // public long getStartTime() { // return startTime; // } // // public void setStartTime(long startTime) { // this.startTime = startTime; // } // // public long getEndTime() { // return endTime; // } // // public void setEndTime(long endTime) { // this.endTime = endTime; // } // // public WalkingMode getWalkingMode() { // return walkingMode; // } // // public void setWalkingMode(WalkingMode walkingMode) { // this.walkingMode = walkingMode; // } // // /** // * Gets the distance walked in this interval. // * // * @return The distance in meters // */ // public double getDistance(){ // if(getWalkingMode() != null) { // return getStepCount() * getWalkingMode().getStepLength(); // }else{ // return 0; // } // } // // /** // * Gets the calories // * @return the calories in cal // */ // public double getCalories(Context context){ // // inspired by https://github.com/bagilevi/android-pedometer/blob/master/src/name/bagi/levente/pedometer/CaloriesNotifier.java // SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context); // float bodyWeight = Float.parseFloat(sharedPref.getString(context.getString(R.string.pref_weight),context.getString(R.string.pref_default_weight))); // return bodyWeight * METRIC_AVG_FACTOR * UnitHelper.metersToKilometers(getDistance()); // } // @Override // public String toString() { // SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyy HH:mm:ss"); // return "StepCount{" + format.format(new Date(startTime)) + // " - " + format.format(new Date(endTime)) + // ": " + stepCount + " @ " + ((walkingMode == null) ? -1 : walkingMode.getId())+ // '}'; // } // }
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; import org.secuso.privacyfriendlyactivitytracker.models.StepCount; import java.util.ArrayList; import java.util.List;
*/ private static SQLiteDatabase getDatabase(StepCountDbHelper instance){ if(db == null){ db = instance.getWritableDatabase(); } return db; } public static void invalidateReference(){ db = null; } public StepCountDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); this.context = context; } public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE_ENTRIES); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Fill when upgrading DB } public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } /** * Stores the given StepCount in database. EndTime will be used for KEY_TIMESTAMP. * @param stepCount the StepCount to save. */
// Path: app/src/main/java/org/secuso/privacyfriendlyactivitytracker/models/StepCount.java // public class StepCount { // // // from https://github.com/bagilevi/android-pedometer/blob/master/src/name/bagi/levente/pedometer/CaloriesNotifier.java // private static double METRIC_RUNNING_FACTOR = 1.02784823; // private static double METRIC_WALKING_FACTOR = 0.708; // private static double METRIC_AVG_FACTOR = (METRIC_RUNNING_FACTOR + METRIC_WALKING_FACTOR) / 2; // // // private int stepCount; // private long startTime; // private long endTime; // private WalkingMode walkingMode; // // public int getStepCount() { // return stepCount; // } // // public void setStepCount(int stepCount) { // this.stepCount = stepCount; // } // // public long getStartTime() { // return startTime; // } // // public void setStartTime(long startTime) { // this.startTime = startTime; // } // // public long getEndTime() { // return endTime; // } // // public void setEndTime(long endTime) { // this.endTime = endTime; // } // // public WalkingMode getWalkingMode() { // return walkingMode; // } // // public void setWalkingMode(WalkingMode walkingMode) { // this.walkingMode = walkingMode; // } // // /** // * Gets the distance walked in this interval. // * // * @return The distance in meters // */ // public double getDistance(){ // if(getWalkingMode() != null) { // return getStepCount() * getWalkingMode().getStepLength(); // }else{ // return 0; // } // } // // /** // * Gets the calories // * @return the calories in cal // */ // public double getCalories(Context context){ // // inspired by https://github.com/bagilevi/android-pedometer/blob/master/src/name/bagi/levente/pedometer/CaloriesNotifier.java // SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context); // float bodyWeight = Float.parseFloat(sharedPref.getString(context.getString(R.string.pref_weight),context.getString(R.string.pref_default_weight))); // return bodyWeight * METRIC_AVG_FACTOR * UnitHelper.metersToKilometers(getDistance()); // } // @Override // public String toString() { // SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyy HH:mm:ss"); // return "StepCount{" + format.format(new Date(startTime)) + // " - " + format.format(new Date(endTime)) + // ": " + stepCount + " @ " + ((walkingMode == null) ? -1 : walkingMode.getId())+ // '}'; // } // } // Path: app/src/main/java/org/secuso/privacyfriendlyactivitytracker/persistence/StepCountDbHelper.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; import org.secuso.privacyfriendlyactivitytracker.models.StepCount; import java.util.ArrayList; import java.util.List; */ private static SQLiteDatabase getDatabase(StepCountDbHelper instance){ if(db == null){ db = instance.getWritableDatabase(); } return db; } public static void invalidateReference(){ db = null; } public StepCountDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); this.context = context; } public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE_ENTRIES); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Fill when upgrading DB } public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } /** * Stores the given StepCount in database. EndTime will be used for KEY_TIMESTAMP. * @param stepCount the StepCount to save. */
public void addStepCount(StepCount stepCount){
SecUSo/privacy-friendly-pedometer
app/src/main/java/org/secuso/privacyfriendlyactivitytracker/persistence/WalkingModePersistenceHelper.java
// Path: app/src/main/java/org/secuso/privacyfriendlyactivitytracker/models/WalkingMode.java // public class WalkingMode { // private long id; // private String name; // private double stepLength; // private double stepFrequency; // private boolean is_active; // private boolean is_deleted; // // public static WalkingMode from(Cursor c) { // WalkingMode alarmItem = new WalkingMode(); // alarmItem.setId(c.getLong(c.getColumnIndex(WalkingModeDbHelper.WalkingModeEntry._ID))); // alarmItem.setName(c.getString(c.getColumnIndex(WalkingModeDbHelper.WalkingModeEntry.KEY_NAME))); // alarmItem.setStepLength(c.getDouble(c.getColumnIndex(WalkingModeDbHelper.WalkingModeEntry.KEY_STEP_SIZE))); // alarmItem.setStepFrequency(c.getDouble(c.getColumnIndex(WalkingModeDbHelper.WalkingModeEntry.KEY_STEP_FREQUENCY))); // alarmItem.setIsActive(Boolean.valueOf(c.getString(c.getColumnIndex(WalkingModeDbHelper.WalkingModeEntry.KEY_IS_ACTIVE)))); // alarmItem.setIsDeleted(Boolean.valueOf(c.getString(c.getColumnIndex(WalkingModeDbHelper.WalkingModeEntry.KEY_IS_DELETED)))); // return alarmItem; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public double getStepLength() { // return stepLength; // } // // public void setStepLength(double stepLength) { // this.stepLength = stepLength; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public double getStepFrequency() { // return stepFrequency; // } // // public void setStepFrequency(double stepFrequency) { // this.stepFrequency = stepFrequency; // } // // public boolean isActive() { // return is_active; // } // // public void setIsActive(boolean is_active) { // this.is_active = is_active; // } // // public boolean isDeleted() { // return is_deleted; // } // // public void setIsDeleted(boolean is_deleted) { // this.is_deleted = is_deleted; // } // // public ContentValues toContentValues() { // ContentValues values = new ContentValues(); // values.put(WalkingModeDbHelper.WalkingModeEntry.KEY_NAME, this.getName()); // values.put(WalkingModeDbHelper.WalkingModeEntry.KEY_STEP_SIZE, this.getStepLength()); // values.put(WalkingModeDbHelper.WalkingModeEntry.KEY_STEP_FREQUENCY, this.getStepFrequency()); // values.put(WalkingModeDbHelper.WalkingModeEntry.KEY_IS_ACTIVE, String.valueOf(this.isActive())); // values.put(WalkingModeDbHelper.WalkingModeEntry.KEY_IS_DELETED, String.valueOf(this.isDeleted())); // return values; // } // // @Override // public String toString() { // return "WalkingMode{" + // "id=" + id + // ", stepLength=" + stepLength + // ", name='" + name + '\'' + // '}'; // } // // // /** // * @return the walking-mode-specific color // */ // public int getColor() { // return ColorHelper.getMaterialColor(this.getId() + this.getName()); // } // // }
import android.content.Context; import android.content.Intent; import android.util.Log; import org.secuso.privacyfriendlyactivitytracker.models.WalkingMode; import java.util.List;
/* Privacy Friendly Pedometer is licensed under the GPLv3. Copyright (C) 2017 Tobias Neidig This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.secuso.privacyfriendlyactivitytracker.persistence; /** * Helper to save and restore walking modes from database. * * @author Tobias Neidig * @version 20170810 */ public class WalkingModePersistenceHelper { /** * Broadcast action identifier for messages broadcast when walking mode changed */ public static final String BROADCAST_ACTION_WALKING_MODE_CHANGED = "org.secuso.privacyfriendlystepcounter.WALKING_MODE_CHANGED"; public static final String BROADCAST_EXTRA_OLD_WALKING_MODE = "org.secuso.privacyfriendlystepcounter.EXTRA_OLD_WALKING_MODE"; public static final String BROADCAST_EXTRA_NEW_WALKING_MODE = "org.secuso.privacyfriendlystepcounter.EXTRA_NEW_WALKING_MODE"; public static final String LOG_CLASS = WalkingModePersistenceHelper.class.getName(); /** * @deprecated Use {@link WalkingModeDbHelper#getAllWalkingModes()} instead. * * Gets all not deleted walking modes from database * * @param context The application context * @return a list of walking modes */
// Path: app/src/main/java/org/secuso/privacyfriendlyactivitytracker/models/WalkingMode.java // public class WalkingMode { // private long id; // private String name; // private double stepLength; // private double stepFrequency; // private boolean is_active; // private boolean is_deleted; // // public static WalkingMode from(Cursor c) { // WalkingMode alarmItem = new WalkingMode(); // alarmItem.setId(c.getLong(c.getColumnIndex(WalkingModeDbHelper.WalkingModeEntry._ID))); // alarmItem.setName(c.getString(c.getColumnIndex(WalkingModeDbHelper.WalkingModeEntry.KEY_NAME))); // alarmItem.setStepLength(c.getDouble(c.getColumnIndex(WalkingModeDbHelper.WalkingModeEntry.KEY_STEP_SIZE))); // alarmItem.setStepFrequency(c.getDouble(c.getColumnIndex(WalkingModeDbHelper.WalkingModeEntry.KEY_STEP_FREQUENCY))); // alarmItem.setIsActive(Boolean.valueOf(c.getString(c.getColumnIndex(WalkingModeDbHelper.WalkingModeEntry.KEY_IS_ACTIVE)))); // alarmItem.setIsDeleted(Boolean.valueOf(c.getString(c.getColumnIndex(WalkingModeDbHelper.WalkingModeEntry.KEY_IS_DELETED)))); // return alarmItem; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public double getStepLength() { // return stepLength; // } // // public void setStepLength(double stepLength) { // this.stepLength = stepLength; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public double getStepFrequency() { // return stepFrequency; // } // // public void setStepFrequency(double stepFrequency) { // this.stepFrequency = stepFrequency; // } // // public boolean isActive() { // return is_active; // } // // public void setIsActive(boolean is_active) { // this.is_active = is_active; // } // // public boolean isDeleted() { // return is_deleted; // } // // public void setIsDeleted(boolean is_deleted) { // this.is_deleted = is_deleted; // } // // public ContentValues toContentValues() { // ContentValues values = new ContentValues(); // values.put(WalkingModeDbHelper.WalkingModeEntry.KEY_NAME, this.getName()); // values.put(WalkingModeDbHelper.WalkingModeEntry.KEY_STEP_SIZE, this.getStepLength()); // values.put(WalkingModeDbHelper.WalkingModeEntry.KEY_STEP_FREQUENCY, this.getStepFrequency()); // values.put(WalkingModeDbHelper.WalkingModeEntry.KEY_IS_ACTIVE, String.valueOf(this.isActive())); // values.put(WalkingModeDbHelper.WalkingModeEntry.KEY_IS_DELETED, String.valueOf(this.isDeleted())); // return values; // } // // @Override // public String toString() { // return "WalkingMode{" + // "id=" + id + // ", stepLength=" + stepLength + // ", name='" + name + '\'' + // '}'; // } // // // /** // * @return the walking-mode-specific color // */ // public int getColor() { // return ColorHelper.getMaterialColor(this.getId() + this.getName()); // } // // } // Path: app/src/main/java/org/secuso/privacyfriendlyactivitytracker/persistence/WalkingModePersistenceHelper.java import android.content.Context; import android.content.Intent; import android.util.Log; import org.secuso.privacyfriendlyactivitytracker.models.WalkingMode; import java.util.List; /* Privacy Friendly Pedometer is licensed under the GPLv3. Copyright (C) 2017 Tobias Neidig This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.secuso.privacyfriendlyactivitytracker.persistence; /** * Helper to save and restore walking modes from database. * * @author Tobias Neidig * @version 20170810 */ public class WalkingModePersistenceHelper { /** * Broadcast action identifier for messages broadcast when walking mode changed */ public static final String BROADCAST_ACTION_WALKING_MODE_CHANGED = "org.secuso.privacyfriendlystepcounter.WALKING_MODE_CHANGED"; public static final String BROADCAST_EXTRA_OLD_WALKING_MODE = "org.secuso.privacyfriendlystepcounter.EXTRA_OLD_WALKING_MODE"; public static final String BROADCAST_EXTRA_NEW_WALKING_MODE = "org.secuso.privacyfriendlystepcounter.EXTRA_NEW_WALKING_MODE"; public static final String LOG_CLASS = WalkingModePersistenceHelper.class.getName(); /** * @deprecated Use {@link WalkingModeDbHelper#getAllWalkingModes()} instead. * * Gets all not deleted walking modes from database * * @param context The application context * @return a list of walking modes */
public static List<WalkingMode> getAllItems(Context context) {
SecUSo/privacy-friendly-pedometer
app/src/main/java/org/secuso/privacyfriendlyactivitytracker/persistence/TrainingDbHelper.java
// Path: app/src/main/java/org/secuso/privacyfriendlyactivitytracker/models/Training.java // public class Training { // private long id; // private String name; // private String description; // private double steps; // private double distance; // private double calories; // private float feeling; // private long start; // private long end; // /** // * The view type for TrainingOverviewAdapter // */ // private int viewType = TrainingOverviewAdapter.VIEW_TYPE_TRAINING_SESSION; // // public static Training from(Cursor c) { // Training trainingSession = new Training(); // trainingSession.setId(c.getLong(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry._ID))); // trainingSession.setName(c.getString(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_NAME))); // trainingSession.setDescription(c.getString(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_DESCRIPTION))); // trainingSession.setSteps(c.getInt(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_STEPS))); // trainingSession.setDistance(c.getDouble(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_DISTANCE))); // trainingSession.setCalories(c.getDouble(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_CALORIES))); // trainingSession.setFeeling(c.getFloat(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_FEELING))); // trainingSession.setStart(c.getLong(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_START))); // trainingSession.setEnd(c.getLong(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_END))); // return trainingSession; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public double getSteps() { // return steps; // } // // public void setSteps(double steps) { // this.steps = steps; // } // // public double getDistance() { // return distance; // } // // public void setDistance(double distance) { // this.distance = distance; // } // // public double getCalories() { // return calories; // } // // public void setCalories(double calories) { // this.calories = calories; // } // // public float getFeeling() { // return feeling; // } // // public void setFeeling(float feeling) { // this.feeling = feeling; // } // // public long getStart() { // return start; // } // // public void setStart(long start) { // this.start = start; // } // // public long getEnd() { // return end; // } // // public void setEnd(long end) { // this.end = end; // } // // public int getViewType() { // return viewType; // } // // public void setViewType(int viewType) { // this.viewType = viewType; // } // // /** // * Returns the duration in seconds // * @return seconds // */ // public int getDuration(){ // long end = this.getEnd(); // if(end == 0){ // end = Calendar.getInstance().getTimeInMillis(); // } // return (Double.valueOf((end - this.getStart())/1000)).intValue(); // } // // /** // * Returns the velocity in meters per second // * @return m/s // */ // public double getVelocity(){ // if(this.getDuration() == 0){ // return 0; // } // return this.getDistance()/this.getDuration(); // } // // public ContentValues toContentValues() { // ContentValues values = new ContentValues(); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_NAME, this.getName()); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_DESCRIPTION, this.getDescription()); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_STEPS, this.getSteps()); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_DISTANCE, String.valueOf(this.getDistance())); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_CALORIES, String.valueOf(this.getCalories())); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_FEELING, String.valueOf(this.getFeeling())); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_START, String.valueOf(this.getStart())); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_END, String.valueOf(this.getEnd())); // return values; // } // }
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; import org.secuso.privacyfriendlyactivitytracker.models.Training; import java.util.ArrayList; import java.util.List;
private static SQLiteDatabase getDatabase(TrainingDbHelper instance){ if(db == null){ db = instance.getWritableDatabase(); } return db; } public static void invalidateReference(){ db = null; } public TrainingDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE_ENTRIES); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Fill when upgrading DB } public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } /** * Inserts the given training session as new entry. * * @param item The training session which should be stored * @return the inserted id */
// Path: app/src/main/java/org/secuso/privacyfriendlyactivitytracker/models/Training.java // public class Training { // private long id; // private String name; // private String description; // private double steps; // private double distance; // private double calories; // private float feeling; // private long start; // private long end; // /** // * The view type for TrainingOverviewAdapter // */ // private int viewType = TrainingOverviewAdapter.VIEW_TYPE_TRAINING_SESSION; // // public static Training from(Cursor c) { // Training trainingSession = new Training(); // trainingSession.setId(c.getLong(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry._ID))); // trainingSession.setName(c.getString(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_NAME))); // trainingSession.setDescription(c.getString(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_DESCRIPTION))); // trainingSession.setSteps(c.getInt(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_STEPS))); // trainingSession.setDistance(c.getDouble(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_DISTANCE))); // trainingSession.setCalories(c.getDouble(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_CALORIES))); // trainingSession.setFeeling(c.getFloat(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_FEELING))); // trainingSession.setStart(c.getLong(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_START))); // trainingSession.setEnd(c.getLong(c.getColumnIndex(TrainingDbHelper.TrainingSessionEntry.KEY_END))); // return trainingSession; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public double getSteps() { // return steps; // } // // public void setSteps(double steps) { // this.steps = steps; // } // // public double getDistance() { // return distance; // } // // public void setDistance(double distance) { // this.distance = distance; // } // // public double getCalories() { // return calories; // } // // public void setCalories(double calories) { // this.calories = calories; // } // // public float getFeeling() { // return feeling; // } // // public void setFeeling(float feeling) { // this.feeling = feeling; // } // // public long getStart() { // return start; // } // // public void setStart(long start) { // this.start = start; // } // // public long getEnd() { // return end; // } // // public void setEnd(long end) { // this.end = end; // } // // public int getViewType() { // return viewType; // } // // public void setViewType(int viewType) { // this.viewType = viewType; // } // // /** // * Returns the duration in seconds // * @return seconds // */ // public int getDuration(){ // long end = this.getEnd(); // if(end == 0){ // end = Calendar.getInstance().getTimeInMillis(); // } // return (Double.valueOf((end - this.getStart())/1000)).intValue(); // } // // /** // * Returns the velocity in meters per second // * @return m/s // */ // public double getVelocity(){ // if(this.getDuration() == 0){ // return 0; // } // return this.getDistance()/this.getDuration(); // } // // public ContentValues toContentValues() { // ContentValues values = new ContentValues(); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_NAME, this.getName()); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_DESCRIPTION, this.getDescription()); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_STEPS, this.getSteps()); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_DISTANCE, String.valueOf(this.getDistance())); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_CALORIES, String.valueOf(this.getCalories())); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_FEELING, String.valueOf(this.getFeeling())); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_START, String.valueOf(this.getStart())); // values.put(TrainingDbHelper.TrainingSessionEntry.KEY_END, String.valueOf(this.getEnd())); // return values; // } // } // Path: app/src/main/java/org/secuso/privacyfriendlyactivitytracker/persistence/TrainingDbHelper.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; import org.secuso.privacyfriendlyactivitytracker.models.Training; import java.util.ArrayList; import java.util.List; private static SQLiteDatabase getDatabase(TrainingDbHelper instance){ if(db == null){ db = instance.getWritableDatabase(); } return db; } public static void invalidateReference(){ db = null; } public TrainingDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE_ENTRIES); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Fill when upgrading DB } public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } /** * Inserts the given training session as new entry. * * @param item The training session which should be stored * @return the inserted id */
protected long addTraining(Training item) {
SecUSo/privacy-friendly-pedometer
app/src/main/java/org/secuso/privacyfriendlyactivitytracker/persistence/WalkingModeDbHelper.java
// Path: app/src/main/java/org/secuso/privacyfriendlyactivitytracker/models/WalkingMode.java // public class WalkingMode { // private long id; // private String name; // private double stepLength; // private double stepFrequency; // private boolean is_active; // private boolean is_deleted; // // public static WalkingMode from(Cursor c) { // WalkingMode alarmItem = new WalkingMode(); // alarmItem.setId(c.getLong(c.getColumnIndex(WalkingModeDbHelper.WalkingModeEntry._ID))); // alarmItem.setName(c.getString(c.getColumnIndex(WalkingModeDbHelper.WalkingModeEntry.KEY_NAME))); // alarmItem.setStepLength(c.getDouble(c.getColumnIndex(WalkingModeDbHelper.WalkingModeEntry.KEY_STEP_SIZE))); // alarmItem.setStepFrequency(c.getDouble(c.getColumnIndex(WalkingModeDbHelper.WalkingModeEntry.KEY_STEP_FREQUENCY))); // alarmItem.setIsActive(Boolean.valueOf(c.getString(c.getColumnIndex(WalkingModeDbHelper.WalkingModeEntry.KEY_IS_ACTIVE)))); // alarmItem.setIsDeleted(Boolean.valueOf(c.getString(c.getColumnIndex(WalkingModeDbHelper.WalkingModeEntry.KEY_IS_DELETED)))); // return alarmItem; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public double getStepLength() { // return stepLength; // } // // public void setStepLength(double stepLength) { // this.stepLength = stepLength; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public double getStepFrequency() { // return stepFrequency; // } // // public void setStepFrequency(double stepFrequency) { // this.stepFrequency = stepFrequency; // } // // public boolean isActive() { // return is_active; // } // // public void setIsActive(boolean is_active) { // this.is_active = is_active; // } // // public boolean isDeleted() { // return is_deleted; // } // // public void setIsDeleted(boolean is_deleted) { // this.is_deleted = is_deleted; // } // // public ContentValues toContentValues() { // ContentValues values = new ContentValues(); // values.put(WalkingModeDbHelper.WalkingModeEntry.KEY_NAME, this.getName()); // values.put(WalkingModeDbHelper.WalkingModeEntry.KEY_STEP_SIZE, this.getStepLength()); // values.put(WalkingModeDbHelper.WalkingModeEntry.KEY_STEP_FREQUENCY, this.getStepFrequency()); // values.put(WalkingModeDbHelper.WalkingModeEntry.KEY_IS_ACTIVE, String.valueOf(this.isActive())); // values.put(WalkingModeDbHelper.WalkingModeEntry.KEY_IS_DELETED, String.valueOf(this.isDeleted())); // return values; // } // // @Override // public String toString() { // return "WalkingMode{" + // "id=" + id + // ", stepLength=" + stepLength + // ", name='" + name + '\'' + // '}'; // } // // // /** // * @return the walking-mode-specific color // */ // public int getColor() { // return ColorHelper.getMaterialColor(this.getId() + this.getName()); // } // // }
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; import android.util.Log; import org.secuso.privacyfriendlyactivitytracker.R; import org.secuso.privacyfriendlyactivitytracker.models.WalkingMode; import java.util.ArrayList; import java.util.List;
} return db; } public static void invalidateReference(){ db = null; } public WalkingModeDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); this.context = context; } public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE_ENTRIES); // Insert default walking modes String[] walkingModesNames = context.getResources().getStringArray(R.array.pref_default_walking_mode_names); String[] walkingModesStepLengthStrings = context.getResources().getStringArray(R.array.pref_default_walking_mode_step_lenghts); if (walkingModesStepLengthStrings.length != walkingModesNames.length) { Log.e(LOG_CLASS, "Number of default walking mode step lengths and names have to be the same."); return; } if (walkingModesNames.length == 0) { Log.e(LOG_CLASS, "There are no default walking modes."); } for (int i = 0; i < walkingModesStepLengthStrings.length; i++) { String stepLengthString = walkingModesStepLengthStrings[i]; double stepLength = Double.valueOf(stepLengthString); String name = walkingModesNames[i];
// Path: app/src/main/java/org/secuso/privacyfriendlyactivitytracker/models/WalkingMode.java // public class WalkingMode { // private long id; // private String name; // private double stepLength; // private double stepFrequency; // private boolean is_active; // private boolean is_deleted; // // public static WalkingMode from(Cursor c) { // WalkingMode alarmItem = new WalkingMode(); // alarmItem.setId(c.getLong(c.getColumnIndex(WalkingModeDbHelper.WalkingModeEntry._ID))); // alarmItem.setName(c.getString(c.getColumnIndex(WalkingModeDbHelper.WalkingModeEntry.KEY_NAME))); // alarmItem.setStepLength(c.getDouble(c.getColumnIndex(WalkingModeDbHelper.WalkingModeEntry.KEY_STEP_SIZE))); // alarmItem.setStepFrequency(c.getDouble(c.getColumnIndex(WalkingModeDbHelper.WalkingModeEntry.KEY_STEP_FREQUENCY))); // alarmItem.setIsActive(Boolean.valueOf(c.getString(c.getColumnIndex(WalkingModeDbHelper.WalkingModeEntry.KEY_IS_ACTIVE)))); // alarmItem.setIsDeleted(Boolean.valueOf(c.getString(c.getColumnIndex(WalkingModeDbHelper.WalkingModeEntry.KEY_IS_DELETED)))); // return alarmItem; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public double getStepLength() { // return stepLength; // } // // public void setStepLength(double stepLength) { // this.stepLength = stepLength; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public double getStepFrequency() { // return stepFrequency; // } // // public void setStepFrequency(double stepFrequency) { // this.stepFrequency = stepFrequency; // } // // public boolean isActive() { // return is_active; // } // // public void setIsActive(boolean is_active) { // this.is_active = is_active; // } // // public boolean isDeleted() { // return is_deleted; // } // // public void setIsDeleted(boolean is_deleted) { // this.is_deleted = is_deleted; // } // // public ContentValues toContentValues() { // ContentValues values = new ContentValues(); // values.put(WalkingModeDbHelper.WalkingModeEntry.KEY_NAME, this.getName()); // values.put(WalkingModeDbHelper.WalkingModeEntry.KEY_STEP_SIZE, this.getStepLength()); // values.put(WalkingModeDbHelper.WalkingModeEntry.KEY_STEP_FREQUENCY, this.getStepFrequency()); // values.put(WalkingModeDbHelper.WalkingModeEntry.KEY_IS_ACTIVE, String.valueOf(this.isActive())); // values.put(WalkingModeDbHelper.WalkingModeEntry.KEY_IS_DELETED, String.valueOf(this.isDeleted())); // return values; // } // // @Override // public String toString() { // return "WalkingMode{" + // "id=" + id + // ", stepLength=" + stepLength + // ", name='" + name + '\'' + // '}'; // } // // // /** // * @return the walking-mode-specific color // */ // public int getColor() { // return ColorHelper.getMaterialColor(this.getId() + this.getName()); // } // // } // Path: app/src/main/java/org/secuso/privacyfriendlyactivitytracker/persistence/WalkingModeDbHelper.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; import android.util.Log; import org.secuso.privacyfriendlyactivitytracker.R; import org.secuso.privacyfriendlyactivitytracker.models.WalkingMode; import java.util.ArrayList; import java.util.List; } return db; } public static void invalidateReference(){ db = null; } public WalkingModeDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); this.context = context; } public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE_ENTRIES); // Insert default walking modes String[] walkingModesNames = context.getResources().getStringArray(R.array.pref_default_walking_mode_names); String[] walkingModesStepLengthStrings = context.getResources().getStringArray(R.array.pref_default_walking_mode_step_lenghts); if (walkingModesStepLengthStrings.length != walkingModesNames.length) { Log.e(LOG_CLASS, "Number of default walking mode step lengths and names have to be the same."); return; } if (walkingModesNames.length == 0) { Log.e(LOG_CLASS, "There are no default walking modes."); } for (int i = 0; i < walkingModesStepLengthStrings.length; i++) { String stepLengthString = walkingModesStepLengthStrings[i]; double stepLength = Double.valueOf(stepLengthString); String name = walkingModesNames[i];
WalkingMode walkingMode = new WalkingMode();
komiya-atsushi/fast-rng-java
fast-rng/src/main/java/biz/k11i/rng/ExponentialRNG.java
// Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double exp(double value) { // return JafamaMath.exp(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double log(double value) { // return JafamaMath.log(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double log1p(double value) { // return JafamaMath.log1p(value); // }
import java.util.Random; import static biz.k11i.util.MathFunctions.exp; import static biz.k11i.util.MathFunctions.log; import static biz.k11i.util.MathFunctions.log1p;
package biz.k11i.rng; /** * Exponential random number generator. */ public interface ExponentialRNG { ExponentialRNG FAST_RNG = ZigguratFast.Z_256; ExponentialRNG GENERAL_RNG = ZigguratGeneral.Z_256; /** * Generates a random value sampled from exponential distribution. * * @param random random number generator * @param theta mean of the distribution * @return a random value */ double generate(Random random, double theta); abstract class ZigguratBase implements ExponentialRNG { final int N; final double R; final double V; final int INDEX_BIT_MASK; final int TAIL_INDEX; ZigguratBase(int nBits, double r, double v) { N = 1 << nBits; R = r; V = v; INDEX_BIT_MASK = (1 << nBits) - 1; TAIL_INDEX = (1 << nBits) - 1; } static double finv(double x, double v) {
// Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double exp(double value) { // return JafamaMath.exp(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double log(double value) { // return JafamaMath.log(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double log1p(double value) { // return JafamaMath.log1p(value); // } // Path: fast-rng/src/main/java/biz/k11i/rng/ExponentialRNG.java import java.util.Random; import static biz.k11i.util.MathFunctions.exp; import static biz.k11i.util.MathFunctions.log; import static biz.k11i.util.MathFunctions.log1p; package biz.k11i.rng; /** * Exponential random number generator. */ public interface ExponentialRNG { ExponentialRNG FAST_RNG = ZigguratFast.Z_256; ExponentialRNG GENERAL_RNG = ZigguratGeneral.Z_256; /** * Generates a random value sampled from exponential distribution. * * @param random random number generator * @param theta mean of the distribution * @return a random value */ double generate(Random random, double theta); abstract class ZigguratBase implements ExponentialRNG { final int N; final double R; final double V; final int INDEX_BIT_MASK; final int TAIL_INDEX; ZigguratBase(int nBits, double r, double v) { N = 1 << nBits; R = r; V = v; INDEX_BIT_MASK = (1 << nBits) - 1; TAIL_INDEX = (1 << nBits) - 1; } static double finv(double x, double v) {
return -log(exp(-x) + v / x);
komiya-atsushi/fast-rng-java
fast-rng/src/main/java/biz/k11i/rng/ExponentialRNG.java
// Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double exp(double value) { // return JafamaMath.exp(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double log(double value) { // return JafamaMath.log(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double log1p(double value) { // return JafamaMath.log1p(value); // }
import java.util.Random; import static biz.k11i.util.MathFunctions.exp; import static biz.k11i.util.MathFunctions.log; import static biz.k11i.util.MathFunctions.log1p;
package biz.k11i.rng; /** * Exponential random number generator. */ public interface ExponentialRNG { ExponentialRNG FAST_RNG = ZigguratFast.Z_256; ExponentialRNG GENERAL_RNG = ZigguratGeneral.Z_256; /** * Generates a random value sampled from exponential distribution. * * @param random random number generator * @param theta mean of the distribution * @return a random value */ double generate(Random random, double theta); abstract class ZigguratBase implements ExponentialRNG { final int N; final double R; final double V; final int INDEX_BIT_MASK; final int TAIL_INDEX; ZigguratBase(int nBits, double r, double v) { N = 1 << nBits; R = r; V = v; INDEX_BIT_MASK = (1 << nBits) - 1; TAIL_INDEX = (1 << nBits) - 1; } static double finv(double x, double v) {
// Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double exp(double value) { // return JafamaMath.exp(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double log(double value) { // return JafamaMath.log(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double log1p(double value) { // return JafamaMath.log1p(value); // } // Path: fast-rng/src/main/java/biz/k11i/rng/ExponentialRNG.java import java.util.Random; import static biz.k11i.util.MathFunctions.exp; import static biz.k11i.util.MathFunctions.log; import static biz.k11i.util.MathFunctions.log1p; package biz.k11i.rng; /** * Exponential random number generator. */ public interface ExponentialRNG { ExponentialRNG FAST_RNG = ZigguratFast.Z_256; ExponentialRNG GENERAL_RNG = ZigguratGeneral.Z_256; /** * Generates a random value sampled from exponential distribution. * * @param random random number generator * @param theta mean of the distribution * @return a random value */ double generate(Random random, double theta); abstract class ZigguratBase implements ExponentialRNG { final int N; final double R; final double V; final int INDEX_BIT_MASK; final int TAIL_INDEX; ZigguratBase(int nBits, double r, double v) { N = 1 << nBits; R = r; V = v; INDEX_BIT_MASK = (1 << nBits) - 1; TAIL_INDEX = (1 << nBits) - 1; } static double finv(double x, double v) {
return -log(exp(-x) + v / x);
komiya-atsushi/fast-rng-java
fast-rng/src/main/java/biz/k11i/rng/ExponentialRNG.java
// Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double exp(double value) { // return JafamaMath.exp(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double log(double value) { // return JafamaMath.log(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double log1p(double value) { // return JafamaMath.log1p(value); // }
import java.util.Random; import static biz.k11i.util.MathFunctions.exp; import static biz.k11i.util.MathFunctions.log; import static biz.k11i.util.MathFunctions.log1p;
k[N - 1] = (long) Math.floor(r / w[N - 1]); f[N - 1] = exp(-r); double x = r; for (int i = N - 2; i >= 1; i--) { x = finv(x, v); w[i - 1] = x / b; k[i] = (long) Math.floor(x / w[i]); f[i] = exp(-x); } k[0] = 0; f[0] = 1; } @Override double generate(Random random, int recursiveCount) { while (true) { long u = random.nextLong(); int i = (int) (u & INDEX_BIT_MASK); u >>>= INDEX_BITS; if (u < k[i]) { return u * w[i]; } if (i == TAIL_INDEX) { if (recursiveCount < 2) { return R + generate(random, recursiveCount + 1); }
// Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double exp(double value) { // return JafamaMath.exp(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double log(double value) { // return JafamaMath.log(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double log1p(double value) { // return JafamaMath.log1p(value); // } // Path: fast-rng/src/main/java/biz/k11i/rng/ExponentialRNG.java import java.util.Random; import static biz.k11i.util.MathFunctions.exp; import static biz.k11i.util.MathFunctions.log; import static biz.k11i.util.MathFunctions.log1p; k[N - 1] = (long) Math.floor(r / w[N - 1]); f[N - 1] = exp(-r); double x = r; for (int i = N - 2; i >= 1; i--) { x = finv(x, v); w[i - 1] = x / b; k[i] = (long) Math.floor(x / w[i]); f[i] = exp(-x); } k[0] = 0; f[0] = 1; } @Override double generate(Random random, int recursiveCount) { while (true) { long u = random.nextLong(); int i = (int) (u & INDEX_BIT_MASK); u >>>= INDEX_BITS; if (u < k[i]) { return u * w[i]; } if (i == TAIL_INDEX) { if (recursiveCount < 2) { return R + generate(random, recursiveCount + 1); }
return R - log1p(-random.nextDouble());
komiya-atsushi/fast-rng-java
fast-rng/src/main/java/biz/k11i/rng/GaussianRNG.java
// Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double exp(double value) { // return JafamaMath.exp(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double log(double value) { // return JafamaMath.log(value); // }
import java.util.Random; import static biz.k11i.util.MathFunctions.exp; import static biz.k11i.util.MathFunctions.log;
package biz.k11i.rng; /** * Gaussian random number generator. */ public interface GaussianRNG { GaussianRNG FAST_RNG = ZigguratFast.Z_256; GaussianRNG GENERAL_RNG = ZigguratGeneral.Z_256; /** * Generates a random value sampled from gaussian distribution (normal distribution). * * @param random random number generator * @return a random value */ double generate(Random random); abstract class ZigguratBase { static double f(double x) { // f(x) = e^{-x^2 / 2}
// Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double exp(double value) { // return JafamaMath.exp(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double log(double value) { // return JafamaMath.log(value); // } // Path: fast-rng/src/main/java/biz/k11i/rng/GaussianRNG.java import java.util.Random; import static biz.k11i.util.MathFunctions.exp; import static biz.k11i.util.MathFunctions.log; package biz.k11i.rng; /** * Gaussian random number generator. */ public interface GaussianRNG { GaussianRNG FAST_RNG = ZigguratFast.Z_256; GaussianRNG GENERAL_RNG = ZigguratGeneral.Z_256; /** * Generates a random value sampled from gaussian distribution (normal distribution). * * @param random random number generator * @return a random value */ double generate(Random random); abstract class ZigguratBase { static double f(double x) { // f(x) = e^{-x^2 / 2}
return exp(-0.5 * x * x);
komiya-atsushi/fast-rng-java
fast-rng/src/main/java/biz/k11i/rng/GaussianRNG.java
// Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double exp(double value) { // return JafamaMath.exp(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double log(double value) { // return JafamaMath.log(value); // }
import java.util.Random; import static biz.k11i.util.MathFunctions.exp; import static biz.k11i.util.MathFunctions.log;
package biz.k11i.rng; /** * Gaussian random number generator. */ public interface GaussianRNG { GaussianRNG FAST_RNG = ZigguratFast.Z_256; GaussianRNG GENERAL_RNG = ZigguratGeneral.Z_256; /** * Generates a random value sampled from gaussian distribution (normal distribution). * * @param random random number generator * @return a random value */ double generate(Random random); abstract class ZigguratBase { static double f(double x) { // f(x) = e^{-x^2 / 2} return exp(-0.5 * x * x); } static double tail(Random random, double r) { double _x, _y; do {
// Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double exp(double value) { // return JafamaMath.exp(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double log(double value) { // return JafamaMath.log(value); // } // Path: fast-rng/src/main/java/biz/k11i/rng/GaussianRNG.java import java.util.Random; import static biz.k11i.util.MathFunctions.exp; import static biz.k11i.util.MathFunctions.log; package biz.k11i.rng; /** * Gaussian random number generator. */ public interface GaussianRNG { GaussianRNG FAST_RNG = ZigguratFast.Z_256; GaussianRNG GENERAL_RNG = ZigguratGeneral.Z_256; /** * Generates a random value sampled from gaussian distribution (normal distribution). * * @param random random number generator * @return a random value */ double generate(Random random); abstract class ZigguratBase { static double f(double x) { // f(x) = e^{-x^2 / 2} return exp(-0.5 * x * x); } static double tail(Random random, double r) { double _x, _y; do {
_x = -log(random.nextDouble()) / r;
komiya-atsushi/fast-rng-java
benchmark/src/jmh/java/biz/k11i/rng/BetaBenchmark.java
// Path: benchmark/src/jmh/java/biz/k11i/rng/util/MtRandom.java // public class MtRandom extends Random { // private final MersenneTwister mersenneTwister; // // public MtRandom() { // mersenneTwister = new MersenneTwister(); // } // // public MtRandom(int seed) { // mersenneTwister = new MersenneTwister(seed); // } // // @Override // public boolean nextBoolean() { // return mersenneTwister.nextBoolean(); // } // // @Override // public void nextBytes(byte[] bytes) { // mersenneTwister.nextBytes(bytes); // } // // @Override // public double nextDouble() { // return mersenneTwister.nextDouble(); // } // // @Override // public float nextFloat() { // return mersenneTwister.nextFloat(); // } // // @Override // public double nextGaussian() { // return mersenneTwister.nextGaussian(); // } // // @Override // public int nextInt() { // return mersenneTwister.nextInt(); // } // // @Override // public int nextInt(int n) throws IllegalArgumentException { // return mersenneTwister.nextInt(n); // } // // @Override // public long nextLong() { // return mersenneTwister.nextLong(); // } // } // // Path: benchmark/src/jmh/java/biz/k11i/rng/util/ParameterPool.java // public class ParameterPool { // private double[] parameters; // private int index; // // public ParameterPool(int seed, int count, double theta) { // parameters = new double[count]; // MtRandom r = new MtRandom(seed); // // for (int i = 0; i < count; i++) { // parameters[i] = Math.nextUp(ExponentialRNG.FAST_RNG.generate(r, theta)); // } // } // // public double next() { // if (index >= parameters.length) { // index = 0; // } // // return parameters[index++]; // } // }
import biz.k11i.rng.util.MtRandom; import biz.k11i.rng.util.ParameterPool; import org.apache.commons.math3.distribution.BetaDistribution; import org.apache.commons.math3.random.MersenneTwister; import org.apache.commons.math3.random.RandomGenerator; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import java.util.Random;
package biz.k11i.rng; public class BetaBenchmark { @State(Scope.Benchmark) public static class FixedParameters { @Param({"0.1:0.1", "0.1:0.5", "0.1:0.99999", "0.5:0.5", "0.5:0.99999", "0.99999:0.99999", "0.05:2.0", "0.2:20.0", "0.8:200.0", "1.0:2.0", "2.0:3.0", "20.0:30.0", "200.0:300.0" }) public String parameters; private double alpha; private double beta;
// Path: benchmark/src/jmh/java/biz/k11i/rng/util/MtRandom.java // public class MtRandom extends Random { // private final MersenneTwister mersenneTwister; // // public MtRandom() { // mersenneTwister = new MersenneTwister(); // } // // public MtRandom(int seed) { // mersenneTwister = new MersenneTwister(seed); // } // // @Override // public boolean nextBoolean() { // return mersenneTwister.nextBoolean(); // } // // @Override // public void nextBytes(byte[] bytes) { // mersenneTwister.nextBytes(bytes); // } // // @Override // public double nextDouble() { // return mersenneTwister.nextDouble(); // } // // @Override // public float nextFloat() { // return mersenneTwister.nextFloat(); // } // // @Override // public double nextGaussian() { // return mersenneTwister.nextGaussian(); // } // // @Override // public int nextInt() { // return mersenneTwister.nextInt(); // } // // @Override // public int nextInt(int n) throws IllegalArgumentException { // return mersenneTwister.nextInt(n); // } // // @Override // public long nextLong() { // return mersenneTwister.nextLong(); // } // } // // Path: benchmark/src/jmh/java/biz/k11i/rng/util/ParameterPool.java // public class ParameterPool { // private double[] parameters; // private int index; // // public ParameterPool(int seed, int count, double theta) { // parameters = new double[count]; // MtRandom r = new MtRandom(seed); // // for (int i = 0; i < count; i++) { // parameters[i] = Math.nextUp(ExponentialRNG.FAST_RNG.generate(r, theta)); // } // } // // public double next() { // if (index >= parameters.length) { // index = 0; // } // // return parameters[index++]; // } // } // Path: benchmark/src/jmh/java/biz/k11i/rng/BetaBenchmark.java import biz.k11i.rng.util.MtRandom; import biz.k11i.rng.util.ParameterPool; import org.apache.commons.math3.distribution.BetaDistribution; import org.apache.commons.math3.random.MersenneTwister; import org.apache.commons.math3.random.RandomGenerator; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import java.util.Random; package biz.k11i.rng; public class BetaBenchmark { @State(Scope.Benchmark) public static class FixedParameters { @Param({"0.1:0.1", "0.1:0.5", "0.1:0.99999", "0.5:0.5", "0.5:0.99999", "0.99999:0.99999", "0.05:2.0", "0.2:20.0", "0.8:200.0", "1.0:2.0", "2.0:3.0", "20.0:30.0", "200.0:300.0" }) public String parameters; private double alpha; private double beta;
private Random random = new MtRandom();
komiya-atsushi/fast-rng-java
benchmark/src/jmh/java/biz/k11i/rng/BetaBenchmark.java
// Path: benchmark/src/jmh/java/biz/k11i/rng/util/MtRandom.java // public class MtRandom extends Random { // private final MersenneTwister mersenneTwister; // // public MtRandom() { // mersenneTwister = new MersenneTwister(); // } // // public MtRandom(int seed) { // mersenneTwister = new MersenneTwister(seed); // } // // @Override // public boolean nextBoolean() { // return mersenneTwister.nextBoolean(); // } // // @Override // public void nextBytes(byte[] bytes) { // mersenneTwister.nextBytes(bytes); // } // // @Override // public double nextDouble() { // return mersenneTwister.nextDouble(); // } // // @Override // public float nextFloat() { // return mersenneTwister.nextFloat(); // } // // @Override // public double nextGaussian() { // return mersenneTwister.nextGaussian(); // } // // @Override // public int nextInt() { // return mersenneTwister.nextInt(); // } // // @Override // public int nextInt(int n) throws IllegalArgumentException { // return mersenneTwister.nextInt(n); // } // // @Override // public long nextLong() { // return mersenneTwister.nextLong(); // } // } // // Path: benchmark/src/jmh/java/biz/k11i/rng/util/ParameterPool.java // public class ParameterPool { // private double[] parameters; // private int index; // // public ParameterPool(int seed, int count, double theta) { // parameters = new double[count]; // MtRandom r = new MtRandom(seed); // // for (int i = 0; i < count; i++) { // parameters[i] = Math.nextUp(ExponentialRNG.FAST_RNG.generate(r, theta)); // } // } // // public double next() { // if (index >= parameters.length) { // index = 0; // } // // return parameters[index++]; // } // }
import biz.k11i.rng.util.MtRandom; import biz.k11i.rng.util.ParameterPool; import org.apache.commons.math3.distribution.BetaDistribution; import org.apache.commons.math3.random.MersenneTwister; import org.apache.commons.math3.random.RandomGenerator; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import java.util.Random;
@Setup public void setUp() { String[] items = parameters.split(":"); alpha = Double.valueOf(items[0]); beta = Double.valueOf(items[1]); commonsMath = new BetaDistribution(alpha, beta); } @Benchmark public double commonsMath() { return commonsMath.sample(); } @Benchmark public double fastRng() { return BetaRNG.FAST_RNG.generate(random, alpha, beta); } @Benchmark public double generalRng() { return BetaRNG.GENERAL_RNG.generate(random, alpha, beta); } } @State(Scope.Benchmark) public static class ArbitraryParameters { private Random random = new MtRandom(); private RandomGenerator randomGenerator = new MersenneTwister();
// Path: benchmark/src/jmh/java/biz/k11i/rng/util/MtRandom.java // public class MtRandom extends Random { // private final MersenneTwister mersenneTwister; // // public MtRandom() { // mersenneTwister = new MersenneTwister(); // } // // public MtRandom(int seed) { // mersenneTwister = new MersenneTwister(seed); // } // // @Override // public boolean nextBoolean() { // return mersenneTwister.nextBoolean(); // } // // @Override // public void nextBytes(byte[] bytes) { // mersenneTwister.nextBytes(bytes); // } // // @Override // public double nextDouble() { // return mersenneTwister.nextDouble(); // } // // @Override // public float nextFloat() { // return mersenneTwister.nextFloat(); // } // // @Override // public double nextGaussian() { // return mersenneTwister.nextGaussian(); // } // // @Override // public int nextInt() { // return mersenneTwister.nextInt(); // } // // @Override // public int nextInt(int n) throws IllegalArgumentException { // return mersenneTwister.nextInt(n); // } // // @Override // public long nextLong() { // return mersenneTwister.nextLong(); // } // } // // Path: benchmark/src/jmh/java/biz/k11i/rng/util/ParameterPool.java // public class ParameterPool { // private double[] parameters; // private int index; // // public ParameterPool(int seed, int count, double theta) { // parameters = new double[count]; // MtRandom r = new MtRandom(seed); // // for (int i = 0; i < count; i++) { // parameters[i] = Math.nextUp(ExponentialRNG.FAST_RNG.generate(r, theta)); // } // } // // public double next() { // if (index >= parameters.length) { // index = 0; // } // // return parameters[index++]; // } // } // Path: benchmark/src/jmh/java/biz/k11i/rng/BetaBenchmark.java import biz.k11i.rng.util.MtRandom; import biz.k11i.rng.util.ParameterPool; import org.apache.commons.math3.distribution.BetaDistribution; import org.apache.commons.math3.random.MersenneTwister; import org.apache.commons.math3.random.RandomGenerator; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import java.util.Random; @Setup public void setUp() { String[] items = parameters.split(":"); alpha = Double.valueOf(items[0]); beta = Double.valueOf(items[1]); commonsMath = new BetaDistribution(alpha, beta); } @Benchmark public double commonsMath() { return commonsMath.sample(); } @Benchmark public double fastRng() { return BetaRNG.FAST_RNG.generate(random, alpha, beta); } @Benchmark public double generalRng() { return BetaRNG.GENERAL_RNG.generate(random, alpha, beta); } } @State(Scope.Benchmark) public static class ArbitraryParameters { private Random random = new MtRandom(); private RandomGenerator randomGenerator = new MersenneTwister();
private ParameterPool alphaParameters = new ParameterPool(12345, 10000, 10.0);
komiya-atsushi/fast-rng-java
fast-rng-test/src/test/java/biz/k11i/rng/test/SecondLevelTestTest.java
// Path: fast-rng-test/src/main/java/biz/k11i/rng/test/gof/GoodnessOfFitTest.java // @SuppressWarnings("unused") // public abstract class GoodnessOfFitTest { // static class BuilderBase<SELF extends BuilderBase<SELF>> { // @SuppressWarnings("unchecked") // private final SELF self = (SELF) this; // // int numRandomValues; // double significanceLevel = DEFAULT_SIGNIFICANCE_LEVEL; // // public SELF numRandomValues(int numRandomValues) { // this.numRandomValues = numRandomValues; // return self; // } // // public SELF significanceLevel(double significanceLevel) { // this.significanceLevel = significanceLevel; // return self; // } // } // // /** Default significance level (0.1%) */ // private static final double DEFAULT_SIGNIFICANCE_LEVEL = 0.001; // // /** Name of the random number generator to be tested */ // public final String rngName; // // /** Significance level to reject the null hypothesis */ // public final double significanceLevel; // // GoodnessOfFitTest(String rngName, double significanceLevel) { // this.rngName = rngName; // this.significanceLevel = significanceLevel; // } // // /** // * Returns {@link ContinuousGofTest} builder object. // * // * @return builder object. // */ // public static ContinuousGofTest.Builder continuous() { // return new ContinuousGofTest.Builder(); // } // // /** // * Returns {@link DiscreteGofTest} builder object. // * // * @return builder obbject. // */ // public static DiscreteGofTest.Builder discrete() { // return new DiscreteGofTest.Builder(); // } // // /** // * Calculate p-values of Goodness-of-Fit test. // * // * @return test result. // */ // public abstract Map<String, Double> test(); // // /** // * Calculate p-values of Goodness-of-Fit test in parallel. // * // * @return test result. // */ // public Map<String, Double> testInParallel() { // ForkJoinPool pool = new ForkJoinPool(); // try { // return testInParallel(pool); // // } finally { // pool.shutdown(); // try { // pool.awaitTermination(1, TimeUnit.SECONDS); // } catch (InterruptedException ignore) { // } // } // } // // /** // * Calculate p-values of Goodness-of-Fit test in parallel using given {@link ForkJoinPool} instance. // * // * @param pool Fork/Join pool to execute tasks in paralle. // * @return test result. // */ // public abstract Map<String, Double> testInParallel(ForkJoinPool pool); // // /** // * Runs Goodness-of-Fit tests and verifis whether the test failed to reject the null hypothesis // * (which means the random sequence that was generated by random number generator can be described as random) or not. // */ // public void testAndVerify() { // Map<String, Double> result = test(); // // result.forEach((t, p) -> // assertThat(p) // .describedAs("At a significance level of %e, the Goodness-of-Fit test of [%s] should fail to reject null hypothesis (The p-value %f should be greater than or equal to %e).\n" + // "This means that the random sequence generated by the random number generator [%s] fit the theoretical probability distribution.", // significanceLevel, t, p, significanceLevel, // rngName) // .isGreaterThanOrEqualTo(significanceLevel)); // } // } // // Path: fast-rng-test/src/main/java/biz/k11i/rng/test/util/distribution/ProbabilityDistributions.java // public interface ProbabilityDistributions { // static ContinuousDistribution gaussian(double mean, double sd) { // return new Gaussian(mean, sd); // } // // static ContinuousDistribution gamma(double shape, double scale) { // return new Gamma(shape, scale); // } // // static ContinuousDistribution beta(double alpha, double beta) { // return new Beta(alpha, beta); // } // // static ContinuousDistribution wrap(RealDistribution distribution) { // return new CommonsMath3DistributionWrapper.Continuous(distribution); // } // // static DiscreteDistribution wrap(IntegerDistribution distribution) { // return new CommonsMath3DistributionWrapper.Discrete(distribution); // } // }
import biz.k11i.rng.test.gof.GoodnessOfFitTest; import biz.k11i.rng.test.util.distribution.ProbabilityDistributions; import org.junit.jupiter.api.Test; import java.util.Random; import static org.assertj.core.api.Assertions.assertThatThrownBy;
package biz.k11i.rng.test; class SecondLevelTestTest { @Test void test() {
// Path: fast-rng-test/src/main/java/biz/k11i/rng/test/gof/GoodnessOfFitTest.java // @SuppressWarnings("unused") // public abstract class GoodnessOfFitTest { // static class BuilderBase<SELF extends BuilderBase<SELF>> { // @SuppressWarnings("unchecked") // private final SELF self = (SELF) this; // // int numRandomValues; // double significanceLevel = DEFAULT_SIGNIFICANCE_LEVEL; // // public SELF numRandomValues(int numRandomValues) { // this.numRandomValues = numRandomValues; // return self; // } // // public SELF significanceLevel(double significanceLevel) { // this.significanceLevel = significanceLevel; // return self; // } // } // // /** Default significance level (0.1%) */ // private static final double DEFAULT_SIGNIFICANCE_LEVEL = 0.001; // // /** Name of the random number generator to be tested */ // public final String rngName; // // /** Significance level to reject the null hypothesis */ // public final double significanceLevel; // // GoodnessOfFitTest(String rngName, double significanceLevel) { // this.rngName = rngName; // this.significanceLevel = significanceLevel; // } // // /** // * Returns {@link ContinuousGofTest} builder object. // * // * @return builder object. // */ // public static ContinuousGofTest.Builder continuous() { // return new ContinuousGofTest.Builder(); // } // // /** // * Returns {@link DiscreteGofTest} builder object. // * // * @return builder obbject. // */ // public static DiscreteGofTest.Builder discrete() { // return new DiscreteGofTest.Builder(); // } // // /** // * Calculate p-values of Goodness-of-Fit test. // * // * @return test result. // */ // public abstract Map<String, Double> test(); // // /** // * Calculate p-values of Goodness-of-Fit test in parallel. // * // * @return test result. // */ // public Map<String, Double> testInParallel() { // ForkJoinPool pool = new ForkJoinPool(); // try { // return testInParallel(pool); // // } finally { // pool.shutdown(); // try { // pool.awaitTermination(1, TimeUnit.SECONDS); // } catch (InterruptedException ignore) { // } // } // } // // /** // * Calculate p-values of Goodness-of-Fit test in parallel using given {@link ForkJoinPool} instance. // * // * @param pool Fork/Join pool to execute tasks in paralle. // * @return test result. // */ // public abstract Map<String, Double> testInParallel(ForkJoinPool pool); // // /** // * Runs Goodness-of-Fit tests and verifis whether the test failed to reject the null hypothesis // * (which means the random sequence that was generated by random number generator can be described as random) or not. // */ // public void testAndVerify() { // Map<String, Double> result = test(); // // result.forEach((t, p) -> // assertThat(p) // .describedAs("At a significance level of %e, the Goodness-of-Fit test of [%s] should fail to reject null hypothesis (The p-value %f should be greater than or equal to %e).\n" + // "This means that the random sequence generated by the random number generator [%s] fit the theoretical probability distribution.", // significanceLevel, t, p, significanceLevel, // rngName) // .isGreaterThanOrEqualTo(significanceLevel)); // } // } // // Path: fast-rng-test/src/main/java/biz/k11i/rng/test/util/distribution/ProbabilityDistributions.java // public interface ProbabilityDistributions { // static ContinuousDistribution gaussian(double mean, double sd) { // return new Gaussian(mean, sd); // } // // static ContinuousDistribution gamma(double shape, double scale) { // return new Gamma(shape, scale); // } // // static ContinuousDistribution beta(double alpha, double beta) { // return new Beta(alpha, beta); // } // // static ContinuousDistribution wrap(RealDistribution distribution) { // return new CommonsMath3DistributionWrapper.Continuous(distribution); // } // // static DiscreteDistribution wrap(IntegerDistribution distribution) { // return new CommonsMath3DistributionWrapper.Discrete(distribution); // } // } // Path: fast-rng-test/src/test/java/biz/k11i/rng/test/SecondLevelTestTest.java import biz.k11i.rng.test.gof.GoodnessOfFitTest; import biz.k11i.rng.test.util.distribution.ProbabilityDistributions; import org.junit.jupiter.api.Test; import java.util.Random; import static org.assertj.core.api.Assertions.assertThatThrownBy; package biz.k11i.rng.test; class SecondLevelTestTest { @Test void test() {
GoodnessOfFitTest gofTest = GoodnessOfFitTest.continuous()
komiya-atsushi/fast-rng-java
fast-rng-test/src/test/java/biz/k11i/rng/test/SecondLevelTestTest.java
// Path: fast-rng-test/src/main/java/biz/k11i/rng/test/gof/GoodnessOfFitTest.java // @SuppressWarnings("unused") // public abstract class GoodnessOfFitTest { // static class BuilderBase<SELF extends BuilderBase<SELF>> { // @SuppressWarnings("unchecked") // private final SELF self = (SELF) this; // // int numRandomValues; // double significanceLevel = DEFAULT_SIGNIFICANCE_LEVEL; // // public SELF numRandomValues(int numRandomValues) { // this.numRandomValues = numRandomValues; // return self; // } // // public SELF significanceLevel(double significanceLevel) { // this.significanceLevel = significanceLevel; // return self; // } // } // // /** Default significance level (0.1%) */ // private static final double DEFAULT_SIGNIFICANCE_LEVEL = 0.001; // // /** Name of the random number generator to be tested */ // public final String rngName; // // /** Significance level to reject the null hypothesis */ // public final double significanceLevel; // // GoodnessOfFitTest(String rngName, double significanceLevel) { // this.rngName = rngName; // this.significanceLevel = significanceLevel; // } // // /** // * Returns {@link ContinuousGofTest} builder object. // * // * @return builder object. // */ // public static ContinuousGofTest.Builder continuous() { // return new ContinuousGofTest.Builder(); // } // // /** // * Returns {@link DiscreteGofTest} builder object. // * // * @return builder obbject. // */ // public static DiscreteGofTest.Builder discrete() { // return new DiscreteGofTest.Builder(); // } // // /** // * Calculate p-values of Goodness-of-Fit test. // * // * @return test result. // */ // public abstract Map<String, Double> test(); // // /** // * Calculate p-values of Goodness-of-Fit test in parallel. // * // * @return test result. // */ // public Map<String, Double> testInParallel() { // ForkJoinPool pool = new ForkJoinPool(); // try { // return testInParallel(pool); // // } finally { // pool.shutdown(); // try { // pool.awaitTermination(1, TimeUnit.SECONDS); // } catch (InterruptedException ignore) { // } // } // } // // /** // * Calculate p-values of Goodness-of-Fit test in parallel using given {@link ForkJoinPool} instance. // * // * @param pool Fork/Join pool to execute tasks in paralle. // * @return test result. // */ // public abstract Map<String, Double> testInParallel(ForkJoinPool pool); // // /** // * Runs Goodness-of-Fit tests and verifis whether the test failed to reject the null hypothesis // * (which means the random sequence that was generated by random number generator can be described as random) or not. // */ // public void testAndVerify() { // Map<String, Double> result = test(); // // result.forEach((t, p) -> // assertThat(p) // .describedAs("At a significance level of %e, the Goodness-of-Fit test of [%s] should fail to reject null hypothesis (The p-value %f should be greater than or equal to %e).\n" + // "This means that the random sequence generated by the random number generator [%s] fit the theoretical probability distribution.", // significanceLevel, t, p, significanceLevel, // rngName) // .isGreaterThanOrEqualTo(significanceLevel)); // } // } // // Path: fast-rng-test/src/main/java/biz/k11i/rng/test/util/distribution/ProbabilityDistributions.java // public interface ProbabilityDistributions { // static ContinuousDistribution gaussian(double mean, double sd) { // return new Gaussian(mean, sd); // } // // static ContinuousDistribution gamma(double shape, double scale) { // return new Gamma(shape, scale); // } // // static ContinuousDistribution beta(double alpha, double beta) { // return new Beta(alpha, beta); // } // // static ContinuousDistribution wrap(RealDistribution distribution) { // return new CommonsMath3DistributionWrapper.Continuous(distribution); // } // // static DiscreteDistribution wrap(IntegerDistribution distribution) { // return new CommonsMath3DistributionWrapper.Discrete(distribution); // } // }
import biz.k11i.rng.test.gof.GoodnessOfFitTest; import biz.k11i.rng.test.util.distribution.ProbabilityDistributions; import org.junit.jupiter.api.Test; import java.util.Random; import static org.assertj.core.api.Assertions.assertThatThrownBy;
package biz.k11i.rng.test; class SecondLevelTestTest { @Test void test() { GoodnessOfFitTest gofTest = GoodnessOfFitTest.continuous()
// Path: fast-rng-test/src/main/java/biz/k11i/rng/test/gof/GoodnessOfFitTest.java // @SuppressWarnings("unused") // public abstract class GoodnessOfFitTest { // static class BuilderBase<SELF extends BuilderBase<SELF>> { // @SuppressWarnings("unchecked") // private final SELF self = (SELF) this; // // int numRandomValues; // double significanceLevel = DEFAULT_SIGNIFICANCE_LEVEL; // // public SELF numRandomValues(int numRandomValues) { // this.numRandomValues = numRandomValues; // return self; // } // // public SELF significanceLevel(double significanceLevel) { // this.significanceLevel = significanceLevel; // return self; // } // } // // /** Default significance level (0.1%) */ // private static final double DEFAULT_SIGNIFICANCE_LEVEL = 0.001; // // /** Name of the random number generator to be tested */ // public final String rngName; // // /** Significance level to reject the null hypothesis */ // public final double significanceLevel; // // GoodnessOfFitTest(String rngName, double significanceLevel) { // this.rngName = rngName; // this.significanceLevel = significanceLevel; // } // // /** // * Returns {@link ContinuousGofTest} builder object. // * // * @return builder object. // */ // public static ContinuousGofTest.Builder continuous() { // return new ContinuousGofTest.Builder(); // } // // /** // * Returns {@link DiscreteGofTest} builder object. // * // * @return builder obbject. // */ // public static DiscreteGofTest.Builder discrete() { // return new DiscreteGofTest.Builder(); // } // // /** // * Calculate p-values of Goodness-of-Fit test. // * // * @return test result. // */ // public abstract Map<String, Double> test(); // // /** // * Calculate p-values of Goodness-of-Fit test in parallel. // * // * @return test result. // */ // public Map<String, Double> testInParallel() { // ForkJoinPool pool = new ForkJoinPool(); // try { // return testInParallel(pool); // // } finally { // pool.shutdown(); // try { // pool.awaitTermination(1, TimeUnit.SECONDS); // } catch (InterruptedException ignore) { // } // } // } // // /** // * Calculate p-values of Goodness-of-Fit test in parallel using given {@link ForkJoinPool} instance. // * // * @param pool Fork/Join pool to execute tasks in paralle. // * @return test result. // */ // public abstract Map<String, Double> testInParallel(ForkJoinPool pool); // // /** // * Runs Goodness-of-Fit tests and verifis whether the test failed to reject the null hypothesis // * (which means the random sequence that was generated by random number generator can be described as random) or not. // */ // public void testAndVerify() { // Map<String, Double> result = test(); // // result.forEach((t, p) -> // assertThat(p) // .describedAs("At a significance level of %e, the Goodness-of-Fit test of [%s] should fail to reject null hypothesis (The p-value %f should be greater than or equal to %e).\n" + // "This means that the random sequence generated by the random number generator [%s] fit the theoretical probability distribution.", // significanceLevel, t, p, significanceLevel, // rngName) // .isGreaterThanOrEqualTo(significanceLevel)); // } // } // // Path: fast-rng-test/src/main/java/biz/k11i/rng/test/util/distribution/ProbabilityDistributions.java // public interface ProbabilityDistributions { // static ContinuousDistribution gaussian(double mean, double sd) { // return new Gaussian(mean, sd); // } // // static ContinuousDistribution gamma(double shape, double scale) { // return new Gamma(shape, scale); // } // // static ContinuousDistribution beta(double alpha, double beta) { // return new Beta(alpha, beta); // } // // static ContinuousDistribution wrap(RealDistribution distribution) { // return new CommonsMath3DistributionWrapper.Continuous(distribution); // } // // static DiscreteDistribution wrap(IntegerDistribution distribution) { // return new CommonsMath3DistributionWrapper.Discrete(distribution); // } // } // Path: fast-rng-test/src/test/java/biz/k11i/rng/test/SecondLevelTestTest.java import biz.k11i.rng.test.gof.GoodnessOfFitTest; import biz.k11i.rng.test.util.distribution.ProbabilityDistributions; import org.junit.jupiter.api.Test; import java.util.Random; import static org.assertj.core.api.Assertions.assertThatThrownBy; package biz.k11i.rng.test; class SecondLevelTestTest { @Test void test() { GoodnessOfFitTest gofTest = GoodnessOfFitTest.continuous()
.probabilityDistribution(ProbabilityDistributions.gaussian(0.0, 1.002 /* not 1.0 */))
komiya-atsushi/fast-rng-java
fast-rng/src/main/java/biz/k11i/rng/BetaRNG.java
// Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double exp(double value) { // return JafamaMath.exp(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double log(double value) { // return JafamaMath.log(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double pow(double value, double power) { // return JafamaMath.pow(value, power); // }
import java.util.Random; import static biz.k11i.util.MathFunctions.exp; import static biz.k11i.util.MathFunctions.log; import static biz.k11i.util.MathFunctions.pow;
// min <= 1, max = 1 if (min == 1.0) { // max = 1, min = 1 return BetaRNGAlgorithms.Unif.INSTANCE; } return BetaRNGAlgorithms.CdfInversion.INSTANCE; } } } class BetaRNGAlgorithms { /** * Implementation of Beta random number generator using Jöhnk's algorithm. * <p> * Jöhnk, M. D. * <i>"Erzeugung von betaverteilten und gammaverteilten Zufallszahlen."</i> * Metrika 8.1 (1964): 5-15. * </p> */ static class Johnk implements BetaRNG { static final BetaRNG INSTANCE = new Johnk(); @Override public double generate(Random random, double alpha, double beta) { while (true) {
// Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double exp(double value) { // return JafamaMath.exp(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double log(double value) { // return JafamaMath.log(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double pow(double value, double power) { // return JafamaMath.pow(value, power); // } // Path: fast-rng/src/main/java/biz/k11i/rng/BetaRNG.java import java.util.Random; import static biz.k11i.util.MathFunctions.exp; import static biz.k11i.util.MathFunctions.log; import static biz.k11i.util.MathFunctions.pow; // min <= 1, max = 1 if (min == 1.0) { // max = 1, min = 1 return BetaRNGAlgorithms.Unif.INSTANCE; } return BetaRNGAlgorithms.CdfInversion.INSTANCE; } } } class BetaRNGAlgorithms { /** * Implementation of Beta random number generator using Jöhnk's algorithm. * <p> * Jöhnk, M. D. * <i>"Erzeugung von betaverteilten und gammaverteilten Zufallszahlen."</i> * Metrika 8.1 (1964): 5-15. * </p> */ static class Johnk implements BetaRNG { static final BetaRNG INSTANCE = new Johnk(); @Override public double generate(Random random, double alpha, double beta) { while (true) {
double u = log(random.nextDouble()) / alpha;
komiya-atsushi/fast-rng-java
fast-rng/src/main/java/biz/k11i/rng/BetaRNG.java
// Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double exp(double value) { // return JafamaMath.exp(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double log(double value) { // return JafamaMath.log(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double pow(double value, double power) { // return JafamaMath.pow(value, power); // }
import java.util.Random; import static biz.k11i.util.MathFunctions.exp; import static biz.k11i.util.MathFunctions.log; import static biz.k11i.util.MathFunctions.pow;
if (min == 1.0) { // max = 1, min = 1 return BetaRNGAlgorithms.Unif.INSTANCE; } return BetaRNGAlgorithms.CdfInversion.INSTANCE; } } } class BetaRNGAlgorithms { /** * Implementation of Beta random number generator using Jöhnk's algorithm. * <p> * Jöhnk, M. D. * <i>"Erzeugung von betaverteilten und gammaverteilten Zufallszahlen."</i> * Metrika 8.1 (1964): 5-15. * </p> */ static class Johnk implements BetaRNG { static final BetaRNG INSTANCE = new Johnk(); @Override public double generate(Random random, double alpha, double beta) { while (true) { double u = log(random.nextDouble()) / alpha; double v = log(random.nextDouble()) / beta;
// Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double exp(double value) { // return JafamaMath.exp(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double log(double value) { // return JafamaMath.log(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double pow(double value, double power) { // return JafamaMath.pow(value, power); // } // Path: fast-rng/src/main/java/biz/k11i/rng/BetaRNG.java import java.util.Random; import static biz.k11i.util.MathFunctions.exp; import static biz.k11i.util.MathFunctions.log; import static biz.k11i.util.MathFunctions.pow; if (min == 1.0) { // max = 1, min = 1 return BetaRNGAlgorithms.Unif.INSTANCE; } return BetaRNGAlgorithms.CdfInversion.INSTANCE; } } } class BetaRNGAlgorithms { /** * Implementation of Beta random number generator using Jöhnk's algorithm. * <p> * Jöhnk, M. D. * <i>"Erzeugung von betaverteilten und gammaverteilten Zufallszahlen."</i> * Metrika 8.1 (1964): 5-15. * </p> */ static class Johnk implements BetaRNG { static final BetaRNG INSTANCE = new Johnk(); @Override public double generate(Random random, double alpha, double beta) { while (true) { double u = log(random.nextDouble()) / alpha; double v = log(random.nextDouble()) / beta;
double uu = exp(u);
komiya-atsushi/fast-rng-java
fast-rng/src/main/java/biz/k11i/rng/BetaRNG.java
// Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double exp(double value) { // return JafamaMath.exp(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double log(double value) { // return JafamaMath.log(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double pow(double value, double power) { // return JafamaMath.pow(value, power); // }
import java.util.Random; import static biz.k11i.util.MathFunctions.exp; import static biz.k11i.util.MathFunctions.log; import static biz.k11i.util.MathFunctions.pow;
double logM = u > v ? u : v; u -= logM; v -= logM; return exp(u - log(exp(u) + exp(v))); } } } } /** * Implementation of Beta random number generator using Sakasegawa's B00 algorithm. * <p> * Sakasegawa, H. * <i>"Stratified rejection and squeeze method for generating beta random numbers."</i> * Annals of the Institute of Statistical Mathematics 35.1 (1983): 291-302. * </p> */ static class B00 implements BetaRNG { static final BetaRNG INSTANCE = new B00(); @Override public double generate(Random random, double alpha, double beta) { double t = (1 - alpha) / (2 - alpha - beta); double s = (beta - alpha) * (1 - alpha - beta); double r = alpha * (1 - alpha); t -= ((s * t + 2 * r) * t - r) / 2 * (s * t + r); double p = t / alpha; double q = (1 - t) / beta;
// Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double exp(double value) { // return JafamaMath.exp(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double log(double value) { // return JafamaMath.log(value); // } // // Path: fast-rng/src/main/java/biz/k11i/util/MathFunctions.java // public static final double pow(double value, double power) { // return JafamaMath.pow(value, power); // } // Path: fast-rng/src/main/java/biz/k11i/rng/BetaRNG.java import java.util.Random; import static biz.k11i.util.MathFunctions.exp; import static biz.k11i.util.MathFunctions.log; import static biz.k11i.util.MathFunctions.pow; double logM = u > v ? u : v; u -= logM; v -= logM; return exp(u - log(exp(u) + exp(v))); } } } } /** * Implementation of Beta random number generator using Sakasegawa's B00 algorithm. * <p> * Sakasegawa, H. * <i>"Stratified rejection and squeeze method for generating beta random numbers."</i> * Annals of the Institute of Statistical Mathematics 35.1 (1983): 291-302. * </p> */ static class B00 implements BetaRNG { static final BetaRNG INSTANCE = new B00(); @Override public double generate(Random random, double alpha, double beta) { double t = (1 - alpha) / (2 - alpha - beta); double s = (beta - alpha) * (1 - alpha - beta); double r = alpha * (1 - alpha); t -= ((s * t + 2 * r) * t - r) / 2 * (s * t + r); double p = t / alpha; double q = (1 - t) / beta;
s = pow((1 - t), beta - 1);
komiya-atsushi/fast-rng-java
benchmark/src/jmh/java/biz/k11i/rng/GammaBenchmark.java
// Path: benchmark/src/jmh/java/biz/k11i/rng/util/MtRandom.java // public class MtRandom extends Random { // private final MersenneTwister mersenneTwister; // // public MtRandom() { // mersenneTwister = new MersenneTwister(); // } // // public MtRandom(int seed) { // mersenneTwister = new MersenneTwister(seed); // } // // @Override // public boolean nextBoolean() { // return mersenneTwister.nextBoolean(); // } // // @Override // public void nextBytes(byte[] bytes) { // mersenneTwister.nextBytes(bytes); // } // // @Override // public double nextDouble() { // return mersenneTwister.nextDouble(); // } // // @Override // public float nextFloat() { // return mersenneTwister.nextFloat(); // } // // @Override // public double nextGaussian() { // return mersenneTwister.nextGaussian(); // } // // @Override // public int nextInt() { // return mersenneTwister.nextInt(); // } // // @Override // public int nextInt(int n) throws IllegalArgumentException { // return mersenneTwister.nextInt(n); // } // // @Override // public long nextLong() { // return mersenneTwister.nextLong(); // } // } // // Path: benchmark/src/jmh/java/biz/k11i/rng/util/ParameterPool.java // public class ParameterPool { // private double[] parameters; // private int index; // // public ParameterPool(int seed, int count, double theta) { // parameters = new double[count]; // MtRandom r = new MtRandom(seed); // // for (int i = 0; i < count; i++) { // parameters[i] = Math.nextUp(ExponentialRNG.FAST_RNG.generate(r, theta)); // } // } // // public double next() { // if (index >= parameters.length) { // index = 0; // } // // return parameters[index++]; // } // }
import biz.k11i.rng.util.MtRandom; import biz.k11i.rng.util.ParameterPool; import org.apache.commons.math3.distribution.GammaDistribution; import org.apache.commons.math3.random.MersenneTwister; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import java.util.Random;
package biz.k11i.rng; public class GammaBenchmark { @State(Scope.Benchmark) public static class FixedParameters { @Param({"0.05", "0.1", "0.2", "0.5", "0.9", "1.0", "1.1", "40.0", "10000.0"}) public double shape; public double scale = 1.0;
// Path: benchmark/src/jmh/java/biz/k11i/rng/util/MtRandom.java // public class MtRandom extends Random { // private final MersenneTwister mersenneTwister; // // public MtRandom() { // mersenneTwister = new MersenneTwister(); // } // // public MtRandom(int seed) { // mersenneTwister = new MersenneTwister(seed); // } // // @Override // public boolean nextBoolean() { // return mersenneTwister.nextBoolean(); // } // // @Override // public void nextBytes(byte[] bytes) { // mersenneTwister.nextBytes(bytes); // } // // @Override // public double nextDouble() { // return mersenneTwister.nextDouble(); // } // // @Override // public float nextFloat() { // return mersenneTwister.nextFloat(); // } // // @Override // public double nextGaussian() { // return mersenneTwister.nextGaussian(); // } // // @Override // public int nextInt() { // return mersenneTwister.nextInt(); // } // // @Override // public int nextInt(int n) throws IllegalArgumentException { // return mersenneTwister.nextInt(n); // } // // @Override // public long nextLong() { // return mersenneTwister.nextLong(); // } // } // // Path: benchmark/src/jmh/java/biz/k11i/rng/util/ParameterPool.java // public class ParameterPool { // private double[] parameters; // private int index; // // public ParameterPool(int seed, int count, double theta) { // parameters = new double[count]; // MtRandom r = new MtRandom(seed); // // for (int i = 0; i < count; i++) { // parameters[i] = Math.nextUp(ExponentialRNG.FAST_RNG.generate(r, theta)); // } // } // // public double next() { // if (index >= parameters.length) { // index = 0; // } // // return parameters[index++]; // } // } // Path: benchmark/src/jmh/java/biz/k11i/rng/GammaBenchmark.java import biz.k11i.rng.util.MtRandom; import biz.k11i.rng.util.ParameterPool; import org.apache.commons.math3.distribution.GammaDistribution; import org.apache.commons.math3.random.MersenneTwister; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import java.util.Random; package biz.k11i.rng; public class GammaBenchmark { @State(Scope.Benchmark) public static class FixedParameters { @Param({"0.05", "0.1", "0.2", "0.5", "0.9", "1.0", "1.1", "40.0", "10000.0"}) public double shape; public double scale = 1.0;
private Random random = new MtRandom();
komiya-atsushi/fast-rng-java
benchmark/src/jmh/java/biz/k11i/rng/GammaBenchmark.java
// Path: benchmark/src/jmh/java/biz/k11i/rng/util/MtRandom.java // public class MtRandom extends Random { // private final MersenneTwister mersenneTwister; // // public MtRandom() { // mersenneTwister = new MersenneTwister(); // } // // public MtRandom(int seed) { // mersenneTwister = new MersenneTwister(seed); // } // // @Override // public boolean nextBoolean() { // return mersenneTwister.nextBoolean(); // } // // @Override // public void nextBytes(byte[] bytes) { // mersenneTwister.nextBytes(bytes); // } // // @Override // public double nextDouble() { // return mersenneTwister.nextDouble(); // } // // @Override // public float nextFloat() { // return mersenneTwister.nextFloat(); // } // // @Override // public double nextGaussian() { // return mersenneTwister.nextGaussian(); // } // // @Override // public int nextInt() { // return mersenneTwister.nextInt(); // } // // @Override // public int nextInt(int n) throws IllegalArgumentException { // return mersenneTwister.nextInt(n); // } // // @Override // public long nextLong() { // return mersenneTwister.nextLong(); // } // } // // Path: benchmark/src/jmh/java/biz/k11i/rng/util/ParameterPool.java // public class ParameterPool { // private double[] parameters; // private int index; // // public ParameterPool(int seed, int count, double theta) { // parameters = new double[count]; // MtRandom r = new MtRandom(seed); // // for (int i = 0; i < count; i++) { // parameters[i] = Math.nextUp(ExponentialRNG.FAST_RNG.generate(r, theta)); // } // } // // public double next() { // if (index >= parameters.length) { // index = 0; // } // // return parameters[index++]; // } // }
import biz.k11i.rng.util.MtRandom; import biz.k11i.rng.util.ParameterPool; import org.apache.commons.math3.distribution.GammaDistribution; import org.apache.commons.math3.random.MersenneTwister; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import java.util.Random;
@Setup public void setUp() { gammaDistribution = new GammaDistribution( new MersenneTwister(), shape, scale, GammaDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY); } @Benchmark public double commonsMath3() { return gammaDistribution.sample(); } @Benchmark public double fastRng() { return GammaRNG.FAST_RNG.generate(random, shape, scale); } @Benchmark public double generalRng() { return GammaRNG.GENERAL_RNG.generate(random, shape, scale); } } @State(Scope.Benchmark) public static class ArbitraryParameters { private double scale = 1.0; private Random random = new MtRandom(); private MersenneTwister mersenneTwister = new MersenneTwister();
// Path: benchmark/src/jmh/java/biz/k11i/rng/util/MtRandom.java // public class MtRandom extends Random { // private final MersenneTwister mersenneTwister; // // public MtRandom() { // mersenneTwister = new MersenneTwister(); // } // // public MtRandom(int seed) { // mersenneTwister = new MersenneTwister(seed); // } // // @Override // public boolean nextBoolean() { // return mersenneTwister.nextBoolean(); // } // // @Override // public void nextBytes(byte[] bytes) { // mersenneTwister.nextBytes(bytes); // } // // @Override // public double nextDouble() { // return mersenneTwister.nextDouble(); // } // // @Override // public float nextFloat() { // return mersenneTwister.nextFloat(); // } // // @Override // public double nextGaussian() { // return mersenneTwister.nextGaussian(); // } // // @Override // public int nextInt() { // return mersenneTwister.nextInt(); // } // // @Override // public int nextInt(int n) throws IllegalArgumentException { // return mersenneTwister.nextInt(n); // } // // @Override // public long nextLong() { // return mersenneTwister.nextLong(); // } // } // // Path: benchmark/src/jmh/java/biz/k11i/rng/util/ParameterPool.java // public class ParameterPool { // private double[] parameters; // private int index; // // public ParameterPool(int seed, int count, double theta) { // parameters = new double[count]; // MtRandom r = new MtRandom(seed); // // for (int i = 0; i < count; i++) { // parameters[i] = Math.nextUp(ExponentialRNG.FAST_RNG.generate(r, theta)); // } // } // // public double next() { // if (index >= parameters.length) { // index = 0; // } // // return parameters[index++]; // } // } // Path: benchmark/src/jmh/java/biz/k11i/rng/GammaBenchmark.java import biz.k11i.rng.util.MtRandom; import biz.k11i.rng.util.ParameterPool; import org.apache.commons.math3.distribution.GammaDistribution; import org.apache.commons.math3.random.MersenneTwister; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import java.util.Random; @Setup public void setUp() { gammaDistribution = new GammaDistribution( new MersenneTwister(), shape, scale, GammaDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY); } @Benchmark public double commonsMath3() { return gammaDistribution.sample(); } @Benchmark public double fastRng() { return GammaRNG.FAST_RNG.generate(random, shape, scale); } @Benchmark public double generalRng() { return GammaRNG.GENERAL_RNG.generate(random, shape, scale); } } @State(Scope.Benchmark) public static class ArbitraryParameters { private double scale = 1.0; private Random random = new MtRandom(); private MersenneTwister mersenneTwister = new MersenneTwister();
private ParameterPool parameters = new ParameterPool(12345, 10000, 10.0);
komiya-atsushi/fast-rng-java
benchmark/src/jmh/java/biz/k11i/rng/ExponentialBenchmark.java
// Path: benchmark/src/jmh/java/biz/k11i/rng/util/ThreadLocalRandomGenerator.java // public class ThreadLocalRandomGenerator implements RandomGenerator { // @Override // public void setSeed(int seed) { // ThreadLocalRandom.current().setSeed(seed); // } // // @Override // public void setSeed(int[] seed) { // throw new UnsupportedOperationException(); // } // // @Override // public void setSeed(long seed) { // ThreadLocalRandom.current().setSeed(seed); // } // // @Override // public void nextBytes(byte[] bytes) { // ThreadLocalRandom.current().nextBytes(bytes); // } // // @Override // public int nextInt() { // return ThreadLocalRandom.current().nextInt(); // } // // @Override // public int nextInt(int n) { // return ThreadLocalRandom.current().nextInt(n); // } // // @Override // public long nextLong() { // return ThreadLocalRandom.current().nextLong(); // } // // @Override // public boolean nextBoolean() { // return ThreadLocalRandom.current().nextBoolean(); // } // // @Override // public float nextFloat() { // return ThreadLocalRandom.current().nextFloat(); // } // // @Override // public double nextDouble() { // return ThreadLocalRandom.current().nextDouble(); // } // // @Override // public double nextGaussian() { // return ThreadLocalRandom.current().nextGaussian(); // } // }
import biz.k11i.rng.util.ThreadLocalRandomGenerator; import org.apache.commons.math3.distribution.ExponentialDistribution; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import java.util.concurrent.ThreadLocalRandom;
package biz.k11i.rng; @State(Scope.Benchmark) public class ExponentialBenchmark { private ExponentialDistribution exponentialDistribution; @Setup public void setUp() { exponentialDistribution = new ExponentialDistribution(
// Path: benchmark/src/jmh/java/biz/k11i/rng/util/ThreadLocalRandomGenerator.java // public class ThreadLocalRandomGenerator implements RandomGenerator { // @Override // public void setSeed(int seed) { // ThreadLocalRandom.current().setSeed(seed); // } // // @Override // public void setSeed(int[] seed) { // throw new UnsupportedOperationException(); // } // // @Override // public void setSeed(long seed) { // ThreadLocalRandom.current().setSeed(seed); // } // // @Override // public void nextBytes(byte[] bytes) { // ThreadLocalRandom.current().nextBytes(bytes); // } // // @Override // public int nextInt() { // return ThreadLocalRandom.current().nextInt(); // } // // @Override // public int nextInt(int n) { // return ThreadLocalRandom.current().nextInt(n); // } // // @Override // public long nextLong() { // return ThreadLocalRandom.current().nextLong(); // } // // @Override // public boolean nextBoolean() { // return ThreadLocalRandom.current().nextBoolean(); // } // // @Override // public float nextFloat() { // return ThreadLocalRandom.current().nextFloat(); // } // // @Override // public double nextDouble() { // return ThreadLocalRandom.current().nextDouble(); // } // // @Override // public double nextGaussian() { // return ThreadLocalRandom.current().nextGaussian(); // } // } // Path: benchmark/src/jmh/java/biz/k11i/rng/ExponentialBenchmark.java import biz.k11i.rng.util.ThreadLocalRandomGenerator; import org.apache.commons.math3.distribution.ExponentialDistribution; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import java.util.concurrent.ThreadLocalRandom; package biz.k11i.rng; @State(Scope.Benchmark) public class ExponentialBenchmark { private ExponentialDistribution exponentialDistribution; @Setup public void setUp() { exponentialDistribution = new ExponentialDistribution(
new ThreadLocalRandomGenerator(),
futurice/meeting-room-tablet
app/src/main/java/com/futurice/android/reservator/view/wizard/WizardAccountSelectionFragment.java
// Path: app/src/main/java/com/futurice/android/reservator/common/PreferenceManager.java // public class PreferenceManager { // private static PreferenceManager sharedInstance = null; // // public static PreferenceManager getInstance(Context context) { // if (sharedInstance == null) { // sharedInstance = new PreferenceManager(context); // } // return sharedInstance; // } // // final static String PREFERENCES_IDENTIFIER = "ReservatorPreferences"; // // final static String PREFERENCES_DEFAULT_ACCOUNT = "googleAccount"; // final static String PREFERENCES_DEFAULT_USER_NAME = "reservationAccount"; // final static String PREFERENCES_ADDRESSBOOK_ENABLED = "addressBookOption"; // final static String PREFERENCES_UNSELECTED_ROOMS = "unselectedRooms"; // final static String PREFERENCES_SELECTED_ROOM = "roomName"; // final static String PREFERENCES_CONFIGURED = "preferencedConfigured"; // final static String PREFERENCES_CALENDAR_MODE = "resourcesOnly"; // // // final SharedPreferences preferences; // // private PreferenceManager(Context c) { // preferences = c.getSharedPreferences(PREFERENCES_IDENTIFIER, // Context.MODE_PRIVATE); // } // // public String getDefaultCalendarAccount() { // return preferences.getString(PREFERENCES_DEFAULT_ACCOUNT, null); // } // // public void setDefaultCalendarAccount(String account) { // SharedPreferences.Editor editor = preferences.edit(); // editor.putString(PREFERENCES_DEFAULT_ACCOUNT, account); // editor.apply(); // } // // public String getDefaultUserName() { // return preferences.getString(PREFERENCES_DEFAULT_USER_NAME, null); // } // // public void setDefaultUserName(String user) { // SharedPreferences.Editor editor = preferences.edit(); // editor.putString(PREFERENCES_DEFAULT_USER_NAME, user); // editor.apply(); // } // // public boolean getAddressBookEnabled() { // return preferences.getBoolean(PREFERENCES_ADDRESSBOOK_ENABLED, false); // } // // public void setAddressBookEnabled(boolean enabled) { // SharedPreferences.Editor editor = preferences.edit(); // editor.putBoolean(PREFERENCES_ADDRESSBOOK_ENABLED, enabled); // editor.apply(); // } // // public HashSet<String> getUnselectedRooms() { // return (HashSet<String>) preferences // .getStringSet(PREFERENCES_UNSELECTED_ROOMS, // new HashSet<String>()); // } // // // public void setUnselectedRooms(HashSet<String> rooms) { // SharedPreferences.Editor editor = preferences.edit(); // editor.putStringSet(PREFERENCES_UNSELECTED_ROOMS, // new HashSet<String>(rooms)); // editor.apply(); // } // // // public String getSelectedRoom() { // return preferences.getString(PREFERENCES_SELECTED_ROOM, null); // } // // public void setSelectedRoom(String newRoom) { // SharedPreferences.Editor editor = preferences.edit(); // editor.putString(PREFERENCES_SELECTED_ROOM, newRoom); // editor.apply(); // } // // // public boolean getApplicationConfigured() { // return preferences.getBoolean(PREFERENCES_CONFIGURED, false); // } // // public void setApplicationConfigured(boolean configured) { // SharedPreferences.Editor editor = preferences.edit(); // editor.putBoolean(PREFERENCES_CONFIGURED, configured); // editor.apply(); // } // // // public void removeAllSettings() { // SharedPreferences.Editor editor = preferences.edit(); // Map<String, ?> keys = preferences.getAll(); // for (Map.Entry<String, ?> entry : keys.entrySet()) { // editor.remove(entry.getKey()); // } // editor.apply(); // } // // public PlatformCalendarDataProxy.Mode getCalendarMode() { // String name = preferences.getString(PREFERENCES_CALENDAR_MODE, null); // if (name == null) { // return null; // } // return Enum.valueOf(PlatformCalendarDataProxy.Mode.class, name); // } // // public void setCalendarMode(PlatformCalendarDataProxy.Mode mode) { // SharedPreferences.Editor editor = preferences.edit(); // editor.putString(PREFERENCES_CALENDAR_MODE, mode.name()); // editor.apply(); // } // // }
import android.accounts.Account; import android.accounts.AccountManager; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import com.futurice.android.reservator.R; import com.futurice.android.reservator.common.PreferenceManager; import com.github.paolorotolo.appintro.ISlidePolicy; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder;
package com.futurice.android.reservator.view.wizard; /** * Created by shoj on 10/11/2016. */ public final class WizardAccountSelectionFragment extends android.support.v4.app.Fragment implements ISlidePolicy { @BindView(R.id.wizard_accounts_radiogroup) RadioGroup accountsRadioGroup = null; @BindView(R.id.wizard_accounts_title) TextView title; Unbinder unbinder; AlertDialog alertDialog; @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.wizard_account_selection, container, false); unbinder = ButterKnife.bind(this, view); title.setText(R.string.selectGoogleAccount); accountsRadioGroup.setOnCheckedChangeListener( new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged( RadioGroup group, int checkedId) { String account = ((RadioButton) group.findViewById(checkedId)) .getText().toString();
// Path: app/src/main/java/com/futurice/android/reservator/common/PreferenceManager.java // public class PreferenceManager { // private static PreferenceManager sharedInstance = null; // // public static PreferenceManager getInstance(Context context) { // if (sharedInstance == null) { // sharedInstance = new PreferenceManager(context); // } // return sharedInstance; // } // // final static String PREFERENCES_IDENTIFIER = "ReservatorPreferences"; // // final static String PREFERENCES_DEFAULT_ACCOUNT = "googleAccount"; // final static String PREFERENCES_DEFAULT_USER_NAME = "reservationAccount"; // final static String PREFERENCES_ADDRESSBOOK_ENABLED = "addressBookOption"; // final static String PREFERENCES_UNSELECTED_ROOMS = "unselectedRooms"; // final static String PREFERENCES_SELECTED_ROOM = "roomName"; // final static String PREFERENCES_CONFIGURED = "preferencedConfigured"; // final static String PREFERENCES_CALENDAR_MODE = "resourcesOnly"; // // // final SharedPreferences preferences; // // private PreferenceManager(Context c) { // preferences = c.getSharedPreferences(PREFERENCES_IDENTIFIER, // Context.MODE_PRIVATE); // } // // public String getDefaultCalendarAccount() { // return preferences.getString(PREFERENCES_DEFAULT_ACCOUNT, null); // } // // public void setDefaultCalendarAccount(String account) { // SharedPreferences.Editor editor = preferences.edit(); // editor.putString(PREFERENCES_DEFAULT_ACCOUNT, account); // editor.apply(); // } // // public String getDefaultUserName() { // return preferences.getString(PREFERENCES_DEFAULT_USER_NAME, null); // } // // public void setDefaultUserName(String user) { // SharedPreferences.Editor editor = preferences.edit(); // editor.putString(PREFERENCES_DEFAULT_USER_NAME, user); // editor.apply(); // } // // public boolean getAddressBookEnabled() { // return preferences.getBoolean(PREFERENCES_ADDRESSBOOK_ENABLED, false); // } // // public void setAddressBookEnabled(boolean enabled) { // SharedPreferences.Editor editor = preferences.edit(); // editor.putBoolean(PREFERENCES_ADDRESSBOOK_ENABLED, enabled); // editor.apply(); // } // // public HashSet<String> getUnselectedRooms() { // return (HashSet<String>) preferences // .getStringSet(PREFERENCES_UNSELECTED_ROOMS, // new HashSet<String>()); // } // // // public void setUnselectedRooms(HashSet<String> rooms) { // SharedPreferences.Editor editor = preferences.edit(); // editor.putStringSet(PREFERENCES_UNSELECTED_ROOMS, // new HashSet<String>(rooms)); // editor.apply(); // } // // // public String getSelectedRoom() { // return preferences.getString(PREFERENCES_SELECTED_ROOM, null); // } // // public void setSelectedRoom(String newRoom) { // SharedPreferences.Editor editor = preferences.edit(); // editor.putString(PREFERENCES_SELECTED_ROOM, newRoom); // editor.apply(); // } // // // public boolean getApplicationConfigured() { // return preferences.getBoolean(PREFERENCES_CONFIGURED, false); // } // // public void setApplicationConfigured(boolean configured) { // SharedPreferences.Editor editor = preferences.edit(); // editor.putBoolean(PREFERENCES_CONFIGURED, configured); // editor.apply(); // } // // // public void removeAllSettings() { // SharedPreferences.Editor editor = preferences.edit(); // Map<String, ?> keys = preferences.getAll(); // for (Map.Entry<String, ?> entry : keys.entrySet()) { // editor.remove(entry.getKey()); // } // editor.apply(); // } // // public PlatformCalendarDataProxy.Mode getCalendarMode() { // String name = preferences.getString(PREFERENCES_CALENDAR_MODE, null); // if (name == null) { // return null; // } // return Enum.valueOf(PlatformCalendarDataProxy.Mode.class, name); // } // // public void setCalendarMode(PlatformCalendarDataProxy.Mode mode) { // SharedPreferences.Editor editor = preferences.edit(); // editor.putString(PREFERENCES_CALENDAR_MODE, mode.name()); // editor.apply(); // } // // } // Path: app/src/main/java/com/futurice/android/reservator/view/wizard/WizardAccountSelectionFragment.java import android.accounts.Account; import android.accounts.AccountManager; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import com.futurice.android.reservator.R; import com.futurice.android.reservator.common.PreferenceManager; import com.github.paolorotolo.appintro.ISlidePolicy; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; package com.futurice.android.reservator.view.wizard; /** * Created by shoj on 10/11/2016. */ public final class WizardAccountSelectionFragment extends android.support.v4.app.Fragment implements ISlidePolicy { @BindView(R.id.wizard_accounts_radiogroup) RadioGroup accountsRadioGroup = null; @BindView(R.id.wizard_accounts_title) TextView title; Unbinder unbinder; AlertDialog alertDialog; @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.wizard_account_selection, container, false); unbinder = ButterKnife.bind(this, view); title.setText(R.string.selectGoogleAccount); accountsRadioGroup.setOnCheckedChangeListener( new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged( RadioGroup group, int checkedId) { String account = ((RadioButton) group.findViewById(checkedId)) .getText().toString();
PreferenceManager.getInstance(getActivity())
futurice/meeting-room-tablet
app/src/main/java/com/futurice/android/reservator/model/platformcontacts/PlatformContactsAddressBook.java
// Path: app/src/main/java/com/futurice/android/reservator/model/AddressBook.java // public abstract class AddressBook { // private Vector<AddressBookEntry> entries; // private Set<AddressBookUpdatedListener> listeners = new HashSet<AddressBookUpdatedListener>(); // // public AddressBook() { // } // // protected abstract Vector<AddressBookEntry> fetchEntries() throws ReservatorException; // // public abstract void setCredentials(String username, String password); // // public Vector<AddressBookEntry> getEntries() throws ReservatorException { // return entries; // } // // public void prefetchEntries() { // if (entries == null) { // new PrefetchEntriesTask().execute(); // } // } // // public AddressBookEntry getEntryByName(String name) { // if (entries == null) { // return null; // no entries, no win // } // // for (AddressBookEntry entry : entries) { // if (entry.getName().equals(name)) { // return entry; // } // } // return null; // } // // public String toString() { // if (entries != null) // return entries.toString(); // return ""; // } // // /** // * Add a listener for this proxy. The listener will be notified after calls to refreshRooms and refreshRoomReservations finish or fail. // * // * @param listener // */ // public void addDataUpdatedListener(AddressBookUpdatedListener listener) { // listeners.add(listener); // } // // /** // * Remove a listener from this proxy. // * // * @param listener // */ // public void removeDataUpdatedListener(AddressBookUpdatedListener listener) { // listeners.remove(listener); // } // // private void notifyEntriesUpdated() { // synchronized (listeners) { // for (AddressBookUpdatedListener l : listeners) { // l.addressBookUpdated(); // } // } // } // // private void notifyAddressBookUpdateFailed(ReservatorException e) { // synchronized (listeners) { // for (AddressBookUpdatedListener l : listeners) { // l.addressBookUpdateFailed(e); // } // } // } // // public void refetchEntries() { // entries = null; // prefetchEntries(); // } // // private class PrefetchEntriesTask extends AsyncTask<Void, Void, Vector<AddressBookEntry>> { // ReservatorException e = null; // // @Override // protected Vector<AddressBookEntry> doInBackground(Void... params) { // try { // return fetchEntries(); // } catch (ReservatorException e) { // this.e = e; // return null; // } // } // // @Override // protected void onPostExecute(Vector<AddressBookEntry> entries) { // if (entries != null) { // AddressBook.this.entries = entries; // notifyEntriesUpdated(); // } else { // notifyAddressBookUpdateFailed(e); // } // } // } // } // // Path: app/src/main/java/com/futurice/android/reservator/model/AddressBookEntry.java // public class AddressBookEntry { // private String name, email; // // public AddressBookEntry(String name, String email) { // this.name = name; // this.email = email; // } // // public String getName() { // return name; // } // // public String getEmail() { // return email; // } // // public String toString() { // return getName() + " <" + getEmail() + ">"; // } // }
import android.content.ContentResolver; import android.database.Cursor; import android.provider.ContactsContract; import com.futurice.android.reservator.model.AddressBook; import com.futurice.android.reservator.model.AddressBookEntry; import com.futurice.android.reservator.model.ReservatorException; import java.util.Vector;
package com.futurice.android.reservator.model.platformcontacts; public class PlatformContactsAddressBook extends AddressBook { private final String GOOGLE_ACCOUNT_TYPE = "com.google"; private String account = null; private ContentResolver resolver; public PlatformContactsAddressBook(ContentResolver resolver) { super(); this.resolver = resolver; } /** * This is a heavy query, and should be called rarely. */ @Override
// Path: app/src/main/java/com/futurice/android/reservator/model/AddressBook.java // public abstract class AddressBook { // private Vector<AddressBookEntry> entries; // private Set<AddressBookUpdatedListener> listeners = new HashSet<AddressBookUpdatedListener>(); // // public AddressBook() { // } // // protected abstract Vector<AddressBookEntry> fetchEntries() throws ReservatorException; // // public abstract void setCredentials(String username, String password); // // public Vector<AddressBookEntry> getEntries() throws ReservatorException { // return entries; // } // // public void prefetchEntries() { // if (entries == null) { // new PrefetchEntriesTask().execute(); // } // } // // public AddressBookEntry getEntryByName(String name) { // if (entries == null) { // return null; // no entries, no win // } // // for (AddressBookEntry entry : entries) { // if (entry.getName().equals(name)) { // return entry; // } // } // return null; // } // // public String toString() { // if (entries != null) // return entries.toString(); // return ""; // } // // /** // * Add a listener for this proxy. The listener will be notified after calls to refreshRooms and refreshRoomReservations finish or fail. // * // * @param listener // */ // public void addDataUpdatedListener(AddressBookUpdatedListener listener) { // listeners.add(listener); // } // // /** // * Remove a listener from this proxy. // * // * @param listener // */ // public void removeDataUpdatedListener(AddressBookUpdatedListener listener) { // listeners.remove(listener); // } // // private void notifyEntriesUpdated() { // synchronized (listeners) { // for (AddressBookUpdatedListener l : listeners) { // l.addressBookUpdated(); // } // } // } // // private void notifyAddressBookUpdateFailed(ReservatorException e) { // synchronized (listeners) { // for (AddressBookUpdatedListener l : listeners) { // l.addressBookUpdateFailed(e); // } // } // } // // public void refetchEntries() { // entries = null; // prefetchEntries(); // } // // private class PrefetchEntriesTask extends AsyncTask<Void, Void, Vector<AddressBookEntry>> { // ReservatorException e = null; // // @Override // protected Vector<AddressBookEntry> doInBackground(Void... params) { // try { // return fetchEntries(); // } catch (ReservatorException e) { // this.e = e; // return null; // } // } // // @Override // protected void onPostExecute(Vector<AddressBookEntry> entries) { // if (entries != null) { // AddressBook.this.entries = entries; // notifyEntriesUpdated(); // } else { // notifyAddressBookUpdateFailed(e); // } // } // } // } // // Path: app/src/main/java/com/futurice/android/reservator/model/AddressBookEntry.java // public class AddressBookEntry { // private String name, email; // // public AddressBookEntry(String name, String email) { // this.name = name; // this.email = email; // } // // public String getName() { // return name; // } // // public String getEmail() { // return email; // } // // public String toString() { // return getName() + " <" + getEmail() + ">"; // } // } // Path: app/src/main/java/com/futurice/android/reservator/model/platformcontacts/PlatformContactsAddressBook.java import android.content.ContentResolver; import android.database.Cursor; import android.provider.ContactsContract; import com.futurice.android.reservator.model.AddressBook; import com.futurice.android.reservator.model.AddressBookEntry; import com.futurice.android.reservator.model.ReservatorException; import java.util.Vector; package com.futurice.android.reservator.model.platformcontacts; public class PlatformContactsAddressBook extends AddressBook { private final String GOOGLE_ACCOUNT_TYPE = "com.google"; private String account = null; private ContentResolver resolver; public PlatformContactsAddressBook(ContentResolver resolver) { super(); this.resolver = resolver; } /** * This is a heavy query, and should be called rarely. */ @Override
protected Vector<AddressBookEntry> fetchEntries() throws ReservatorException {
futurice/meeting-room-tablet
app/src/main/java/com/futurice/android/reservator/model/Room.java
// Path: app/src/main/java/com/futurice/android/reservator/common/Helpers.java // public class Helpers { // /** // * Read all from InputStream // * // * @param is Stream to read from // * @param size Guess the size of InputStream contents, give negative for the automatic // * @return // */ // public static String readFromInputStream(InputStream is, int size) { // try { // ByteArrayOutputStream os; // if (size <= 0) { // os = new ByteArrayOutputStream(); // } else { // os = new ByteArrayOutputStream(size); // } // byte buffer[] = new byte[4096]; // int len; // while ((len = is.read(buffer)) != -1) { // os.write(buffer, 0, len); // } // return os.toString("UTF-8"); // } catch (IOException e) { // Log.e("SOAP", "readFromInputStream", e); // return ""; // } // } // // // TODO: an hour and a half - and other common expressions // public static String humanizeTimeSpan(int minutes) { // if (minutes < 30) { // return Integer.toString(minutes) + " minutes"; // } else if (minutes < 45) { // return "half an hour"; // } else if (minutes < 60) { // return "45 minutes"; // } else if (minutes < 85) { // return "an hour"; // } else if (minutes < 110) { // return "an hour and a half"; // } else if (minutes < 24 * 60) { // return Integer.toString((minutes + 10) / 60) + " hours"; // } else { // return Integer.toString(minutes / (60 * 24)) + " days"; // } // } // // // For use in traffic lights // public static String humanizeTimeSpan2(int minutes) { // int hours = minutes / 60; // // if (minutes < 15) { // return getUnits(minutes, "minute", "minutes"); // } else if (minutes < 30) { // return getUnits(roundTo(minutes, 5), "minute", "minutes"); // } else if (minutes < 60) { // return getUnits(roundTo(minutes, 15), "minute", "minutes"); // } else if (minutes < 60 * 4) { // int hourMins = roundTo(minutes - hours * 60, 15); // if (hourMins == 60) { // hours++; // hourMins = 0; // } // // if (hourMins == 0) { // return getUnits(hours, "hour", "hours"); // } else { // return String.format(Locale.getDefault(), "%dh:%02dmin", hours, hourMins); // } // } else if (minutes < 24 * 60) { // return getUnits(hours, "hour", "hours"); // } else { // return getUnits(hours / 24, "day", "days"); // } // } // // private static String getUnits(int amount, String unitName, String unitNamePlural) { // if (amount == 1) return String.format("1 %s", unitName); // return String.format(Locale.getDefault(), "%d %s", amount, unitNamePlural); // } // // private static int roundTo(int in, int precision) { // return precision * ((int) Math.floor(in / (1.0 * precision))); // } // }
import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.List; import java.util.Vector; import com.futurice.android.reservator.common.Helpers;
} /** * Prerequisite: isFree * * @return true if room is continuously free now and for the rest of the day */ public boolean isFreeRestOfDay() { DateTime now = new DateTime(); DateTime max = now.add(Calendar.DAY_OF_YEAR, 1).stripTime(); TimeSpan restOfDay = new TimeSpan(now, max); for (Reservation r : reservations) { if (r.getTimeSpan().intersects(restOfDay)) return false; if (r.getStartTime().after(max)) return true; } return true; } public String getStatusText() { if (this.isFree()) { int freeMinutes = this.minutesFreeFromNow(); if (freeMinutes > FREE_THRESHOLD_MINUTES) { return "Free"; } else if (freeMinutes < RESERVED_THRESHOLD_MINUTES) { return "Reserved"; } else {
// Path: app/src/main/java/com/futurice/android/reservator/common/Helpers.java // public class Helpers { // /** // * Read all from InputStream // * // * @param is Stream to read from // * @param size Guess the size of InputStream contents, give negative for the automatic // * @return // */ // public static String readFromInputStream(InputStream is, int size) { // try { // ByteArrayOutputStream os; // if (size <= 0) { // os = new ByteArrayOutputStream(); // } else { // os = new ByteArrayOutputStream(size); // } // byte buffer[] = new byte[4096]; // int len; // while ((len = is.read(buffer)) != -1) { // os.write(buffer, 0, len); // } // return os.toString("UTF-8"); // } catch (IOException e) { // Log.e("SOAP", "readFromInputStream", e); // return ""; // } // } // // // TODO: an hour and a half - and other common expressions // public static String humanizeTimeSpan(int minutes) { // if (minutes < 30) { // return Integer.toString(minutes) + " minutes"; // } else if (minutes < 45) { // return "half an hour"; // } else if (minutes < 60) { // return "45 minutes"; // } else if (minutes < 85) { // return "an hour"; // } else if (minutes < 110) { // return "an hour and a half"; // } else if (minutes < 24 * 60) { // return Integer.toString((minutes + 10) / 60) + " hours"; // } else { // return Integer.toString(minutes / (60 * 24)) + " days"; // } // } // // // For use in traffic lights // public static String humanizeTimeSpan2(int minutes) { // int hours = minutes / 60; // // if (minutes < 15) { // return getUnits(minutes, "minute", "minutes"); // } else if (minutes < 30) { // return getUnits(roundTo(minutes, 5), "minute", "minutes"); // } else if (minutes < 60) { // return getUnits(roundTo(minutes, 15), "minute", "minutes"); // } else if (minutes < 60 * 4) { // int hourMins = roundTo(minutes - hours * 60, 15); // if (hourMins == 60) { // hours++; // hourMins = 0; // } // // if (hourMins == 0) { // return getUnits(hours, "hour", "hours"); // } else { // return String.format(Locale.getDefault(), "%dh:%02dmin", hours, hourMins); // } // } else if (minutes < 24 * 60) { // return getUnits(hours, "hour", "hours"); // } else { // return getUnits(hours / 24, "day", "days"); // } // } // // private static String getUnits(int amount, String unitName, String unitNamePlural) { // if (amount == 1) return String.format("1 %s", unitName); // return String.format(Locale.getDefault(), "%d %s", amount, unitNamePlural); // } // // private static int roundTo(int in, int precision) { // return precision * ((int) Math.floor(in / (1.0 * precision))); // } // } // Path: app/src/main/java/com/futurice/android/reservator/model/Room.java import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.List; import java.util.Vector; import com.futurice.android.reservator.common.Helpers; } /** * Prerequisite: isFree * * @return true if room is continuously free now and for the rest of the day */ public boolean isFreeRestOfDay() { DateTime now = new DateTime(); DateTime max = now.add(Calendar.DAY_OF_YEAR, 1).stripTime(); TimeSpan restOfDay = new TimeSpan(now, max); for (Reservation r : reservations) { if (r.getTimeSpan().intersects(restOfDay)) return false; if (r.getStartTime().after(max)) return true; } return true; } public String getStatusText() { if (this.isFree()) { int freeMinutes = this.minutesFreeFromNow(); if (freeMinutes > FREE_THRESHOLD_MINUTES) { return "Free"; } else if (freeMinutes < RESERVED_THRESHOLD_MINUTES) { return "Reserved"; } else {
return "Free for " + Helpers.humanizeTimeSpan(freeMinutes);
futurice/meeting-room-tablet
app/src/main/java/com/futurice/android/reservator/model/CachedDataProxy.java
// Path: app/src/main/java/com/futurice/android/reservator/common/CacheMap.java // public class CacheMap<K, V> { // private final HashMap<K, Bucket> map; // // public CacheMap() { // this.map = new HashMap<K, Bucket>(); // } // // public V get(K key) { // Bucket b = map.get(key); // // if (b == null || b.getExpireMillis() < System.currentTimeMillis()) { // return null; // } else { // return b.getValue(); // } // } // // public void put(K key, V value, long duration) { // map.put(key, new Bucket(value, System.currentTimeMillis() + duration)); // } // // public void remove(K key) { // map.remove(key); // } // // public void clear() { // this.map.clear(); // } // // private class Bucket { // private long expireAt; // private V value; // // public Bucket(V value, long expireAt) { // this.value = value; // this.expireAt = expireAt; // } // // public V getValue() { // return value; // } // // public long getExpireMillis() { // return expireAt; // } // } // }
import java.util.Vector; import android.util.Log; import com.futurice.android.reservator.common.CacheMap;
package com.futurice.android.reservator.model; public class CachedDataProxy extends DataProxy { // private static final long CACHE_ROOMS_FOR = 3600*1000; // 1 hour private static final long CACHE_RESERVATION_FOR = 60 * 1000; // 1 minute private final DataProxy dataProxy;
// Path: app/src/main/java/com/futurice/android/reservator/common/CacheMap.java // public class CacheMap<K, V> { // private final HashMap<K, Bucket> map; // // public CacheMap() { // this.map = new HashMap<K, Bucket>(); // } // // public V get(K key) { // Bucket b = map.get(key); // // if (b == null || b.getExpireMillis() < System.currentTimeMillis()) { // return null; // } else { // return b.getValue(); // } // } // // public void put(K key, V value, long duration) { // map.put(key, new Bucket(value, System.currentTimeMillis() + duration)); // } // // public void remove(K key) { // map.remove(key); // } // // public void clear() { // this.map.clear(); // } // // private class Bucket { // private long expireAt; // private V value; // // public Bucket(V value, long expireAt) { // this.value = value; // this.expireAt = expireAt; // } // // public V getValue() { // return value; // } // // public long getExpireMillis() { // return expireAt; // } // } // } // Path: app/src/main/java/com/futurice/android/reservator/model/CachedDataProxy.java import java.util.Vector; import android.util.Log; import com.futurice.android.reservator.common.CacheMap; package com.futurice.android.reservator.model; public class CachedDataProxy extends DataProxy { // private static final long CACHE_ROOMS_FOR = 3600*1000; // 1 hour private static final long CACHE_RESERVATION_FOR = 60 * 1000; // 1 minute private final DataProxy dataProxy;
private final CacheMap<String, Vector<Reservation>> reservationCache;
Daskiworks/ghwatch
app/src/main/java/com/daskiworks/ghwatch/ListOfNotificationsByRepositoriesFilterDialog.java
// Path: app/src/main/java/com/daskiworks/ghwatch/model/NotifCount.java // public class NotifCount { // // public String title; // public int count = 0; // // }
import com.daskiworks.ghwatch.model.NotificationStreamViewData; import android.app.Dialog; import androidx.annotation.NonNull; import com.google.android.material.bottomsheet.BottomSheetBehavior; import com.google.android.material.bottomsheet.BottomSheetDialog; import com.google.android.material.bottomsheet.BottomSheetDialogFragment; import android.view.MotionEvent; import android.view.View; import android.view.ViewTreeObserver; import android.widget.AdapterView; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ListView; import android.widget.Toast; import com.daskiworks.ghwatch.model.NotifCount;
} else { resetButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getMainActivity().setFilterByRepository(null); dismiss(); } }); //long press tooltip! resetButton.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { Toast.makeText(getContext(), view.getContentDescription(), Toast.LENGTH_SHORT).show(); return true; } }); } ActivityTracker.sendView(getActivity(), TAG); } protected MainActivity getMainActivity() { return (MainActivity) getActivity(); } private class RepositoriesListItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (repositoriesListView != null) {
// Path: app/src/main/java/com/daskiworks/ghwatch/model/NotifCount.java // public class NotifCount { // // public String title; // public int count = 0; // // } // Path: app/src/main/java/com/daskiworks/ghwatch/ListOfNotificationsByRepositoriesFilterDialog.java import com.daskiworks.ghwatch.model.NotificationStreamViewData; import android.app.Dialog; import androidx.annotation.NonNull; import com.google.android.material.bottomsheet.BottomSheetBehavior; import com.google.android.material.bottomsheet.BottomSheetDialog; import com.google.android.material.bottomsheet.BottomSheetDialogFragment; import android.view.MotionEvent; import android.view.View; import android.view.ViewTreeObserver; import android.widget.AdapterView; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ListView; import android.widget.Toast; import com.daskiworks.ghwatch.model.NotifCount; } else { resetButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getMainActivity().setFilterByRepository(null); dismiss(); } }); //long press tooltip! resetButton.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { Toast.makeText(getContext(), view.getContentDescription(), Toast.LENGTH_SHORT).show(); return true; } }); } ActivityTracker.sendView(getActivity(), TAG); } protected MainActivity getMainActivity() { return (MainActivity) getActivity(); } private class RepositoriesListItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (repositoriesListView != null) {
NotifCount nc = (NotifCount) repositoriesListAdapter.getItem(position);
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/component/EncryptTextComponent.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java // public class EncryptTextFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptTextViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerEncryptTextComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentEncryptTextBinding binding = FragmentEncryptTextBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/EncryptTextModule.java // @Module // public class EncryptTextModule { // @Provides // @ActivityScope // public EncryptTextViewModel provideEncryptTextViewModel(Zerokit zerokit, EventBus eventBus) { // return new EncryptTextViewModel(zerokit, eventBus); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/EncryptTextViewModel.java // public class EncryptTextViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerEncrypt; // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerDecrypt; // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerCopy; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgressEncrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgressDecrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> encryptClicked; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textOriginal; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textEncrypted; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textDecrypted; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textSummary; // // private final Zerokit zerokit; // // @SuppressWarnings("WeakerAccess") // String tresorId; // // @Inject // public EncryptTextViewModel(Zerokit zerokit, final EventBus eventBus) { // this.zerokit = zerokit; // // this.inProgressEncrypt = new ObservableField<>(false); // this.inProgressDecrypt = new ObservableField<>(false); // this.encryptClicked = new ObservableField<>(false); // this.textOriginal = new ObservableField<>(); // this.textEncrypted = new ObservableField<>(); // this.textSummary = new ObservableField<>(); // this.textDecrypted = new ObservableField<>(); // this.clickListenerEncrypt = new View.OnClickListener() { // @Override // public void onClick(View v) { // encryptClicked.set(true); // encrypt(tresorId, textOriginal.get()); // } // }; // this.clickListenerDecrypt = new View.OnClickListener() { // @Override // public void onClick(View v) { // decrypt(textEncrypted.get()); // } // }; // this.clickListenerCopy = new View.OnClickListener() { // @Override // public void onClick(View v) { // eventBus.post(new CopyEncryptedTextMessage(textEncrypted.get())); // } // }; // } // // @SuppressWarnings("WeakerAccess") // void encrypt(String tresorId, String text) { // inProgressEncrypt.set(true); // zerokit.encrypt(tresorId, text).enqueue(new Action<String>() { // @Override // public void call(String encryptedText) { // inProgressEncrypt.set(false); // textEncrypted.set(encryptedText); // } // }, new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError responseZerokitError) { // inProgressEncrypt.set(false); // } // }); // } // // @SuppressWarnings("WeakerAccess") // void decrypt(String cipherText) { // inProgressDecrypt.set(true); // zerokit.decrypt(cipherText).enqueue(new Action<String>() { // @Override // public void call(String decryptedText) { // inProgressDecrypt.set(false); // textDecrypted.set(decryptedText); // } // }, new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError responseError) { // inProgressDecrypt.set(false); // textDecrypted.set(""); // } // }); // } // // @Subscribe // @SuppressWarnings("unused") // public void onEvent(CreateTresorFinishedMessage message) { // tresorId = message.getTresorId(); // textSummary.set("Tresor ID: " + message.getTresorId()); // } // // }
import com.tresorit.zerokitsdk.fragment.EncryptTextFragment; import com.tresorit.zerokitsdk.module.EncryptTextModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import com.tresorit.zerokitsdk.viewmodel.EncryptTextViewModel; import dagger.Component;
package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = {
// Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java // public class EncryptTextFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptTextViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerEncryptTextComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentEncryptTextBinding binding = FragmentEncryptTextBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/EncryptTextModule.java // @Module // public class EncryptTextModule { // @Provides // @ActivityScope // public EncryptTextViewModel provideEncryptTextViewModel(Zerokit zerokit, EventBus eventBus) { // return new EncryptTextViewModel(zerokit, eventBus); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/EncryptTextViewModel.java // public class EncryptTextViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerEncrypt; // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerDecrypt; // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerCopy; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgressEncrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgressDecrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> encryptClicked; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textOriginal; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textEncrypted; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textDecrypted; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textSummary; // // private final Zerokit zerokit; // // @SuppressWarnings("WeakerAccess") // String tresorId; // // @Inject // public EncryptTextViewModel(Zerokit zerokit, final EventBus eventBus) { // this.zerokit = zerokit; // // this.inProgressEncrypt = new ObservableField<>(false); // this.inProgressDecrypt = new ObservableField<>(false); // this.encryptClicked = new ObservableField<>(false); // this.textOriginal = new ObservableField<>(); // this.textEncrypted = new ObservableField<>(); // this.textSummary = new ObservableField<>(); // this.textDecrypted = new ObservableField<>(); // this.clickListenerEncrypt = new View.OnClickListener() { // @Override // public void onClick(View v) { // encryptClicked.set(true); // encrypt(tresorId, textOriginal.get()); // } // }; // this.clickListenerDecrypt = new View.OnClickListener() { // @Override // public void onClick(View v) { // decrypt(textEncrypted.get()); // } // }; // this.clickListenerCopy = new View.OnClickListener() { // @Override // public void onClick(View v) { // eventBus.post(new CopyEncryptedTextMessage(textEncrypted.get())); // } // }; // } // // @SuppressWarnings("WeakerAccess") // void encrypt(String tresorId, String text) { // inProgressEncrypt.set(true); // zerokit.encrypt(tresorId, text).enqueue(new Action<String>() { // @Override // public void call(String encryptedText) { // inProgressEncrypt.set(false); // textEncrypted.set(encryptedText); // } // }, new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError responseZerokitError) { // inProgressEncrypt.set(false); // } // }); // } // // @SuppressWarnings("WeakerAccess") // void decrypt(String cipherText) { // inProgressDecrypt.set(true); // zerokit.decrypt(cipherText).enqueue(new Action<String>() { // @Override // public void call(String decryptedText) { // inProgressDecrypt.set(false); // textDecrypted.set(decryptedText); // } // }, new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError responseError) { // inProgressDecrypt.set(false); // textDecrypted.set(""); // } // }); // } // // @Subscribe // @SuppressWarnings("unused") // public void onEvent(CreateTresorFinishedMessage message) { // tresorId = message.getTresorId(); // textSummary.set("Tresor ID: " + message.getTresorId()); // } // // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/component/EncryptTextComponent.java import com.tresorit.zerokitsdk.fragment.EncryptTextFragment; import com.tresorit.zerokitsdk.module.EncryptTextModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import com.tresorit.zerokitsdk.viewmodel.EncryptTextViewModel; import dagger.Component; package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = {
EncryptTextModule.class
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/component/EncryptTextComponent.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java // public class EncryptTextFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptTextViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerEncryptTextComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentEncryptTextBinding binding = FragmentEncryptTextBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/EncryptTextModule.java // @Module // public class EncryptTextModule { // @Provides // @ActivityScope // public EncryptTextViewModel provideEncryptTextViewModel(Zerokit zerokit, EventBus eventBus) { // return new EncryptTextViewModel(zerokit, eventBus); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/EncryptTextViewModel.java // public class EncryptTextViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerEncrypt; // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerDecrypt; // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerCopy; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgressEncrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgressDecrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> encryptClicked; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textOriginal; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textEncrypted; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textDecrypted; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textSummary; // // private final Zerokit zerokit; // // @SuppressWarnings("WeakerAccess") // String tresorId; // // @Inject // public EncryptTextViewModel(Zerokit zerokit, final EventBus eventBus) { // this.zerokit = zerokit; // // this.inProgressEncrypt = new ObservableField<>(false); // this.inProgressDecrypt = new ObservableField<>(false); // this.encryptClicked = new ObservableField<>(false); // this.textOriginal = new ObservableField<>(); // this.textEncrypted = new ObservableField<>(); // this.textSummary = new ObservableField<>(); // this.textDecrypted = new ObservableField<>(); // this.clickListenerEncrypt = new View.OnClickListener() { // @Override // public void onClick(View v) { // encryptClicked.set(true); // encrypt(tresorId, textOriginal.get()); // } // }; // this.clickListenerDecrypt = new View.OnClickListener() { // @Override // public void onClick(View v) { // decrypt(textEncrypted.get()); // } // }; // this.clickListenerCopy = new View.OnClickListener() { // @Override // public void onClick(View v) { // eventBus.post(new CopyEncryptedTextMessage(textEncrypted.get())); // } // }; // } // // @SuppressWarnings("WeakerAccess") // void encrypt(String tresorId, String text) { // inProgressEncrypt.set(true); // zerokit.encrypt(tresorId, text).enqueue(new Action<String>() { // @Override // public void call(String encryptedText) { // inProgressEncrypt.set(false); // textEncrypted.set(encryptedText); // } // }, new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError responseZerokitError) { // inProgressEncrypt.set(false); // } // }); // } // // @SuppressWarnings("WeakerAccess") // void decrypt(String cipherText) { // inProgressDecrypt.set(true); // zerokit.decrypt(cipherText).enqueue(new Action<String>() { // @Override // public void call(String decryptedText) { // inProgressDecrypt.set(false); // textDecrypted.set(decryptedText); // } // }, new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError responseError) { // inProgressDecrypt.set(false); // textDecrypted.set(""); // } // }); // } // // @Subscribe // @SuppressWarnings("unused") // public void onEvent(CreateTresorFinishedMessage message) { // tresorId = message.getTresorId(); // textSummary.set("Tresor ID: " + message.getTresorId()); // } // // }
import com.tresorit.zerokitsdk.fragment.EncryptTextFragment; import com.tresorit.zerokitsdk.module.EncryptTextModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import com.tresorit.zerokitsdk.viewmodel.EncryptTextViewModel; import dagger.Component;
package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = { EncryptTextModule.class }, dependencies = { ApplicationComponent.class } ) public interface EncryptTextComponent {
// Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java // public class EncryptTextFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptTextViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerEncryptTextComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentEncryptTextBinding binding = FragmentEncryptTextBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/EncryptTextModule.java // @Module // public class EncryptTextModule { // @Provides // @ActivityScope // public EncryptTextViewModel provideEncryptTextViewModel(Zerokit zerokit, EventBus eventBus) { // return new EncryptTextViewModel(zerokit, eventBus); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/EncryptTextViewModel.java // public class EncryptTextViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerEncrypt; // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerDecrypt; // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerCopy; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgressEncrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgressDecrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> encryptClicked; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textOriginal; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textEncrypted; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textDecrypted; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textSummary; // // private final Zerokit zerokit; // // @SuppressWarnings("WeakerAccess") // String tresorId; // // @Inject // public EncryptTextViewModel(Zerokit zerokit, final EventBus eventBus) { // this.zerokit = zerokit; // // this.inProgressEncrypt = new ObservableField<>(false); // this.inProgressDecrypt = new ObservableField<>(false); // this.encryptClicked = new ObservableField<>(false); // this.textOriginal = new ObservableField<>(); // this.textEncrypted = new ObservableField<>(); // this.textSummary = new ObservableField<>(); // this.textDecrypted = new ObservableField<>(); // this.clickListenerEncrypt = new View.OnClickListener() { // @Override // public void onClick(View v) { // encryptClicked.set(true); // encrypt(tresorId, textOriginal.get()); // } // }; // this.clickListenerDecrypt = new View.OnClickListener() { // @Override // public void onClick(View v) { // decrypt(textEncrypted.get()); // } // }; // this.clickListenerCopy = new View.OnClickListener() { // @Override // public void onClick(View v) { // eventBus.post(new CopyEncryptedTextMessage(textEncrypted.get())); // } // }; // } // // @SuppressWarnings("WeakerAccess") // void encrypt(String tresorId, String text) { // inProgressEncrypt.set(true); // zerokit.encrypt(tresorId, text).enqueue(new Action<String>() { // @Override // public void call(String encryptedText) { // inProgressEncrypt.set(false); // textEncrypted.set(encryptedText); // } // }, new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError responseZerokitError) { // inProgressEncrypt.set(false); // } // }); // } // // @SuppressWarnings("WeakerAccess") // void decrypt(String cipherText) { // inProgressDecrypt.set(true); // zerokit.decrypt(cipherText).enqueue(new Action<String>() { // @Override // public void call(String decryptedText) { // inProgressDecrypt.set(false); // textDecrypted.set(decryptedText); // } // }, new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError responseError) { // inProgressDecrypt.set(false); // textDecrypted.set(""); // } // }); // } // // @Subscribe // @SuppressWarnings("unused") // public void onEvent(CreateTresorFinishedMessage message) { // tresorId = message.getTresorId(); // textSummary.set("Tresor ID: " + message.getTresorId()); // } // // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/component/EncryptTextComponent.java import com.tresorit.zerokitsdk.fragment.EncryptTextFragment; import com.tresorit.zerokitsdk.module.EncryptTextModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import com.tresorit.zerokitsdk.viewmodel.EncryptTextViewModel; import dagger.Component; package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = { EncryptTextModule.class }, dependencies = { ApplicationComponent.class } ) public interface EncryptTextComponent {
void inject(EncryptTextFragment fragment);
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/component/EncryptTextComponent.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java // public class EncryptTextFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptTextViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerEncryptTextComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentEncryptTextBinding binding = FragmentEncryptTextBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/EncryptTextModule.java // @Module // public class EncryptTextModule { // @Provides // @ActivityScope // public EncryptTextViewModel provideEncryptTextViewModel(Zerokit zerokit, EventBus eventBus) { // return new EncryptTextViewModel(zerokit, eventBus); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/EncryptTextViewModel.java // public class EncryptTextViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerEncrypt; // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerDecrypt; // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerCopy; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgressEncrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgressDecrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> encryptClicked; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textOriginal; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textEncrypted; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textDecrypted; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textSummary; // // private final Zerokit zerokit; // // @SuppressWarnings("WeakerAccess") // String tresorId; // // @Inject // public EncryptTextViewModel(Zerokit zerokit, final EventBus eventBus) { // this.zerokit = zerokit; // // this.inProgressEncrypt = new ObservableField<>(false); // this.inProgressDecrypt = new ObservableField<>(false); // this.encryptClicked = new ObservableField<>(false); // this.textOriginal = new ObservableField<>(); // this.textEncrypted = new ObservableField<>(); // this.textSummary = new ObservableField<>(); // this.textDecrypted = new ObservableField<>(); // this.clickListenerEncrypt = new View.OnClickListener() { // @Override // public void onClick(View v) { // encryptClicked.set(true); // encrypt(tresorId, textOriginal.get()); // } // }; // this.clickListenerDecrypt = new View.OnClickListener() { // @Override // public void onClick(View v) { // decrypt(textEncrypted.get()); // } // }; // this.clickListenerCopy = new View.OnClickListener() { // @Override // public void onClick(View v) { // eventBus.post(new CopyEncryptedTextMessage(textEncrypted.get())); // } // }; // } // // @SuppressWarnings("WeakerAccess") // void encrypt(String tresorId, String text) { // inProgressEncrypt.set(true); // zerokit.encrypt(tresorId, text).enqueue(new Action<String>() { // @Override // public void call(String encryptedText) { // inProgressEncrypt.set(false); // textEncrypted.set(encryptedText); // } // }, new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError responseZerokitError) { // inProgressEncrypt.set(false); // } // }); // } // // @SuppressWarnings("WeakerAccess") // void decrypt(String cipherText) { // inProgressDecrypt.set(true); // zerokit.decrypt(cipherText).enqueue(new Action<String>() { // @Override // public void call(String decryptedText) { // inProgressDecrypt.set(false); // textDecrypted.set(decryptedText); // } // }, new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError responseError) { // inProgressDecrypt.set(false); // textDecrypted.set(""); // } // }); // } // // @Subscribe // @SuppressWarnings("unused") // public void onEvent(CreateTresorFinishedMessage message) { // tresorId = message.getTresorId(); // textSummary.set("Tresor ID: " + message.getTresorId()); // } // // }
import com.tresorit.zerokitsdk.fragment.EncryptTextFragment; import com.tresorit.zerokitsdk.module.EncryptTextModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import com.tresorit.zerokitsdk.viewmodel.EncryptTextViewModel; import dagger.Component;
package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = { EncryptTextModule.class }, dependencies = { ApplicationComponent.class } ) public interface EncryptTextComponent { void inject(EncryptTextFragment fragment);
// Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java // public class EncryptTextFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptTextViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerEncryptTextComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentEncryptTextBinding binding = FragmentEncryptTextBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/EncryptTextModule.java // @Module // public class EncryptTextModule { // @Provides // @ActivityScope // public EncryptTextViewModel provideEncryptTextViewModel(Zerokit zerokit, EventBus eventBus) { // return new EncryptTextViewModel(zerokit, eventBus); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/EncryptTextViewModel.java // public class EncryptTextViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerEncrypt; // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerDecrypt; // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerCopy; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgressEncrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgressDecrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> encryptClicked; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textOriginal; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textEncrypted; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textDecrypted; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textSummary; // // private final Zerokit zerokit; // // @SuppressWarnings("WeakerAccess") // String tresorId; // // @Inject // public EncryptTextViewModel(Zerokit zerokit, final EventBus eventBus) { // this.zerokit = zerokit; // // this.inProgressEncrypt = new ObservableField<>(false); // this.inProgressDecrypt = new ObservableField<>(false); // this.encryptClicked = new ObservableField<>(false); // this.textOriginal = new ObservableField<>(); // this.textEncrypted = new ObservableField<>(); // this.textSummary = new ObservableField<>(); // this.textDecrypted = new ObservableField<>(); // this.clickListenerEncrypt = new View.OnClickListener() { // @Override // public void onClick(View v) { // encryptClicked.set(true); // encrypt(tresorId, textOriginal.get()); // } // }; // this.clickListenerDecrypt = new View.OnClickListener() { // @Override // public void onClick(View v) { // decrypt(textEncrypted.get()); // } // }; // this.clickListenerCopy = new View.OnClickListener() { // @Override // public void onClick(View v) { // eventBus.post(new CopyEncryptedTextMessage(textEncrypted.get())); // } // }; // } // // @SuppressWarnings("WeakerAccess") // void encrypt(String tresorId, String text) { // inProgressEncrypt.set(true); // zerokit.encrypt(tresorId, text).enqueue(new Action<String>() { // @Override // public void call(String encryptedText) { // inProgressEncrypt.set(false); // textEncrypted.set(encryptedText); // } // }, new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError responseZerokitError) { // inProgressEncrypt.set(false); // } // }); // } // // @SuppressWarnings("WeakerAccess") // void decrypt(String cipherText) { // inProgressDecrypt.set(true); // zerokit.decrypt(cipherText).enqueue(new Action<String>() { // @Override // public void call(String decryptedText) { // inProgressDecrypt.set(false); // textDecrypted.set(decryptedText); // } // }, new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError responseError) { // inProgressDecrypt.set(false); // textDecrypted.set(""); // } // }); // } // // @Subscribe // @SuppressWarnings("unused") // public void onEvent(CreateTresorFinishedMessage message) { // tresorId = message.getTresorId(); // textSummary.set("Tresor ID: " + message.getTresorId()); // } // // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/component/EncryptTextComponent.java import com.tresorit.zerokitsdk.fragment.EncryptTextFragment; import com.tresorit.zerokitsdk.module.EncryptTextModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import com.tresorit.zerokitsdk.viewmodel.EncryptTextViewModel; import dagger.Component; package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = { EncryptTextModule.class }, dependencies = { ApplicationComponent.class } ) public interface EncryptTextComponent { void inject(EncryptTextFragment fragment);
EncryptTextViewModel viewmodel();
tresorit/ZeroKit-Android-SDK
zerokit/src/main/java/com/tresorit/zerokit/ZerokitInitializer.java
// Path: zerokit/src/main/java/com/tresorit/zerokit/Zerokit.java // public static final String API_ROOT = "com.tresorit.zerokitsdk.API_ROOT";
import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import static com.tresorit.zerokit.Zerokit.API_ROOT;
package com.tresorit.zerokit; public class ZerokitInitializer extends ContentProvider { @Override public boolean onCreate() { try { Context context = getContext();
// Path: zerokit/src/main/java/com/tresorit/zerokit/Zerokit.java // public static final String API_ROOT = "com.tresorit.zerokitsdk.API_ROOT"; // Path: zerokit/src/main/java/com/tresorit/zerokit/ZerokitInitializer.java import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import static com.tresorit.zerokit.Zerokit.API_ROOT; package com.tresorit.zerokit; public class ZerokitInitializer extends ContentProvider { @Override public boolean onCreate() { try { Context context = getContext();
String url = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA).metaData.getString(API_ROOT);
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/component/RegistrationComponent.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/SignUpFragment.java // public class SignUpFragment extends ComponentControllerFragment<RegistrationComponent> { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // RegistrationViewModel registrationViewModel; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // getComponent().inject(this); // FragmentRegistrationBinding binding = FragmentRegistrationBinding.inflate(inflater, container, false); // binding.setViewmodel(registrationViewModel); // return binding.getRoot(); // } // // // @Override // protected RegistrationComponent onCreateNonConfigurationComponent() { // return DaggerRegistrationComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build(); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/RegistrationModule.java // @Module // public class RegistrationModule { // // @Provides // @ActivityScope // public RegistrationViewModel provideRegistrationViewModel(Zerokit zerokit, AdminApi adminApi, EventBus eventbus, SharedPreferences sharedPreferences, Context context) { // return new RegistrationViewModel(zerokit, adminApi, eventbus, sharedPreferences, context.getResources()); // } // }
import com.tresorit.zerokitsdk.fragment.SignUpFragment; import com.tresorit.zerokitsdk.module.RegistrationModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import dagger.Component;
package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = {
// Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/SignUpFragment.java // public class SignUpFragment extends ComponentControllerFragment<RegistrationComponent> { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // RegistrationViewModel registrationViewModel; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // getComponent().inject(this); // FragmentRegistrationBinding binding = FragmentRegistrationBinding.inflate(inflater, container, false); // binding.setViewmodel(registrationViewModel); // return binding.getRoot(); // } // // // @Override // protected RegistrationComponent onCreateNonConfigurationComponent() { // return DaggerRegistrationComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build(); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/RegistrationModule.java // @Module // public class RegistrationModule { // // @Provides // @ActivityScope // public RegistrationViewModel provideRegistrationViewModel(Zerokit zerokit, AdminApi adminApi, EventBus eventbus, SharedPreferences sharedPreferences, Context context) { // return new RegistrationViewModel(zerokit, adminApi, eventbus, sharedPreferences, context.getResources()); // } // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/component/RegistrationComponent.java import com.tresorit.zerokitsdk.fragment.SignUpFragment; import com.tresorit.zerokitsdk.module.RegistrationModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import dagger.Component; package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = {
RegistrationModule.class
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/component/RegistrationComponent.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/SignUpFragment.java // public class SignUpFragment extends ComponentControllerFragment<RegistrationComponent> { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // RegistrationViewModel registrationViewModel; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // getComponent().inject(this); // FragmentRegistrationBinding binding = FragmentRegistrationBinding.inflate(inflater, container, false); // binding.setViewmodel(registrationViewModel); // return binding.getRoot(); // } // // // @Override // protected RegistrationComponent onCreateNonConfigurationComponent() { // return DaggerRegistrationComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build(); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/RegistrationModule.java // @Module // public class RegistrationModule { // // @Provides // @ActivityScope // public RegistrationViewModel provideRegistrationViewModel(Zerokit zerokit, AdminApi adminApi, EventBus eventbus, SharedPreferences sharedPreferences, Context context) { // return new RegistrationViewModel(zerokit, adminApi, eventbus, sharedPreferences, context.getResources()); // } // }
import com.tresorit.zerokitsdk.fragment.SignUpFragment; import com.tresorit.zerokitsdk.module.RegistrationModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import dagger.Component;
package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = { RegistrationModule.class }, dependencies = { ApplicationComponent.class } ) public interface RegistrationComponent {
// Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/SignUpFragment.java // public class SignUpFragment extends ComponentControllerFragment<RegistrationComponent> { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // RegistrationViewModel registrationViewModel; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // getComponent().inject(this); // FragmentRegistrationBinding binding = FragmentRegistrationBinding.inflate(inflater, container, false); // binding.setViewmodel(registrationViewModel); // return binding.getRoot(); // } // // // @Override // protected RegistrationComponent onCreateNonConfigurationComponent() { // return DaggerRegistrationComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build(); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/RegistrationModule.java // @Module // public class RegistrationModule { // // @Provides // @ActivityScope // public RegistrationViewModel provideRegistrationViewModel(Zerokit zerokit, AdminApi adminApi, EventBus eventbus, SharedPreferences sharedPreferences, Context context) { // return new RegistrationViewModel(zerokit, adminApi, eventbus, sharedPreferences, context.getResources()); // } // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/component/RegistrationComponent.java import com.tresorit.zerokitsdk.fragment.SignUpFragment; import com.tresorit.zerokitsdk.module.RegistrationModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import dagger.Component; package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = { RegistrationModule.class }, dependencies = { ApplicationComponent.class } ) public interface RegistrationComponent {
void inject(SignUpFragment fragment);
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/module/ApplicationModule.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // }
import android.content.Context; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.scopes.ApplicationScope; import dagger.Module; import dagger.Provides;
package com.tresorit.zerokitsdk.module; @Module public class ApplicationModule {
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/ApplicationModule.java import android.content.Context; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.scopes.ApplicationScope; import dagger.Module; import dagger.Provides; package com.tresorit.zerokitsdk.module; @Module public class ApplicationModule {
private final ZerokitApplication application;
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/component/PagerComponent.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/adapter/EncryptPagerAdapter.java // public class EncryptPagerAdapter extends FragmentPagerAdapter { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorFragment createTresorFragment; // // @SuppressWarnings("WeakerAccess") // @Inject // EncryptTextFragment encryptTextFragment; // // @SuppressWarnings("WeakerAccess") // @Inject // ShareTresorFragment shareTresorFragment; // // // public EncryptPagerAdapter(Context context, FragmentManager fm) { // super(fm); // DaggerPagerComponent.builder().applicationComponent(ZerokitApplication.get(context).component()).build().inject(this); // } // // @Override // public Fragment getItem(int position) { // switch (position){ // case 0: // return createTresorFragment; // case 1: // return encryptTextFragment; // case 2: // return shareTresorFragment; // default: // return new Fragment(); // } // } // // @Override // public int getCount() { // return 3; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/CreateTresorFragment.java // public class CreateTresorFragment extends Fragment { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorViewModel viewModel; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerCreateTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentCreateTresorBinding binding = FragmentCreateTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java // public class EncryptTextFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptTextViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerEncryptTextComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentEncryptTextBinding binding = FragmentEncryptTextBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/ShareTresorFragment.java // public class ShareTresorFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // ShareTresorViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerShareTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentShareTresorBinding binding = FragmentShareTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/PagerModule.java // @Module // public class PagerModule { // // @Provides // @ActivityScope // public CreateTresorFragment provideCreateTresorFragment() { // return new CreateTresorFragment(); // } // // @Provides // @ActivityScope // public ShareTresorFragment provideShareTresorFragment() { // return new ShareTresorFragment(); // } // // @Provides // @ActivityScope // public EncryptTextFragment provideEncryptTextFragment() { // return new EncryptTextFragment(); // } // }
import com.tresorit.zerokitsdk.adapter.EncryptPagerAdapter; import com.tresorit.zerokitsdk.fragment.CreateTresorFragment; import com.tresorit.zerokitsdk.fragment.EncryptTextFragment; import com.tresorit.zerokitsdk.fragment.ShareTresorFragment; import com.tresorit.zerokitsdk.module.PagerModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import dagger.Component;
package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = {
// Path: sample/src/main/java/com/tresorit/zerokitsdk/adapter/EncryptPagerAdapter.java // public class EncryptPagerAdapter extends FragmentPagerAdapter { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorFragment createTresorFragment; // // @SuppressWarnings("WeakerAccess") // @Inject // EncryptTextFragment encryptTextFragment; // // @SuppressWarnings("WeakerAccess") // @Inject // ShareTresorFragment shareTresorFragment; // // // public EncryptPagerAdapter(Context context, FragmentManager fm) { // super(fm); // DaggerPagerComponent.builder().applicationComponent(ZerokitApplication.get(context).component()).build().inject(this); // } // // @Override // public Fragment getItem(int position) { // switch (position){ // case 0: // return createTresorFragment; // case 1: // return encryptTextFragment; // case 2: // return shareTresorFragment; // default: // return new Fragment(); // } // } // // @Override // public int getCount() { // return 3; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/CreateTresorFragment.java // public class CreateTresorFragment extends Fragment { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorViewModel viewModel; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerCreateTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentCreateTresorBinding binding = FragmentCreateTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java // public class EncryptTextFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptTextViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerEncryptTextComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentEncryptTextBinding binding = FragmentEncryptTextBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/ShareTresorFragment.java // public class ShareTresorFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // ShareTresorViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerShareTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentShareTresorBinding binding = FragmentShareTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/PagerModule.java // @Module // public class PagerModule { // // @Provides // @ActivityScope // public CreateTresorFragment provideCreateTresorFragment() { // return new CreateTresorFragment(); // } // // @Provides // @ActivityScope // public ShareTresorFragment provideShareTresorFragment() { // return new ShareTresorFragment(); // } // // @Provides // @ActivityScope // public EncryptTextFragment provideEncryptTextFragment() { // return new EncryptTextFragment(); // } // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/component/PagerComponent.java import com.tresorit.zerokitsdk.adapter.EncryptPagerAdapter; import com.tresorit.zerokitsdk.fragment.CreateTresorFragment; import com.tresorit.zerokitsdk.fragment.EncryptTextFragment; import com.tresorit.zerokitsdk.fragment.ShareTresorFragment; import com.tresorit.zerokitsdk.module.PagerModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import dagger.Component; package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = {
PagerModule.class,
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/component/PagerComponent.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/adapter/EncryptPagerAdapter.java // public class EncryptPagerAdapter extends FragmentPagerAdapter { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorFragment createTresorFragment; // // @SuppressWarnings("WeakerAccess") // @Inject // EncryptTextFragment encryptTextFragment; // // @SuppressWarnings("WeakerAccess") // @Inject // ShareTresorFragment shareTresorFragment; // // // public EncryptPagerAdapter(Context context, FragmentManager fm) { // super(fm); // DaggerPagerComponent.builder().applicationComponent(ZerokitApplication.get(context).component()).build().inject(this); // } // // @Override // public Fragment getItem(int position) { // switch (position){ // case 0: // return createTresorFragment; // case 1: // return encryptTextFragment; // case 2: // return shareTresorFragment; // default: // return new Fragment(); // } // } // // @Override // public int getCount() { // return 3; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/CreateTresorFragment.java // public class CreateTresorFragment extends Fragment { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorViewModel viewModel; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerCreateTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentCreateTresorBinding binding = FragmentCreateTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java // public class EncryptTextFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptTextViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerEncryptTextComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentEncryptTextBinding binding = FragmentEncryptTextBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/ShareTresorFragment.java // public class ShareTresorFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // ShareTresorViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerShareTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentShareTresorBinding binding = FragmentShareTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/PagerModule.java // @Module // public class PagerModule { // // @Provides // @ActivityScope // public CreateTresorFragment provideCreateTresorFragment() { // return new CreateTresorFragment(); // } // // @Provides // @ActivityScope // public ShareTresorFragment provideShareTresorFragment() { // return new ShareTresorFragment(); // } // // @Provides // @ActivityScope // public EncryptTextFragment provideEncryptTextFragment() { // return new EncryptTextFragment(); // } // }
import com.tresorit.zerokitsdk.adapter.EncryptPagerAdapter; import com.tresorit.zerokitsdk.fragment.CreateTresorFragment; import com.tresorit.zerokitsdk.fragment.EncryptTextFragment; import com.tresorit.zerokitsdk.fragment.ShareTresorFragment; import com.tresorit.zerokitsdk.module.PagerModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import dagger.Component;
package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = { PagerModule.class, }, dependencies = { ApplicationComponent.class } ) public interface PagerComponent extends ApplicationComponent {
// Path: sample/src/main/java/com/tresorit/zerokitsdk/adapter/EncryptPagerAdapter.java // public class EncryptPagerAdapter extends FragmentPagerAdapter { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorFragment createTresorFragment; // // @SuppressWarnings("WeakerAccess") // @Inject // EncryptTextFragment encryptTextFragment; // // @SuppressWarnings("WeakerAccess") // @Inject // ShareTresorFragment shareTresorFragment; // // // public EncryptPagerAdapter(Context context, FragmentManager fm) { // super(fm); // DaggerPagerComponent.builder().applicationComponent(ZerokitApplication.get(context).component()).build().inject(this); // } // // @Override // public Fragment getItem(int position) { // switch (position){ // case 0: // return createTresorFragment; // case 1: // return encryptTextFragment; // case 2: // return shareTresorFragment; // default: // return new Fragment(); // } // } // // @Override // public int getCount() { // return 3; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/CreateTresorFragment.java // public class CreateTresorFragment extends Fragment { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorViewModel viewModel; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerCreateTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentCreateTresorBinding binding = FragmentCreateTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java // public class EncryptTextFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptTextViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerEncryptTextComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentEncryptTextBinding binding = FragmentEncryptTextBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/ShareTresorFragment.java // public class ShareTresorFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // ShareTresorViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerShareTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentShareTresorBinding binding = FragmentShareTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/PagerModule.java // @Module // public class PagerModule { // // @Provides // @ActivityScope // public CreateTresorFragment provideCreateTresorFragment() { // return new CreateTresorFragment(); // } // // @Provides // @ActivityScope // public ShareTresorFragment provideShareTresorFragment() { // return new ShareTresorFragment(); // } // // @Provides // @ActivityScope // public EncryptTextFragment provideEncryptTextFragment() { // return new EncryptTextFragment(); // } // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/component/PagerComponent.java import com.tresorit.zerokitsdk.adapter.EncryptPagerAdapter; import com.tresorit.zerokitsdk.fragment.CreateTresorFragment; import com.tresorit.zerokitsdk.fragment.EncryptTextFragment; import com.tresorit.zerokitsdk.fragment.ShareTresorFragment; import com.tresorit.zerokitsdk.module.PagerModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import dagger.Component; package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = { PagerModule.class, }, dependencies = { ApplicationComponent.class } ) public interface PagerComponent extends ApplicationComponent {
void inject(EncryptPagerAdapter fragment);
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/component/PagerComponent.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/adapter/EncryptPagerAdapter.java // public class EncryptPagerAdapter extends FragmentPagerAdapter { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorFragment createTresorFragment; // // @SuppressWarnings("WeakerAccess") // @Inject // EncryptTextFragment encryptTextFragment; // // @SuppressWarnings("WeakerAccess") // @Inject // ShareTresorFragment shareTresorFragment; // // // public EncryptPagerAdapter(Context context, FragmentManager fm) { // super(fm); // DaggerPagerComponent.builder().applicationComponent(ZerokitApplication.get(context).component()).build().inject(this); // } // // @Override // public Fragment getItem(int position) { // switch (position){ // case 0: // return createTresorFragment; // case 1: // return encryptTextFragment; // case 2: // return shareTresorFragment; // default: // return new Fragment(); // } // } // // @Override // public int getCount() { // return 3; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/CreateTresorFragment.java // public class CreateTresorFragment extends Fragment { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorViewModel viewModel; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerCreateTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentCreateTresorBinding binding = FragmentCreateTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java // public class EncryptTextFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptTextViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerEncryptTextComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentEncryptTextBinding binding = FragmentEncryptTextBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/ShareTresorFragment.java // public class ShareTresorFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // ShareTresorViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerShareTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentShareTresorBinding binding = FragmentShareTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/PagerModule.java // @Module // public class PagerModule { // // @Provides // @ActivityScope // public CreateTresorFragment provideCreateTresorFragment() { // return new CreateTresorFragment(); // } // // @Provides // @ActivityScope // public ShareTresorFragment provideShareTresorFragment() { // return new ShareTresorFragment(); // } // // @Provides // @ActivityScope // public EncryptTextFragment provideEncryptTextFragment() { // return new EncryptTextFragment(); // } // }
import com.tresorit.zerokitsdk.adapter.EncryptPagerAdapter; import com.tresorit.zerokitsdk.fragment.CreateTresorFragment; import com.tresorit.zerokitsdk.fragment.EncryptTextFragment; import com.tresorit.zerokitsdk.fragment.ShareTresorFragment; import com.tresorit.zerokitsdk.module.PagerModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import dagger.Component;
package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = { PagerModule.class, }, dependencies = { ApplicationComponent.class } ) public interface PagerComponent extends ApplicationComponent { void inject(EncryptPagerAdapter fragment);
// Path: sample/src/main/java/com/tresorit/zerokitsdk/adapter/EncryptPagerAdapter.java // public class EncryptPagerAdapter extends FragmentPagerAdapter { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorFragment createTresorFragment; // // @SuppressWarnings("WeakerAccess") // @Inject // EncryptTextFragment encryptTextFragment; // // @SuppressWarnings("WeakerAccess") // @Inject // ShareTresorFragment shareTresorFragment; // // // public EncryptPagerAdapter(Context context, FragmentManager fm) { // super(fm); // DaggerPagerComponent.builder().applicationComponent(ZerokitApplication.get(context).component()).build().inject(this); // } // // @Override // public Fragment getItem(int position) { // switch (position){ // case 0: // return createTresorFragment; // case 1: // return encryptTextFragment; // case 2: // return shareTresorFragment; // default: // return new Fragment(); // } // } // // @Override // public int getCount() { // return 3; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/CreateTresorFragment.java // public class CreateTresorFragment extends Fragment { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorViewModel viewModel; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerCreateTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentCreateTresorBinding binding = FragmentCreateTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java // public class EncryptTextFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptTextViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerEncryptTextComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentEncryptTextBinding binding = FragmentEncryptTextBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/ShareTresorFragment.java // public class ShareTresorFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // ShareTresorViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerShareTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentShareTresorBinding binding = FragmentShareTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/PagerModule.java // @Module // public class PagerModule { // // @Provides // @ActivityScope // public CreateTresorFragment provideCreateTresorFragment() { // return new CreateTresorFragment(); // } // // @Provides // @ActivityScope // public ShareTresorFragment provideShareTresorFragment() { // return new ShareTresorFragment(); // } // // @Provides // @ActivityScope // public EncryptTextFragment provideEncryptTextFragment() { // return new EncryptTextFragment(); // } // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/component/PagerComponent.java import com.tresorit.zerokitsdk.adapter.EncryptPagerAdapter; import com.tresorit.zerokitsdk.fragment.CreateTresorFragment; import com.tresorit.zerokitsdk.fragment.EncryptTextFragment; import com.tresorit.zerokitsdk.fragment.ShareTresorFragment; import com.tresorit.zerokitsdk.module.PagerModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import dagger.Component; package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = { PagerModule.class, }, dependencies = { ApplicationComponent.class } ) public interface PagerComponent extends ApplicationComponent { void inject(EncryptPagerAdapter fragment);
CreateTresorFragment createTresorFragment();
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/component/PagerComponent.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/adapter/EncryptPagerAdapter.java // public class EncryptPagerAdapter extends FragmentPagerAdapter { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorFragment createTresorFragment; // // @SuppressWarnings("WeakerAccess") // @Inject // EncryptTextFragment encryptTextFragment; // // @SuppressWarnings("WeakerAccess") // @Inject // ShareTresorFragment shareTresorFragment; // // // public EncryptPagerAdapter(Context context, FragmentManager fm) { // super(fm); // DaggerPagerComponent.builder().applicationComponent(ZerokitApplication.get(context).component()).build().inject(this); // } // // @Override // public Fragment getItem(int position) { // switch (position){ // case 0: // return createTresorFragment; // case 1: // return encryptTextFragment; // case 2: // return shareTresorFragment; // default: // return new Fragment(); // } // } // // @Override // public int getCount() { // return 3; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/CreateTresorFragment.java // public class CreateTresorFragment extends Fragment { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorViewModel viewModel; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerCreateTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentCreateTresorBinding binding = FragmentCreateTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java // public class EncryptTextFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptTextViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerEncryptTextComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentEncryptTextBinding binding = FragmentEncryptTextBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/ShareTresorFragment.java // public class ShareTresorFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // ShareTresorViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerShareTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentShareTresorBinding binding = FragmentShareTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/PagerModule.java // @Module // public class PagerModule { // // @Provides // @ActivityScope // public CreateTresorFragment provideCreateTresorFragment() { // return new CreateTresorFragment(); // } // // @Provides // @ActivityScope // public ShareTresorFragment provideShareTresorFragment() { // return new ShareTresorFragment(); // } // // @Provides // @ActivityScope // public EncryptTextFragment provideEncryptTextFragment() { // return new EncryptTextFragment(); // } // }
import com.tresorit.zerokitsdk.adapter.EncryptPagerAdapter; import com.tresorit.zerokitsdk.fragment.CreateTresorFragment; import com.tresorit.zerokitsdk.fragment.EncryptTextFragment; import com.tresorit.zerokitsdk.fragment.ShareTresorFragment; import com.tresorit.zerokitsdk.module.PagerModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import dagger.Component;
package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = { PagerModule.class, }, dependencies = { ApplicationComponent.class } ) public interface PagerComponent extends ApplicationComponent { void inject(EncryptPagerAdapter fragment); CreateTresorFragment createTresorFragment();
// Path: sample/src/main/java/com/tresorit/zerokitsdk/adapter/EncryptPagerAdapter.java // public class EncryptPagerAdapter extends FragmentPagerAdapter { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorFragment createTresorFragment; // // @SuppressWarnings("WeakerAccess") // @Inject // EncryptTextFragment encryptTextFragment; // // @SuppressWarnings("WeakerAccess") // @Inject // ShareTresorFragment shareTresorFragment; // // // public EncryptPagerAdapter(Context context, FragmentManager fm) { // super(fm); // DaggerPagerComponent.builder().applicationComponent(ZerokitApplication.get(context).component()).build().inject(this); // } // // @Override // public Fragment getItem(int position) { // switch (position){ // case 0: // return createTresorFragment; // case 1: // return encryptTextFragment; // case 2: // return shareTresorFragment; // default: // return new Fragment(); // } // } // // @Override // public int getCount() { // return 3; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/CreateTresorFragment.java // public class CreateTresorFragment extends Fragment { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorViewModel viewModel; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerCreateTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentCreateTresorBinding binding = FragmentCreateTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java // public class EncryptTextFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptTextViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerEncryptTextComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentEncryptTextBinding binding = FragmentEncryptTextBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/ShareTresorFragment.java // public class ShareTresorFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // ShareTresorViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerShareTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentShareTresorBinding binding = FragmentShareTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/PagerModule.java // @Module // public class PagerModule { // // @Provides // @ActivityScope // public CreateTresorFragment provideCreateTresorFragment() { // return new CreateTresorFragment(); // } // // @Provides // @ActivityScope // public ShareTresorFragment provideShareTresorFragment() { // return new ShareTresorFragment(); // } // // @Provides // @ActivityScope // public EncryptTextFragment provideEncryptTextFragment() { // return new EncryptTextFragment(); // } // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/component/PagerComponent.java import com.tresorit.zerokitsdk.adapter.EncryptPagerAdapter; import com.tresorit.zerokitsdk.fragment.CreateTresorFragment; import com.tresorit.zerokitsdk.fragment.EncryptTextFragment; import com.tresorit.zerokitsdk.fragment.ShareTresorFragment; import com.tresorit.zerokitsdk.module.PagerModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import dagger.Component; package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = { PagerModule.class, }, dependencies = { ApplicationComponent.class } ) public interface PagerComponent extends ApplicationComponent { void inject(EncryptPagerAdapter fragment); CreateTresorFragment createTresorFragment();
EncryptTextFragment encryptTextFragment();
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/component/PagerComponent.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/adapter/EncryptPagerAdapter.java // public class EncryptPagerAdapter extends FragmentPagerAdapter { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorFragment createTresorFragment; // // @SuppressWarnings("WeakerAccess") // @Inject // EncryptTextFragment encryptTextFragment; // // @SuppressWarnings("WeakerAccess") // @Inject // ShareTresorFragment shareTresorFragment; // // // public EncryptPagerAdapter(Context context, FragmentManager fm) { // super(fm); // DaggerPagerComponent.builder().applicationComponent(ZerokitApplication.get(context).component()).build().inject(this); // } // // @Override // public Fragment getItem(int position) { // switch (position){ // case 0: // return createTresorFragment; // case 1: // return encryptTextFragment; // case 2: // return shareTresorFragment; // default: // return new Fragment(); // } // } // // @Override // public int getCount() { // return 3; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/CreateTresorFragment.java // public class CreateTresorFragment extends Fragment { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorViewModel viewModel; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerCreateTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentCreateTresorBinding binding = FragmentCreateTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java // public class EncryptTextFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptTextViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerEncryptTextComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentEncryptTextBinding binding = FragmentEncryptTextBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/ShareTresorFragment.java // public class ShareTresorFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // ShareTresorViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerShareTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentShareTresorBinding binding = FragmentShareTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/PagerModule.java // @Module // public class PagerModule { // // @Provides // @ActivityScope // public CreateTresorFragment provideCreateTresorFragment() { // return new CreateTresorFragment(); // } // // @Provides // @ActivityScope // public ShareTresorFragment provideShareTresorFragment() { // return new ShareTresorFragment(); // } // // @Provides // @ActivityScope // public EncryptTextFragment provideEncryptTextFragment() { // return new EncryptTextFragment(); // } // }
import com.tresorit.zerokitsdk.adapter.EncryptPagerAdapter; import com.tresorit.zerokitsdk.fragment.CreateTresorFragment; import com.tresorit.zerokitsdk.fragment.EncryptTextFragment; import com.tresorit.zerokitsdk.fragment.ShareTresorFragment; import com.tresorit.zerokitsdk.module.PagerModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import dagger.Component;
package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = { PagerModule.class, }, dependencies = { ApplicationComponent.class } ) public interface PagerComponent extends ApplicationComponent { void inject(EncryptPagerAdapter fragment); CreateTresorFragment createTresorFragment(); EncryptTextFragment encryptTextFragment();
// Path: sample/src/main/java/com/tresorit/zerokitsdk/adapter/EncryptPagerAdapter.java // public class EncryptPagerAdapter extends FragmentPagerAdapter { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorFragment createTresorFragment; // // @SuppressWarnings("WeakerAccess") // @Inject // EncryptTextFragment encryptTextFragment; // // @SuppressWarnings("WeakerAccess") // @Inject // ShareTresorFragment shareTresorFragment; // // // public EncryptPagerAdapter(Context context, FragmentManager fm) { // super(fm); // DaggerPagerComponent.builder().applicationComponent(ZerokitApplication.get(context).component()).build().inject(this); // } // // @Override // public Fragment getItem(int position) { // switch (position){ // case 0: // return createTresorFragment; // case 1: // return encryptTextFragment; // case 2: // return shareTresorFragment; // default: // return new Fragment(); // } // } // // @Override // public int getCount() { // return 3; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/CreateTresorFragment.java // public class CreateTresorFragment extends Fragment { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorViewModel viewModel; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerCreateTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentCreateTresorBinding binding = FragmentCreateTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java // public class EncryptTextFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptTextViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerEncryptTextComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentEncryptTextBinding binding = FragmentEncryptTextBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/ShareTresorFragment.java // public class ShareTresorFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // ShareTresorViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerShareTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentShareTresorBinding binding = FragmentShareTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/PagerModule.java // @Module // public class PagerModule { // // @Provides // @ActivityScope // public CreateTresorFragment provideCreateTresorFragment() { // return new CreateTresorFragment(); // } // // @Provides // @ActivityScope // public ShareTresorFragment provideShareTresorFragment() { // return new ShareTresorFragment(); // } // // @Provides // @ActivityScope // public EncryptTextFragment provideEncryptTextFragment() { // return new EncryptTextFragment(); // } // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/component/PagerComponent.java import com.tresorit.zerokitsdk.adapter.EncryptPagerAdapter; import com.tresorit.zerokitsdk.fragment.CreateTresorFragment; import com.tresorit.zerokitsdk.fragment.EncryptTextFragment; import com.tresorit.zerokitsdk.fragment.ShareTresorFragment; import com.tresorit.zerokitsdk.module.PagerModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import dagger.Component; package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = { PagerModule.class, }, dependencies = { ApplicationComponent.class } ) public interface PagerComponent extends ApplicationComponent { void inject(EncryptPagerAdapter fragment); CreateTresorFragment createTresorFragment(); EncryptTextFragment encryptTextFragment();
ShareTresorFragment shareTresorFragment();
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/module/SignInModule.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/SignInViewModel.java // public class SignInViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final BottomNavigationView.OnNavigationItemSelectedListener onNavigationItemSelectedListener; // @SuppressWarnings("WeakerAccess") // public final ObservableInt displayedChild; // // @Inject // public SignInViewModel(@SuppressWarnings("UnusedParameters") EventBus eventBus) { // displayedChild = new ObservableInt(0); // onNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { // @Override // public boolean onNavigationItemSelected(@NonNull MenuItem item) { // displayedChild.set(item.getItemId() == R.id.tab_signin ? 0 : 1); // return true; // } // }; // } // }
import com.tresorit.zerokitsdk.scopes.ActivityScope; import com.tresorit.zerokitsdk.viewmodel.SignInViewModel; import org.greenrobot.eventbus.EventBus; import dagger.Module; import dagger.Provides;
package com.tresorit.zerokitsdk.module; @Module public class SignInModule { @Provides @ActivityScope
// Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/SignInViewModel.java // public class SignInViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final BottomNavigationView.OnNavigationItemSelectedListener onNavigationItemSelectedListener; // @SuppressWarnings("WeakerAccess") // public final ObservableInt displayedChild; // // @Inject // public SignInViewModel(@SuppressWarnings("UnusedParameters") EventBus eventBus) { // displayedChild = new ObservableInt(0); // onNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { // @Override // public boolean onNavigationItemSelected(@NonNull MenuItem item) { // displayedChild.set(item.getItemId() == R.id.tab_signin ? 0 : 1); // return true; // } // }; // } // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/SignInModule.java import com.tresorit.zerokitsdk.scopes.ActivityScope; import com.tresorit.zerokitsdk.viewmodel.SignInViewModel; import org.greenrobot.eventbus.EventBus; import dagger.Module; import dagger.Provides; package com.tresorit.zerokitsdk.module; @Module public class SignInModule { @Provides @ActivityScope
public SignInViewModel provideSignInViewModel(EventBus eventBus) {
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/EncryptTextViewModel.java // public class EncryptTextViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerEncrypt; // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerDecrypt; // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerCopy; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgressEncrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgressDecrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> encryptClicked; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textOriginal; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textEncrypted; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textDecrypted; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textSummary; // // private final Zerokit zerokit; // // @SuppressWarnings("WeakerAccess") // String tresorId; // // @Inject // public EncryptTextViewModel(Zerokit zerokit, final EventBus eventBus) { // this.zerokit = zerokit; // // this.inProgressEncrypt = new ObservableField<>(false); // this.inProgressDecrypt = new ObservableField<>(false); // this.encryptClicked = new ObservableField<>(false); // this.textOriginal = new ObservableField<>(); // this.textEncrypted = new ObservableField<>(); // this.textSummary = new ObservableField<>(); // this.textDecrypted = new ObservableField<>(); // this.clickListenerEncrypt = new View.OnClickListener() { // @Override // public void onClick(View v) { // encryptClicked.set(true); // encrypt(tresorId, textOriginal.get()); // } // }; // this.clickListenerDecrypt = new View.OnClickListener() { // @Override // public void onClick(View v) { // decrypt(textEncrypted.get()); // } // }; // this.clickListenerCopy = new View.OnClickListener() { // @Override // public void onClick(View v) { // eventBus.post(new CopyEncryptedTextMessage(textEncrypted.get())); // } // }; // } // // @SuppressWarnings("WeakerAccess") // void encrypt(String tresorId, String text) { // inProgressEncrypt.set(true); // zerokit.encrypt(tresorId, text).enqueue(new Action<String>() { // @Override // public void call(String encryptedText) { // inProgressEncrypt.set(false); // textEncrypted.set(encryptedText); // } // }, new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError responseZerokitError) { // inProgressEncrypt.set(false); // } // }); // } // // @SuppressWarnings("WeakerAccess") // void decrypt(String cipherText) { // inProgressDecrypt.set(true); // zerokit.decrypt(cipherText).enqueue(new Action<String>() { // @Override // public void call(String decryptedText) { // inProgressDecrypt.set(false); // textDecrypted.set(decryptedText); // } // }, new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError responseError) { // inProgressDecrypt.set(false); // textDecrypted.set(""); // } // }); // } // // @Subscribe // @SuppressWarnings("unused") // public void onEvent(CreateTresorFinishedMessage message) { // tresorId = message.getTresorId(); // textSummary.set("Tresor ID: " + message.getTresorId()); // } // // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.component.DaggerEncryptTextComponent; import com.tresorit.zerokitsdk.databinding.FragmentEncryptTextBinding; import com.tresorit.zerokitsdk.viewmodel.EncryptTextViewModel; import org.greenrobot.eventbus.EventBus; import javax.inject.Inject;
package com.tresorit.zerokitsdk.fragment; public class EncryptTextFragment extends Fragment { @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) @Inject
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/EncryptTextViewModel.java // public class EncryptTextViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerEncrypt; // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerDecrypt; // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerCopy; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgressEncrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgressDecrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> encryptClicked; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textOriginal; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textEncrypted; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textDecrypted; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textSummary; // // private final Zerokit zerokit; // // @SuppressWarnings("WeakerAccess") // String tresorId; // // @Inject // public EncryptTextViewModel(Zerokit zerokit, final EventBus eventBus) { // this.zerokit = zerokit; // // this.inProgressEncrypt = new ObservableField<>(false); // this.inProgressDecrypt = new ObservableField<>(false); // this.encryptClicked = new ObservableField<>(false); // this.textOriginal = new ObservableField<>(); // this.textEncrypted = new ObservableField<>(); // this.textSummary = new ObservableField<>(); // this.textDecrypted = new ObservableField<>(); // this.clickListenerEncrypt = new View.OnClickListener() { // @Override // public void onClick(View v) { // encryptClicked.set(true); // encrypt(tresorId, textOriginal.get()); // } // }; // this.clickListenerDecrypt = new View.OnClickListener() { // @Override // public void onClick(View v) { // decrypt(textEncrypted.get()); // } // }; // this.clickListenerCopy = new View.OnClickListener() { // @Override // public void onClick(View v) { // eventBus.post(new CopyEncryptedTextMessage(textEncrypted.get())); // } // }; // } // // @SuppressWarnings("WeakerAccess") // void encrypt(String tresorId, String text) { // inProgressEncrypt.set(true); // zerokit.encrypt(tresorId, text).enqueue(new Action<String>() { // @Override // public void call(String encryptedText) { // inProgressEncrypt.set(false); // textEncrypted.set(encryptedText); // } // }, new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError responseZerokitError) { // inProgressEncrypt.set(false); // } // }); // } // // @SuppressWarnings("WeakerAccess") // void decrypt(String cipherText) { // inProgressDecrypt.set(true); // zerokit.decrypt(cipherText).enqueue(new Action<String>() { // @Override // public void call(String decryptedText) { // inProgressDecrypt.set(false); // textDecrypted.set(decryptedText); // } // }, new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError responseError) { // inProgressDecrypt.set(false); // textDecrypted.set(""); // } // }); // } // // @Subscribe // @SuppressWarnings("unused") // public void onEvent(CreateTresorFinishedMessage message) { // tresorId = message.getTresorId(); // textSummary.set("Tresor ID: " + message.getTresorId()); // } // // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.component.DaggerEncryptTextComponent; import com.tresorit.zerokitsdk.databinding.FragmentEncryptTextBinding; import com.tresorit.zerokitsdk.viewmodel.EncryptTextViewModel; import org.greenrobot.eventbus.EventBus; import javax.inject.Inject; package com.tresorit.zerokitsdk.fragment; public class EncryptTextFragment extends Fragment { @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) @Inject
EncryptTextViewModel viewModel;
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/EncryptTextViewModel.java // public class EncryptTextViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerEncrypt; // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerDecrypt; // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerCopy; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgressEncrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgressDecrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> encryptClicked; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textOriginal; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textEncrypted; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textDecrypted; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textSummary; // // private final Zerokit zerokit; // // @SuppressWarnings("WeakerAccess") // String tresorId; // // @Inject // public EncryptTextViewModel(Zerokit zerokit, final EventBus eventBus) { // this.zerokit = zerokit; // // this.inProgressEncrypt = new ObservableField<>(false); // this.inProgressDecrypt = new ObservableField<>(false); // this.encryptClicked = new ObservableField<>(false); // this.textOriginal = new ObservableField<>(); // this.textEncrypted = new ObservableField<>(); // this.textSummary = new ObservableField<>(); // this.textDecrypted = new ObservableField<>(); // this.clickListenerEncrypt = new View.OnClickListener() { // @Override // public void onClick(View v) { // encryptClicked.set(true); // encrypt(tresorId, textOriginal.get()); // } // }; // this.clickListenerDecrypt = new View.OnClickListener() { // @Override // public void onClick(View v) { // decrypt(textEncrypted.get()); // } // }; // this.clickListenerCopy = new View.OnClickListener() { // @Override // public void onClick(View v) { // eventBus.post(new CopyEncryptedTextMessage(textEncrypted.get())); // } // }; // } // // @SuppressWarnings("WeakerAccess") // void encrypt(String tresorId, String text) { // inProgressEncrypt.set(true); // zerokit.encrypt(tresorId, text).enqueue(new Action<String>() { // @Override // public void call(String encryptedText) { // inProgressEncrypt.set(false); // textEncrypted.set(encryptedText); // } // }, new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError responseZerokitError) { // inProgressEncrypt.set(false); // } // }); // } // // @SuppressWarnings("WeakerAccess") // void decrypt(String cipherText) { // inProgressDecrypt.set(true); // zerokit.decrypt(cipherText).enqueue(new Action<String>() { // @Override // public void call(String decryptedText) { // inProgressDecrypt.set(false); // textDecrypted.set(decryptedText); // } // }, new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError responseError) { // inProgressDecrypt.set(false); // textDecrypted.set(""); // } // }); // } // // @Subscribe // @SuppressWarnings("unused") // public void onEvent(CreateTresorFinishedMessage message) { // tresorId = message.getTresorId(); // textSummary.set("Tresor ID: " + message.getTresorId()); // } // // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.component.DaggerEncryptTextComponent; import com.tresorit.zerokitsdk.databinding.FragmentEncryptTextBinding; import com.tresorit.zerokitsdk.viewmodel.EncryptTextViewModel; import org.greenrobot.eventbus.EventBus; import javax.inject.Inject;
package com.tresorit.zerokitsdk.fragment; public class EncryptTextFragment extends Fragment { @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) @Inject EncryptTextViewModel viewModel; @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) @Inject EventBus eventBus; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/EncryptTextViewModel.java // public class EncryptTextViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerEncrypt; // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerDecrypt; // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerCopy; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgressEncrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgressDecrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> encryptClicked; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textOriginal; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textEncrypted; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textDecrypted; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textSummary; // // private final Zerokit zerokit; // // @SuppressWarnings("WeakerAccess") // String tresorId; // // @Inject // public EncryptTextViewModel(Zerokit zerokit, final EventBus eventBus) { // this.zerokit = zerokit; // // this.inProgressEncrypt = new ObservableField<>(false); // this.inProgressDecrypt = new ObservableField<>(false); // this.encryptClicked = new ObservableField<>(false); // this.textOriginal = new ObservableField<>(); // this.textEncrypted = new ObservableField<>(); // this.textSummary = new ObservableField<>(); // this.textDecrypted = new ObservableField<>(); // this.clickListenerEncrypt = new View.OnClickListener() { // @Override // public void onClick(View v) { // encryptClicked.set(true); // encrypt(tresorId, textOriginal.get()); // } // }; // this.clickListenerDecrypt = new View.OnClickListener() { // @Override // public void onClick(View v) { // decrypt(textEncrypted.get()); // } // }; // this.clickListenerCopy = new View.OnClickListener() { // @Override // public void onClick(View v) { // eventBus.post(new CopyEncryptedTextMessage(textEncrypted.get())); // } // }; // } // // @SuppressWarnings("WeakerAccess") // void encrypt(String tresorId, String text) { // inProgressEncrypt.set(true); // zerokit.encrypt(tresorId, text).enqueue(new Action<String>() { // @Override // public void call(String encryptedText) { // inProgressEncrypt.set(false); // textEncrypted.set(encryptedText); // } // }, new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError responseZerokitError) { // inProgressEncrypt.set(false); // } // }); // } // // @SuppressWarnings("WeakerAccess") // void decrypt(String cipherText) { // inProgressDecrypt.set(true); // zerokit.decrypt(cipherText).enqueue(new Action<String>() { // @Override // public void call(String decryptedText) { // inProgressDecrypt.set(false); // textDecrypted.set(decryptedText); // } // }, new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError responseError) { // inProgressDecrypt.set(false); // textDecrypted.set(""); // } // }); // } // // @Subscribe // @SuppressWarnings("unused") // public void onEvent(CreateTresorFinishedMessage message) { // tresorId = message.getTresorId(); // textSummary.set("Tresor ID: " + message.getTresorId()); // } // // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.component.DaggerEncryptTextComponent; import com.tresorit.zerokitsdk.databinding.FragmentEncryptTextBinding; import com.tresorit.zerokitsdk.viewmodel.EncryptTextViewModel; import org.greenrobot.eventbus.EventBus; import javax.inject.Inject; package com.tresorit.zerokitsdk.fragment; public class EncryptTextFragment extends Fragment { @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) @Inject EncryptTextViewModel viewModel; @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) @Inject EventBus eventBus; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
DaggerEncryptTextComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this);
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/fragment/DecryptFragment.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/DecryptViewModel.java // public class DecryptViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerDecrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgressDecrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textEncrypted; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textDecrypted; // // private final Zerokit zerokit; // // @Inject // public DecryptViewModel(Zerokit zerokit) { // this.zerokit = zerokit; // // this.inProgressDecrypt = new ObservableField<>(false); // this.textEncrypted = new ObservableField<>(); // this.textDecrypted = new ObservableField<>(); // this.clickListenerDecrypt = new View.OnClickListener() { // @Override // public void onClick(View v) { // decrypt(textEncrypted.get()); // } // }; // } // // // @SuppressWarnings("WeakerAccess") // void decrypt(String cipherText){ // inProgressDecrypt.set(true); // zerokit.decrypt(cipherText).enqueue(new Action<String>() { // @Override // public void call(String decryptedText) { // inProgressDecrypt.set(false); // textDecrypted.set(decryptedText); // } // }, new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError responseError) { // inProgressDecrypt.set(false); // textDecrypted.set(""); // } // }); // } // // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.component.DaggerDecryptComponent; import com.tresorit.zerokitsdk.databinding.FragmentDecryptBinding; import com.tresorit.zerokitsdk.viewmodel.DecryptViewModel; import javax.inject.Inject;
package com.tresorit.zerokitsdk.fragment; public class DecryptFragment extends Fragment { @SuppressWarnings("WeakerAccess") @Inject
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/DecryptViewModel.java // public class DecryptViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerDecrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgressDecrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textEncrypted; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textDecrypted; // // private final Zerokit zerokit; // // @Inject // public DecryptViewModel(Zerokit zerokit) { // this.zerokit = zerokit; // // this.inProgressDecrypt = new ObservableField<>(false); // this.textEncrypted = new ObservableField<>(); // this.textDecrypted = new ObservableField<>(); // this.clickListenerDecrypt = new View.OnClickListener() { // @Override // public void onClick(View v) { // decrypt(textEncrypted.get()); // } // }; // } // // // @SuppressWarnings("WeakerAccess") // void decrypt(String cipherText){ // inProgressDecrypt.set(true); // zerokit.decrypt(cipherText).enqueue(new Action<String>() { // @Override // public void call(String decryptedText) { // inProgressDecrypt.set(false); // textDecrypted.set(decryptedText); // } // }, new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError responseError) { // inProgressDecrypt.set(false); // textDecrypted.set(""); // } // }); // } // // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/DecryptFragment.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.component.DaggerDecryptComponent; import com.tresorit.zerokitsdk.databinding.FragmentDecryptBinding; import com.tresorit.zerokitsdk.viewmodel.DecryptViewModel; import javax.inject.Inject; package com.tresorit.zerokitsdk.fragment; public class DecryptFragment extends Fragment { @SuppressWarnings("WeakerAccess") @Inject
DecryptViewModel viewModel;
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/fragment/DecryptFragment.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/DecryptViewModel.java // public class DecryptViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerDecrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgressDecrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textEncrypted; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textDecrypted; // // private final Zerokit zerokit; // // @Inject // public DecryptViewModel(Zerokit zerokit) { // this.zerokit = zerokit; // // this.inProgressDecrypt = new ObservableField<>(false); // this.textEncrypted = new ObservableField<>(); // this.textDecrypted = new ObservableField<>(); // this.clickListenerDecrypt = new View.OnClickListener() { // @Override // public void onClick(View v) { // decrypt(textEncrypted.get()); // } // }; // } // // // @SuppressWarnings("WeakerAccess") // void decrypt(String cipherText){ // inProgressDecrypt.set(true); // zerokit.decrypt(cipherText).enqueue(new Action<String>() { // @Override // public void call(String decryptedText) { // inProgressDecrypt.set(false); // textDecrypted.set(decryptedText); // } // }, new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError responseError) { // inProgressDecrypt.set(false); // textDecrypted.set(""); // } // }); // } // // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.component.DaggerDecryptComponent; import com.tresorit.zerokitsdk.databinding.FragmentDecryptBinding; import com.tresorit.zerokitsdk.viewmodel.DecryptViewModel; import javax.inject.Inject;
package com.tresorit.zerokitsdk.fragment; public class DecryptFragment extends Fragment { @SuppressWarnings("WeakerAccess") @Inject DecryptViewModel viewModel; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/DecryptViewModel.java // public class DecryptViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerDecrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgressDecrypt; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textEncrypted; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textDecrypted; // // private final Zerokit zerokit; // // @Inject // public DecryptViewModel(Zerokit zerokit) { // this.zerokit = zerokit; // // this.inProgressDecrypt = new ObservableField<>(false); // this.textEncrypted = new ObservableField<>(); // this.textDecrypted = new ObservableField<>(); // this.clickListenerDecrypt = new View.OnClickListener() { // @Override // public void onClick(View v) { // decrypt(textEncrypted.get()); // } // }; // } // // // @SuppressWarnings("WeakerAccess") // void decrypt(String cipherText){ // inProgressDecrypt.set(true); // zerokit.decrypt(cipherText).enqueue(new Action<String>() { // @Override // public void call(String decryptedText) { // inProgressDecrypt.set(false); // textDecrypted.set(decryptedText); // } // }, new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError responseError) { // inProgressDecrypt.set(false); // textDecrypted.set(""); // } // }); // } // // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/DecryptFragment.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.component.DaggerDecryptComponent; import com.tresorit.zerokitsdk.databinding.FragmentDecryptBinding; import com.tresorit.zerokitsdk.viewmodel.DecryptViewModel; import javax.inject.Inject; package com.tresorit.zerokitsdk.fragment; public class DecryptFragment extends Fragment { @SuppressWarnings("WeakerAccess") @Inject DecryptViewModel viewModel; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
DaggerDecryptComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this);
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/component/ApplicationComponent.java // @ApplicationScope // @Component( // modules = { // ApplicationModule.class, // EventBusModule.class, // AdminApiModule.class, // ZerokitSdkModule.class, // SharedPreferencesModule.class // } // ) // public interface ApplicationComponent { // Context context(); // EventBus eventbus(); // AdminApi adminApi(); // Zerokit zerokit(); // SharedPreferences sharedpreferences(); // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/AdminApiModule.java // @Module // public class AdminApiModule { // // public AdminApiModule(String host, String cliendId) { // AdminApi.init(host, cliendId); // } // // @Provides // @ApplicationScope // public AdminApi provideAdminApi(){ // return AdminApi.getInstance(); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/ApplicationModule.java // @Module // public class ApplicationModule { // // private final ZerokitApplication application; // // public ApplicationModule(ZerokitApplication application) { // this.application = application; // } // // @Provides // @ApplicationScope // public Context provideContext() { // return application; // } // }
import android.app.Application; import android.content.Context; import com.tresorit.zerokitsdk.component.ApplicationComponent; import com.tresorit.zerokitsdk.component.DaggerApplicationComponent; import com.tresorit.zerokitsdk.module.AdminApiModule; import com.tresorit.zerokitsdk.module.ApplicationModule;
package com.tresorit.zerokitsdk; public class ZerokitApplication extends Application { private ApplicationComponent component; public static ZerokitApplication get(Context context) { return (ZerokitApplication) context.getApplicationContext(); } @Override public void onCreate() { super.onCreate(); component = DaggerApplicationComponent.builder()
// Path: sample/src/main/java/com/tresorit/zerokitsdk/component/ApplicationComponent.java // @ApplicationScope // @Component( // modules = { // ApplicationModule.class, // EventBusModule.class, // AdminApiModule.class, // ZerokitSdkModule.class, // SharedPreferencesModule.class // } // ) // public interface ApplicationComponent { // Context context(); // EventBus eventbus(); // AdminApi adminApi(); // Zerokit zerokit(); // SharedPreferences sharedpreferences(); // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/AdminApiModule.java // @Module // public class AdminApiModule { // // public AdminApiModule(String host, String cliendId) { // AdminApi.init(host, cliendId); // } // // @Provides // @ApplicationScope // public AdminApi provideAdminApi(){ // return AdminApi.getInstance(); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/ApplicationModule.java // @Module // public class ApplicationModule { // // private final ZerokitApplication application; // // public ApplicationModule(ZerokitApplication application) { // this.application = application; // } // // @Provides // @ApplicationScope // public Context provideContext() { // return application; // } // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java import android.app.Application; import android.content.Context; import com.tresorit.zerokitsdk.component.ApplicationComponent; import com.tresorit.zerokitsdk.component.DaggerApplicationComponent; import com.tresorit.zerokitsdk.module.AdminApiModule; import com.tresorit.zerokitsdk.module.ApplicationModule; package com.tresorit.zerokitsdk; public class ZerokitApplication extends Application { private ApplicationComponent component; public static ZerokitApplication get(Context context) { return (ZerokitApplication) context.getApplicationContext(); } @Override public void onCreate() { super.onCreate(); component = DaggerApplicationComponent.builder()
.applicationModule(new ApplicationModule(this))
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/component/ApplicationComponent.java // @ApplicationScope // @Component( // modules = { // ApplicationModule.class, // EventBusModule.class, // AdminApiModule.class, // ZerokitSdkModule.class, // SharedPreferencesModule.class // } // ) // public interface ApplicationComponent { // Context context(); // EventBus eventbus(); // AdminApi adminApi(); // Zerokit zerokit(); // SharedPreferences sharedpreferences(); // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/AdminApiModule.java // @Module // public class AdminApiModule { // // public AdminApiModule(String host, String cliendId) { // AdminApi.init(host, cliendId); // } // // @Provides // @ApplicationScope // public AdminApi provideAdminApi(){ // return AdminApi.getInstance(); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/ApplicationModule.java // @Module // public class ApplicationModule { // // private final ZerokitApplication application; // // public ApplicationModule(ZerokitApplication application) { // this.application = application; // } // // @Provides // @ApplicationScope // public Context provideContext() { // return application; // } // }
import android.app.Application; import android.content.Context; import com.tresorit.zerokitsdk.component.ApplicationComponent; import com.tresorit.zerokitsdk.component.DaggerApplicationComponent; import com.tresorit.zerokitsdk.module.AdminApiModule; import com.tresorit.zerokitsdk.module.ApplicationModule;
package com.tresorit.zerokitsdk; public class ZerokitApplication extends Application { private ApplicationComponent component; public static ZerokitApplication get(Context context) { return (ZerokitApplication) context.getApplicationContext(); } @Override public void onCreate() { super.onCreate(); component = DaggerApplicationComponent.builder() .applicationModule(new ApplicationModule(this))
// Path: sample/src/main/java/com/tresorit/zerokitsdk/component/ApplicationComponent.java // @ApplicationScope // @Component( // modules = { // ApplicationModule.class, // EventBusModule.class, // AdminApiModule.class, // ZerokitSdkModule.class, // SharedPreferencesModule.class // } // ) // public interface ApplicationComponent { // Context context(); // EventBus eventbus(); // AdminApi adminApi(); // Zerokit zerokit(); // SharedPreferences sharedpreferences(); // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/AdminApiModule.java // @Module // public class AdminApiModule { // // public AdminApiModule(String host, String cliendId) { // AdminApi.init(host, cliendId); // } // // @Provides // @ApplicationScope // public AdminApi provideAdminApi(){ // return AdminApi.getInstance(); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/ApplicationModule.java // @Module // public class ApplicationModule { // // private final ZerokitApplication application; // // public ApplicationModule(ZerokitApplication application) { // this.application = application; // } // // @Provides // @ApplicationScope // public Context provideContext() { // return application; // } // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java import android.app.Application; import android.content.Context; import com.tresorit.zerokitsdk.component.ApplicationComponent; import com.tresorit.zerokitsdk.component.DaggerApplicationComponent; import com.tresorit.zerokitsdk.module.AdminApiModule; import com.tresorit.zerokitsdk.module.ApplicationModule; package com.tresorit.zerokitsdk; public class ZerokitApplication extends Application { private ApplicationComponent component; public static ZerokitApplication get(Context context) { return (ZerokitApplication) context.getApplicationContext(); } @Override public void onCreate() { super.onCreate(); component = DaggerApplicationComponent.builder() .applicationModule(new ApplicationModule(this))
.adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID))
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/fragment/ShareTresorFragment.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/ShareTresorViewModel.java // public class ShareTresorViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListener; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgress; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> userId; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textSummary; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> sharedWithUserId; // // @SuppressWarnings("WeakerAccess") // final Action<ResponseZerokitError> errorResponseHandlerSdk; // @SuppressWarnings("WeakerAccess") // final Action<ResponseAdminApiError> errorResponseHandlerAdminapi; // // final Zerokit zerokit; // // @SuppressWarnings("WeakerAccess") // final AdminApi adminApi; // // @SuppressWarnings("WeakerAccess") // String tresorId; // // @Inject // public ShareTresorViewModel(Zerokit zerokit, AdminApi adminApi, final EventBus eventBus) { // this.zerokit = zerokit; // this.adminApi = adminApi; // // this.inProgress = new ObservableField<>(false); // this.userId = new ObservableField<>(); // this.textSummary = new ObservableField<>(); // this.sharedWithUserId = new ObservableField<>(""); // this.clickListener = new View.OnClickListener() { // @Override // public void onClick(View v) { // shareTresor(tresorId, userId.get()); // } // }; // errorResponseHandlerSdk = new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // errorResponseHandlerAdminapi = new Action<ResponseAdminApiError>() { // @Override // public void call(ResponseAdminApiError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // } // // @SuppressWarnings("WeakerAccess") // void shareTresor(final String tresorId, final String userName) { // inProgress.set(true); // sharedWithUserId.set(""); // this.adminApi.getUserId(userName).enqueue(new Action<String>() { // @Override // public void call(String userId) { // zerokit.shareTresor(tresorId, userId).enqueue(new Action<String>() { // @Override // public void call(String shareId) { // adminApi.sharedTresor(shareId).enqueue(new Action<Void>() { // @Override // public void call(Void result) { // sharedWithUserId.set("Shared with: " + userName); // inProgress.set(false); // } // }, errorResponseHandlerAdminapi); // } // }, errorResponseHandlerSdk); // } // }, errorResponseHandlerAdminapi); // } // // @Subscribe // @SuppressWarnings("unused") // public void onEvent(CreateTresorFinishedMessage message) { // tresorId = message.getTresorId(); // textSummary.set("Tresor ID: " + message.getTresorId()); // sharedWithUserId.set(""); // } // // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.component.DaggerShareTresorComponent; import com.tresorit.zerokitsdk.databinding.FragmentShareTresorBinding; import com.tresorit.zerokitsdk.viewmodel.ShareTresorViewModel; import org.greenrobot.eventbus.EventBus; import javax.inject.Inject;
package com.tresorit.zerokitsdk.fragment; public class ShareTresorFragment extends Fragment { @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) @Inject
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/ShareTresorViewModel.java // public class ShareTresorViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListener; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgress; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> userId; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textSummary; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> sharedWithUserId; // // @SuppressWarnings("WeakerAccess") // final Action<ResponseZerokitError> errorResponseHandlerSdk; // @SuppressWarnings("WeakerAccess") // final Action<ResponseAdminApiError> errorResponseHandlerAdminapi; // // final Zerokit zerokit; // // @SuppressWarnings("WeakerAccess") // final AdminApi adminApi; // // @SuppressWarnings("WeakerAccess") // String tresorId; // // @Inject // public ShareTresorViewModel(Zerokit zerokit, AdminApi adminApi, final EventBus eventBus) { // this.zerokit = zerokit; // this.adminApi = adminApi; // // this.inProgress = new ObservableField<>(false); // this.userId = new ObservableField<>(); // this.textSummary = new ObservableField<>(); // this.sharedWithUserId = new ObservableField<>(""); // this.clickListener = new View.OnClickListener() { // @Override // public void onClick(View v) { // shareTresor(tresorId, userId.get()); // } // }; // errorResponseHandlerSdk = new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // errorResponseHandlerAdminapi = new Action<ResponseAdminApiError>() { // @Override // public void call(ResponseAdminApiError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // } // // @SuppressWarnings("WeakerAccess") // void shareTresor(final String tresorId, final String userName) { // inProgress.set(true); // sharedWithUserId.set(""); // this.adminApi.getUserId(userName).enqueue(new Action<String>() { // @Override // public void call(String userId) { // zerokit.shareTresor(tresorId, userId).enqueue(new Action<String>() { // @Override // public void call(String shareId) { // adminApi.sharedTresor(shareId).enqueue(new Action<Void>() { // @Override // public void call(Void result) { // sharedWithUserId.set("Shared with: " + userName); // inProgress.set(false); // } // }, errorResponseHandlerAdminapi); // } // }, errorResponseHandlerSdk); // } // }, errorResponseHandlerAdminapi); // } // // @Subscribe // @SuppressWarnings("unused") // public void onEvent(CreateTresorFinishedMessage message) { // tresorId = message.getTresorId(); // textSummary.set("Tresor ID: " + message.getTresorId()); // sharedWithUserId.set(""); // } // // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/ShareTresorFragment.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.component.DaggerShareTresorComponent; import com.tresorit.zerokitsdk.databinding.FragmentShareTresorBinding; import com.tresorit.zerokitsdk.viewmodel.ShareTresorViewModel; import org.greenrobot.eventbus.EventBus; import javax.inject.Inject; package com.tresorit.zerokitsdk.fragment; public class ShareTresorFragment extends Fragment { @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) @Inject
ShareTresorViewModel viewModel;
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/fragment/ShareTresorFragment.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/ShareTresorViewModel.java // public class ShareTresorViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListener; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgress; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> userId; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textSummary; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> sharedWithUserId; // // @SuppressWarnings("WeakerAccess") // final Action<ResponseZerokitError> errorResponseHandlerSdk; // @SuppressWarnings("WeakerAccess") // final Action<ResponseAdminApiError> errorResponseHandlerAdminapi; // // final Zerokit zerokit; // // @SuppressWarnings("WeakerAccess") // final AdminApi adminApi; // // @SuppressWarnings("WeakerAccess") // String tresorId; // // @Inject // public ShareTresorViewModel(Zerokit zerokit, AdminApi adminApi, final EventBus eventBus) { // this.zerokit = zerokit; // this.adminApi = adminApi; // // this.inProgress = new ObservableField<>(false); // this.userId = new ObservableField<>(); // this.textSummary = new ObservableField<>(); // this.sharedWithUserId = new ObservableField<>(""); // this.clickListener = new View.OnClickListener() { // @Override // public void onClick(View v) { // shareTresor(tresorId, userId.get()); // } // }; // errorResponseHandlerSdk = new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // errorResponseHandlerAdminapi = new Action<ResponseAdminApiError>() { // @Override // public void call(ResponseAdminApiError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // } // // @SuppressWarnings("WeakerAccess") // void shareTresor(final String tresorId, final String userName) { // inProgress.set(true); // sharedWithUserId.set(""); // this.adminApi.getUserId(userName).enqueue(new Action<String>() { // @Override // public void call(String userId) { // zerokit.shareTresor(tresorId, userId).enqueue(new Action<String>() { // @Override // public void call(String shareId) { // adminApi.sharedTresor(shareId).enqueue(new Action<Void>() { // @Override // public void call(Void result) { // sharedWithUserId.set("Shared with: " + userName); // inProgress.set(false); // } // }, errorResponseHandlerAdminapi); // } // }, errorResponseHandlerSdk); // } // }, errorResponseHandlerAdminapi); // } // // @Subscribe // @SuppressWarnings("unused") // public void onEvent(CreateTresorFinishedMessage message) { // tresorId = message.getTresorId(); // textSummary.set("Tresor ID: " + message.getTresorId()); // sharedWithUserId.set(""); // } // // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.component.DaggerShareTresorComponent; import com.tresorit.zerokitsdk.databinding.FragmentShareTresorBinding; import com.tresorit.zerokitsdk.viewmodel.ShareTresorViewModel; import org.greenrobot.eventbus.EventBus; import javax.inject.Inject;
package com.tresorit.zerokitsdk.fragment; public class ShareTresorFragment extends Fragment { @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) @Inject ShareTresorViewModel viewModel; @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) @Inject EventBus eventBus; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/ShareTresorViewModel.java // public class ShareTresorViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListener; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgress; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> userId; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> textSummary; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> sharedWithUserId; // // @SuppressWarnings("WeakerAccess") // final Action<ResponseZerokitError> errorResponseHandlerSdk; // @SuppressWarnings("WeakerAccess") // final Action<ResponseAdminApiError> errorResponseHandlerAdminapi; // // final Zerokit zerokit; // // @SuppressWarnings("WeakerAccess") // final AdminApi adminApi; // // @SuppressWarnings("WeakerAccess") // String tresorId; // // @Inject // public ShareTresorViewModel(Zerokit zerokit, AdminApi adminApi, final EventBus eventBus) { // this.zerokit = zerokit; // this.adminApi = adminApi; // // this.inProgress = new ObservableField<>(false); // this.userId = new ObservableField<>(); // this.textSummary = new ObservableField<>(); // this.sharedWithUserId = new ObservableField<>(""); // this.clickListener = new View.OnClickListener() { // @Override // public void onClick(View v) { // shareTresor(tresorId, userId.get()); // } // }; // errorResponseHandlerSdk = new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // errorResponseHandlerAdminapi = new Action<ResponseAdminApiError>() { // @Override // public void call(ResponseAdminApiError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // } // // @SuppressWarnings("WeakerAccess") // void shareTresor(final String tresorId, final String userName) { // inProgress.set(true); // sharedWithUserId.set(""); // this.adminApi.getUserId(userName).enqueue(new Action<String>() { // @Override // public void call(String userId) { // zerokit.shareTresor(tresorId, userId).enqueue(new Action<String>() { // @Override // public void call(String shareId) { // adminApi.sharedTresor(shareId).enqueue(new Action<Void>() { // @Override // public void call(Void result) { // sharedWithUserId.set("Shared with: " + userName); // inProgress.set(false); // } // }, errorResponseHandlerAdminapi); // } // }, errorResponseHandlerSdk); // } // }, errorResponseHandlerAdminapi); // } // // @Subscribe // @SuppressWarnings("unused") // public void onEvent(CreateTresorFinishedMessage message) { // tresorId = message.getTresorId(); // textSummary.set("Tresor ID: " + message.getTresorId()); // sharedWithUserId.set(""); // } // // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/ShareTresorFragment.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.component.DaggerShareTresorComponent; import com.tresorit.zerokitsdk.databinding.FragmentShareTresorBinding; import com.tresorit.zerokitsdk.viewmodel.ShareTresorViewModel; import org.greenrobot.eventbus.EventBus; import javax.inject.Inject; package com.tresorit.zerokitsdk.fragment; public class ShareTresorFragment extends Fragment { @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) @Inject ShareTresorViewModel viewModel; @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) @Inject EventBus eventBus; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
DaggerShareTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this);
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/component/LoginComponent.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/SignInFragment.java // public class SignInFragment extends ComponentControllerFragment<LoginComponent> { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // LoginViewModel loginViewModel; // // @Override // protected LoginComponent onCreateNonConfigurationComponent() { // return DaggerLoginComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build(); // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // getComponent().inject(this); // FragmentLoginBinding binding = FragmentLoginBinding.inflate(inflater, container, false); // binding.setViewmodel(loginViewModel); // return binding.getRoot(); // } // // // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/LoginModule.java // @Module // public class LoginModule { // @Provides // @ActivityScope // public LoginViewModel provideLoginViewModel(Zerokit zerokit, AdminApi adminApi, EventBus eventBus) { // return new LoginViewModel(zerokit, adminApi, eventBus); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/LoginViewModel.java // public class LoginViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> userName; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> passwordError; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> usernameError; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgress; // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerLogin; // @SuppressWarnings("WeakerAccess") // public final View.OnFocusChangeListener focusChangeListener; // // @SuppressWarnings("WeakerAccess") // public final PasswordEditText.PasswordExporter passwordExporter; // // @SuppressWarnings("WeakerAccess") // final Zerokit zerokit; // @SuppressWarnings("WeakerAccess") // final AdminApi adminApi; // // @SuppressWarnings("WeakerAccess") // final EventBus eventBus; // // @SuppressWarnings("WeakerAccess") // final Action<ResponseZerokitError> errorResponseHandlerSdk; // @SuppressWarnings("WeakerAccess") // final Action<ResponseAdminApiError> errorResponseHandlerAdminapi; // // @Inject // public LoginViewModel(Zerokit zerokit, AdminApi adminApi, final EventBus eventBus) { // this.zerokit = zerokit; // this.adminApi = adminApi; // this.eventBus = eventBus; // // this.passwordExporter = new PasswordEditText.PasswordExporter(); // // this.clickListenerLogin = new View.OnClickListener() { // @Override // public void onClick(View view) { // attemptLogin(); // } // }; // // userName = new ObservableField<>(""); // passwordError = new ObservableField<>(""); // usernameError = new ObservableField<>(""); // inProgress = new ObservableField<>(false); // errorResponseHandlerSdk = new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // errorResponseHandlerAdminapi = new Action<ResponseAdminApiError>() { // @Override // public void call(ResponseAdminApiError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // focusChangeListener = new View.OnFocusChangeListener() { // @Override // public void onFocusChange(View v, boolean hasFocus) { // passwordError.set(""); // usernameError.set(""); // } // }; // } // // @SuppressWarnings("WeakerAccess") // void attemptLogin() { // if (TextUtils.isEmpty(userName.get())) usernameError.set("Required"); // else if (passwordExporter.isEmpty()) passwordError.set("Required"); // else login(userName.get(), passwordExporter); // } // // private void login(String username, final PasswordEditText.PasswordExporter passwordExporter) { // inProgress.set(true); // adminApi.getUserId(username).enqueue(new Action<String>() { // @Override // public void call(String userId) { // zerokit.login(userId, passwordExporter).enqueue(new Action<ResponseZerokitLogin>() { // @Override // public void call(ResponseZerokitLogin responseLogin) { // zerokit.getIdentityTokens(adminApi.getClientId()).enqueue(new Action<IdentityTokens>() { // @Override // public void call(IdentityTokens identityTokens) { // adminApi.login(identityTokens.getAuthorizationCode()).enqueue(new Action<ResponseAdminApiLoginByCode>() { // @Override // public void call(ResponseAdminApiLoginByCode responseAdminApiLoginByCode) { // adminApi.setToken(responseAdminApiLoginByCode.getId()); // inProgress.set(false); // eventBus.post(new LoginFinisedMessage()); // } // }, errorResponseHandlerAdminapi); // } // }, errorResponseHandlerSdk); // } // }, errorResponseHandlerSdk); // } // }, errorResponseHandlerAdminapi); // } // }
import com.tresorit.zerokitsdk.fragment.SignInFragment; import com.tresorit.zerokitsdk.module.LoginModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import com.tresorit.zerokitsdk.viewmodel.LoginViewModel; import dagger.Component;
package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = {
// Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/SignInFragment.java // public class SignInFragment extends ComponentControllerFragment<LoginComponent> { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // LoginViewModel loginViewModel; // // @Override // protected LoginComponent onCreateNonConfigurationComponent() { // return DaggerLoginComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build(); // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // getComponent().inject(this); // FragmentLoginBinding binding = FragmentLoginBinding.inflate(inflater, container, false); // binding.setViewmodel(loginViewModel); // return binding.getRoot(); // } // // // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/LoginModule.java // @Module // public class LoginModule { // @Provides // @ActivityScope // public LoginViewModel provideLoginViewModel(Zerokit zerokit, AdminApi adminApi, EventBus eventBus) { // return new LoginViewModel(zerokit, adminApi, eventBus); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/LoginViewModel.java // public class LoginViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> userName; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> passwordError; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> usernameError; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgress; // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerLogin; // @SuppressWarnings("WeakerAccess") // public final View.OnFocusChangeListener focusChangeListener; // // @SuppressWarnings("WeakerAccess") // public final PasswordEditText.PasswordExporter passwordExporter; // // @SuppressWarnings("WeakerAccess") // final Zerokit zerokit; // @SuppressWarnings("WeakerAccess") // final AdminApi adminApi; // // @SuppressWarnings("WeakerAccess") // final EventBus eventBus; // // @SuppressWarnings("WeakerAccess") // final Action<ResponseZerokitError> errorResponseHandlerSdk; // @SuppressWarnings("WeakerAccess") // final Action<ResponseAdminApiError> errorResponseHandlerAdminapi; // // @Inject // public LoginViewModel(Zerokit zerokit, AdminApi adminApi, final EventBus eventBus) { // this.zerokit = zerokit; // this.adminApi = adminApi; // this.eventBus = eventBus; // // this.passwordExporter = new PasswordEditText.PasswordExporter(); // // this.clickListenerLogin = new View.OnClickListener() { // @Override // public void onClick(View view) { // attemptLogin(); // } // }; // // userName = new ObservableField<>(""); // passwordError = new ObservableField<>(""); // usernameError = new ObservableField<>(""); // inProgress = new ObservableField<>(false); // errorResponseHandlerSdk = new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // errorResponseHandlerAdminapi = new Action<ResponseAdminApiError>() { // @Override // public void call(ResponseAdminApiError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // focusChangeListener = new View.OnFocusChangeListener() { // @Override // public void onFocusChange(View v, boolean hasFocus) { // passwordError.set(""); // usernameError.set(""); // } // }; // } // // @SuppressWarnings("WeakerAccess") // void attemptLogin() { // if (TextUtils.isEmpty(userName.get())) usernameError.set("Required"); // else if (passwordExporter.isEmpty()) passwordError.set("Required"); // else login(userName.get(), passwordExporter); // } // // private void login(String username, final PasswordEditText.PasswordExporter passwordExporter) { // inProgress.set(true); // adminApi.getUserId(username).enqueue(new Action<String>() { // @Override // public void call(String userId) { // zerokit.login(userId, passwordExporter).enqueue(new Action<ResponseZerokitLogin>() { // @Override // public void call(ResponseZerokitLogin responseLogin) { // zerokit.getIdentityTokens(adminApi.getClientId()).enqueue(new Action<IdentityTokens>() { // @Override // public void call(IdentityTokens identityTokens) { // adminApi.login(identityTokens.getAuthorizationCode()).enqueue(new Action<ResponseAdminApiLoginByCode>() { // @Override // public void call(ResponseAdminApiLoginByCode responseAdminApiLoginByCode) { // adminApi.setToken(responseAdminApiLoginByCode.getId()); // inProgress.set(false); // eventBus.post(new LoginFinisedMessage()); // } // }, errorResponseHandlerAdminapi); // } // }, errorResponseHandlerSdk); // } // }, errorResponseHandlerSdk); // } // }, errorResponseHandlerAdminapi); // } // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/component/LoginComponent.java import com.tresorit.zerokitsdk.fragment.SignInFragment; import com.tresorit.zerokitsdk.module.LoginModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import com.tresorit.zerokitsdk.viewmodel.LoginViewModel; import dagger.Component; package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = {
LoginModule.class
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/component/LoginComponent.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/SignInFragment.java // public class SignInFragment extends ComponentControllerFragment<LoginComponent> { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // LoginViewModel loginViewModel; // // @Override // protected LoginComponent onCreateNonConfigurationComponent() { // return DaggerLoginComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build(); // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // getComponent().inject(this); // FragmentLoginBinding binding = FragmentLoginBinding.inflate(inflater, container, false); // binding.setViewmodel(loginViewModel); // return binding.getRoot(); // } // // // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/LoginModule.java // @Module // public class LoginModule { // @Provides // @ActivityScope // public LoginViewModel provideLoginViewModel(Zerokit zerokit, AdminApi adminApi, EventBus eventBus) { // return new LoginViewModel(zerokit, adminApi, eventBus); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/LoginViewModel.java // public class LoginViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> userName; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> passwordError; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> usernameError; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgress; // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerLogin; // @SuppressWarnings("WeakerAccess") // public final View.OnFocusChangeListener focusChangeListener; // // @SuppressWarnings("WeakerAccess") // public final PasswordEditText.PasswordExporter passwordExporter; // // @SuppressWarnings("WeakerAccess") // final Zerokit zerokit; // @SuppressWarnings("WeakerAccess") // final AdminApi adminApi; // // @SuppressWarnings("WeakerAccess") // final EventBus eventBus; // // @SuppressWarnings("WeakerAccess") // final Action<ResponseZerokitError> errorResponseHandlerSdk; // @SuppressWarnings("WeakerAccess") // final Action<ResponseAdminApiError> errorResponseHandlerAdminapi; // // @Inject // public LoginViewModel(Zerokit zerokit, AdminApi adminApi, final EventBus eventBus) { // this.zerokit = zerokit; // this.adminApi = adminApi; // this.eventBus = eventBus; // // this.passwordExporter = new PasswordEditText.PasswordExporter(); // // this.clickListenerLogin = new View.OnClickListener() { // @Override // public void onClick(View view) { // attemptLogin(); // } // }; // // userName = new ObservableField<>(""); // passwordError = new ObservableField<>(""); // usernameError = new ObservableField<>(""); // inProgress = new ObservableField<>(false); // errorResponseHandlerSdk = new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // errorResponseHandlerAdminapi = new Action<ResponseAdminApiError>() { // @Override // public void call(ResponseAdminApiError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // focusChangeListener = new View.OnFocusChangeListener() { // @Override // public void onFocusChange(View v, boolean hasFocus) { // passwordError.set(""); // usernameError.set(""); // } // }; // } // // @SuppressWarnings("WeakerAccess") // void attemptLogin() { // if (TextUtils.isEmpty(userName.get())) usernameError.set("Required"); // else if (passwordExporter.isEmpty()) passwordError.set("Required"); // else login(userName.get(), passwordExporter); // } // // private void login(String username, final PasswordEditText.PasswordExporter passwordExporter) { // inProgress.set(true); // adminApi.getUserId(username).enqueue(new Action<String>() { // @Override // public void call(String userId) { // zerokit.login(userId, passwordExporter).enqueue(new Action<ResponseZerokitLogin>() { // @Override // public void call(ResponseZerokitLogin responseLogin) { // zerokit.getIdentityTokens(adminApi.getClientId()).enqueue(new Action<IdentityTokens>() { // @Override // public void call(IdentityTokens identityTokens) { // adminApi.login(identityTokens.getAuthorizationCode()).enqueue(new Action<ResponseAdminApiLoginByCode>() { // @Override // public void call(ResponseAdminApiLoginByCode responseAdminApiLoginByCode) { // adminApi.setToken(responseAdminApiLoginByCode.getId()); // inProgress.set(false); // eventBus.post(new LoginFinisedMessage()); // } // }, errorResponseHandlerAdminapi); // } // }, errorResponseHandlerSdk); // } // }, errorResponseHandlerSdk); // } // }, errorResponseHandlerAdminapi); // } // }
import com.tresorit.zerokitsdk.fragment.SignInFragment; import com.tresorit.zerokitsdk.module.LoginModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import com.tresorit.zerokitsdk.viewmodel.LoginViewModel; import dagger.Component;
package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = { LoginModule.class }, dependencies = { ApplicationComponent.class } ) public interface LoginComponent {
// Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/SignInFragment.java // public class SignInFragment extends ComponentControllerFragment<LoginComponent> { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // LoginViewModel loginViewModel; // // @Override // protected LoginComponent onCreateNonConfigurationComponent() { // return DaggerLoginComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build(); // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // getComponent().inject(this); // FragmentLoginBinding binding = FragmentLoginBinding.inflate(inflater, container, false); // binding.setViewmodel(loginViewModel); // return binding.getRoot(); // } // // // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/LoginModule.java // @Module // public class LoginModule { // @Provides // @ActivityScope // public LoginViewModel provideLoginViewModel(Zerokit zerokit, AdminApi adminApi, EventBus eventBus) { // return new LoginViewModel(zerokit, adminApi, eventBus); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/LoginViewModel.java // public class LoginViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> userName; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> passwordError; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> usernameError; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgress; // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerLogin; // @SuppressWarnings("WeakerAccess") // public final View.OnFocusChangeListener focusChangeListener; // // @SuppressWarnings("WeakerAccess") // public final PasswordEditText.PasswordExporter passwordExporter; // // @SuppressWarnings("WeakerAccess") // final Zerokit zerokit; // @SuppressWarnings("WeakerAccess") // final AdminApi adminApi; // // @SuppressWarnings("WeakerAccess") // final EventBus eventBus; // // @SuppressWarnings("WeakerAccess") // final Action<ResponseZerokitError> errorResponseHandlerSdk; // @SuppressWarnings("WeakerAccess") // final Action<ResponseAdminApiError> errorResponseHandlerAdminapi; // // @Inject // public LoginViewModel(Zerokit zerokit, AdminApi adminApi, final EventBus eventBus) { // this.zerokit = zerokit; // this.adminApi = adminApi; // this.eventBus = eventBus; // // this.passwordExporter = new PasswordEditText.PasswordExporter(); // // this.clickListenerLogin = new View.OnClickListener() { // @Override // public void onClick(View view) { // attemptLogin(); // } // }; // // userName = new ObservableField<>(""); // passwordError = new ObservableField<>(""); // usernameError = new ObservableField<>(""); // inProgress = new ObservableField<>(false); // errorResponseHandlerSdk = new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // errorResponseHandlerAdminapi = new Action<ResponseAdminApiError>() { // @Override // public void call(ResponseAdminApiError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // focusChangeListener = new View.OnFocusChangeListener() { // @Override // public void onFocusChange(View v, boolean hasFocus) { // passwordError.set(""); // usernameError.set(""); // } // }; // } // // @SuppressWarnings("WeakerAccess") // void attemptLogin() { // if (TextUtils.isEmpty(userName.get())) usernameError.set("Required"); // else if (passwordExporter.isEmpty()) passwordError.set("Required"); // else login(userName.get(), passwordExporter); // } // // private void login(String username, final PasswordEditText.PasswordExporter passwordExporter) { // inProgress.set(true); // adminApi.getUserId(username).enqueue(new Action<String>() { // @Override // public void call(String userId) { // zerokit.login(userId, passwordExporter).enqueue(new Action<ResponseZerokitLogin>() { // @Override // public void call(ResponseZerokitLogin responseLogin) { // zerokit.getIdentityTokens(adminApi.getClientId()).enqueue(new Action<IdentityTokens>() { // @Override // public void call(IdentityTokens identityTokens) { // adminApi.login(identityTokens.getAuthorizationCode()).enqueue(new Action<ResponseAdminApiLoginByCode>() { // @Override // public void call(ResponseAdminApiLoginByCode responseAdminApiLoginByCode) { // adminApi.setToken(responseAdminApiLoginByCode.getId()); // inProgress.set(false); // eventBus.post(new LoginFinisedMessage()); // } // }, errorResponseHandlerAdminapi); // } // }, errorResponseHandlerSdk); // } // }, errorResponseHandlerSdk); // } // }, errorResponseHandlerAdminapi); // } // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/component/LoginComponent.java import com.tresorit.zerokitsdk.fragment.SignInFragment; import com.tresorit.zerokitsdk.module.LoginModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import com.tresorit.zerokitsdk.viewmodel.LoginViewModel; import dagger.Component; package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = { LoginModule.class }, dependencies = { ApplicationComponent.class } ) public interface LoginComponent {
void inject(SignInFragment fragment);
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/component/LoginComponent.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/SignInFragment.java // public class SignInFragment extends ComponentControllerFragment<LoginComponent> { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // LoginViewModel loginViewModel; // // @Override // protected LoginComponent onCreateNonConfigurationComponent() { // return DaggerLoginComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build(); // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // getComponent().inject(this); // FragmentLoginBinding binding = FragmentLoginBinding.inflate(inflater, container, false); // binding.setViewmodel(loginViewModel); // return binding.getRoot(); // } // // // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/LoginModule.java // @Module // public class LoginModule { // @Provides // @ActivityScope // public LoginViewModel provideLoginViewModel(Zerokit zerokit, AdminApi adminApi, EventBus eventBus) { // return new LoginViewModel(zerokit, adminApi, eventBus); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/LoginViewModel.java // public class LoginViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> userName; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> passwordError; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> usernameError; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgress; // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerLogin; // @SuppressWarnings("WeakerAccess") // public final View.OnFocusChangeListener focusChangeListener; // // @SuppressWarnings("WeakerAccess") // public final PasswordEditText.PasswordExporter passwordExporter; // // @SuppressWarnings("WeakerAccess") // final Zerokit zerokit; // @SuppressWarnings("WeakerAccess") // final AdminApi adminApi; // // @SuppressWarnings("WeakerAccess") // final EventBus eventBus; // // @SuppressWarnings("WeakerAccess") // final Action<ResponseZerokitError> errorResponseHandlerSdk; // @SuppressWarnings("WeakerAccess") // final Action<ResponseAdminApiError> errorResponseHandlerAdminapi; // // @Inject // public LoginViewModel(Zerokit zerokit, AdminApi adminApi, final EventBus eventBus) { // this.zerokit = zerokit; // this.adminApi = adminApi; // this.eventBus = eventBus; // // this.passwordExporter = new PasswordEditText.PasswordExporter(); // // this.clickListenerLogin = new View.OnClickListener() { // @Override // public void onClick(View view) { // attemptLogin(); // } // }; // // userName = new ObservableField<>(""); // passwordError = new ObservableField<>(""); // usernameError = new ObservableField<>(""); // inProgress = new ObservableField<>(false); // errorResponseHandlerSdk = new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // errorResponseHandlerAdminapi = new Action<ResponseAdminApiError>() { // @Override // public void call(ResponseAdminApiError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // focusChangeListener = new View.OnFocusChangeListener() { // @Override // public void onFocusChange(View v, boolean hasFocus) { // passwordError.set(""); // usernameError.set(""); // } // }; // } // // @SuppressWarnings("WeakerAccess") // void attemptLogin() { // if (TextUtils.isEmpty(userName.get())) usernameError.set("Required"); // else if (passwordExporter.isEmpty()) passwordError.set("Required"); // else login(userName.get(), passwordExporter); // } // // private void login(String username, final PasswordEditText.PasswordExporter passwordExporter) { // inProgress.set(true); // adminApi.getUserId(username).enqueue(new Action<String>() { // @Override // public void call(String userId) { // zerokit.login(userId, passwordExporter).enqueue(new Action<ResponseZerokitLogin>() { // @Override // public void call(ResponseZerokitLogin responseLogin) { // zerokit.getIdentityTokens(adminApi.getClientId()).enqueue(new Action<IdentityTokens>() { // @Override // public void call(IdentityTokens identityTokens) { // adminApi.login(identityTokens.getAuthorizationCode()).enqueue(new Action<ResponseAdminApiLoginByCode>() { // @Override // public void call(ResponseAdminApiLoginByCode responseAdminApiLoginByCode) { // adminApi.setToken(responseAdminApiLoginByCode.getId()); // inProgress.set(false); // eventBus.post(new LoginFinisedMessage()); // } // }, errorResponseHandlerAdminapi); // } // }, errorResponseHandlerSdk); // } // }, errorResponseHandlerSdk); // } // }, errorResponseHandlerAdminapi); // } // }
import com.tresorit.zerokitsdk.fragment.SignInFragment; import com.tresorit.zerokitsdk.module.LoginModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import com.tresorit.zerokitsdk.viewmodel.LoginViewModel; import dagger.Component;
package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = { LoginModule.class }, dependencies = { ApplicationComponent.class } ) public interface LoginComponent { void inject(SignInFragment fragment);
// Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/SignInFragment.java // public class SignInFragment extends ComponentControllerFragment<LoginComponent> { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // LoginViewModel loginViewModel; // // @Override // protected LoginComponent onCreateNonConfigurationComponent() { // return DaggerLoginComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build(); // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // getComponent().inject(this); // FragmentLoginBinding binding = FragmentLoginBinding.inflate(inflater, container, false); // binding.setViewmodel(loginViewModel); // return binding.getRoot(); // } // // // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/LoginModule.java // @Module // public class LoginModule { // @Provides // @ActivityScope // public LoginViewModel provideLoginViewModel(Zerokit zerokit, AdminApi adminApi, EventBus eventBus) { // return new LoginViewModel(zerokit, adminApi, eventBus); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/LoginViewModel.java // public class LoginViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> userName; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> passwordError; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> usernameError; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgress; // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListenerLogin; // @SuppressWarnings("WeakerAccess") // public final View.OnFocusChangeListener focusChangeListener; // // @SuppressWarnings("WeakerAccess") // public final PasswordEditText.PasswordExporter passwordExporter; // // @SuppressWarnings("WeakerAccess") // final Zerokit zerokit; // @SuppressWarnings("WeakerAccess") // final AdminApi adminApi; // // @SuppressWarnings("WeakerAccess") // final EventBus eventBus; // // @SuppressWarnings("WeakerAccess") // final Action<ResponseZerokitError> errorResponseHandlerSdk; // @SuppressWarnings("WeakerAccess") // final Action<ResponseAdminApiError> errorResponseHandlerAdminapi; // // @Inject // public LoginViewModel(Zerokit zerokit, AdminApi adminApi, final EventBus eventBus) { // this.zerokit = zerokit; // this.adminApi = adminApi; // this.eventBus = eventBus; // // this.passwordExporter = new PasswordEditText.PasswordExporter(); // // this.clickListenerLogin = new View.OnClickListener() { // @Override // public void onClick(View view) { // attemptLogin(); // } // }; // // userName = new ObservableField<>(""); // passwordError = new ObservableField<>(""); // usernameError = new ObservableField<>(""); // inProgress = new ObservableField<>(false); // errorResponseHandlerSdk = new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // errorResponseHandlerAdminapi = new Action<ResponseAdminApiError>() { // @Override // public void call(ResponseAdminApiError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // focusChangeListener = new View.OnFocusChangeListener() { // @Override // public void onFocusChange(View v, boolean hasFocus) { // passwordError.set(""); // usernameError.set(""); // } // }; // } // // @SuppressWarnings("WeakerAccess") // void attemptLogin() { // if (TextUtils.isEmpty(userName.get())) usernameError.set("Required"); // else if (passwordExporter.isEmpty()) passwordError.set("Required"); // else login(userName.get(), passwordExporter); // } // // private void login(String username, final PasswordEditText.PasswordExporter passwordExporter) { // inProgress.set(true); // adminApi.getUserId(username).enqueue(new Action<String>() { // @Override // public void call(String userId) { // zerokit.login(userId, passwordExporter).enqueue(new Action<ResponseZerokitLogin>() { // @Override // public void call(ResponseZerokitLogin responseLogin) { // zerokit.getIdentityTokens(adminApi.getClientId()).enqueue(new Action<IdentityTokens>() { // @Override // public void call(IdentityTokens identityTokens) { // adminApi.login(identityTokens.getAuthorizationCode()).enqueue(new Action<ResponseAdminApiLoginByCode>() { // @Override // public void call(ResponseAdminApiLoginByCode responseAdminApiLoginByCode) { // adminApi.setToken(responseAdminApiLoginByCode.getId()); // inProgress.set(false); // eventBus.post(new LoginFinisedMessage()); // } // }, errorResponseHandlerAdminapi); // } // }, errorResponseHandlerSdk); // } // }, errorResponseHandlerSdk); // } // }, errorResponseHandlerAdminapi); // } // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/component/LoginComponent.java import com.tresorit.zerokitsdk.fragment.SignInFragment; import com.tresorit.zerokitsdk.module.LoginModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import com.tresorit.zerokitsdk.viewmodel.LoginViewModel; import dagger.Component; package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = { LoginModule.class }, dependencies = { ApplicationComponent.class } ) public interface LoginComponent { void inject(SignInFragment fragment);
LoginViewModel viewModel();
tresorit/ZeroKit-Android-SDK
zerokit/src/main/java/com/tresorit/zerokit/response/ResponseZerokitInternalException.java
// Path: zerokit/src/main/java/com/tresorit/zerokit/util/JSONObject.java // public class JSONObject { // // private org.json.JSONObject jsonObject; // // public JSONObject() { // jsonObject = new org.json.JSONObject(); // } // // public JSONObject(String json) { // try { // jsonObject = new org.json.JSONObject(json); // } catch (JSONException e) { // //e.printStackTrace(); // jsonObject = new org.json.JSONObject(); // } // } // // public org.json.JSONObject getJSONObject(String name) { // if (jsonObject != null) // try { // return jsonObject.getJSONObject(name); // } catch (JSONException e) { // //e.printStackTrace(); // } // return new org.json.JSONObject(); // } // // // public String getString(String name) { // if (jsonObject != null) // try { // return jsonObject.getString(name); // } catch (JSONException e) { // //e.printStackTrace(); // } // return ""; // } // // public double getDouble(String name) { // if (jsonObject != null) // try { // return jsonObject.getDouble(name); // } catch (JSONException e) { // //e.printStackTrace(); // } // return 0; // } // // public int getInt(String name) { // if (jsonObject != null) // try { // return jsonObject.getInt(name); // } catch (JSONException e) { // //e.printStackTrace(); // } // return 0; // } // // public List<String> getStringArray(String name) { // if (jsonObject != null) // try { // JSONArray jsonArray = jsonObject.getJSONArray(name); // List<String> result = new ArrayList<>(); // for (int i = 0; i < jsonArray.length(); i++) // result.add(jsonArray.getString(i)); // return result; // } catch (JSONException e) { // //e.printStackTrace(); // } // return new ArrayList<>(); // } // // public JSONObject put(String name, Object value) { // if (jsonObject != null) // try { // jsonObject.put(name, value); // } catch (JSONException e) { // //e.printStackTrace(); // } // return this; // } // // @Override // public String toString() { // return jsonObject != null ? jsonObject.toString() : ""; // } // } // // Path: common/src/main/java/com/tresorit/zerokit/util/ZerokitJson.java // public abstract class ZerokitJson { // // public abstract <T extends ZerokitJson> T parse(String json); // // }
import com.tresorit.zerokit.util.JSONObject; import com.tresorit.zerokit.util.ZerokitJson;
package com.tresorit.zerokit.response; public class ResponseZerokitInternalException extends ZerokitJson { private String type; private String code; @Override public String toString() { return String.format("type: %s, code: %s", type, code); } @SuppressWarnings("unchecked") @Override public ResponseZerokitInternalException parse(String json) {
// Path: zerokit/src/main/java/com/tresorit/zerokit/util/JSONObject.java // public class JSONObject { // // private org.json.JSONObject jsonObject; // // public JSONObject() { // jsonObject = new org.json.JSONObject(); // } // // public JSONObject(String json) { // try { // jsonObject = new org.json.JSONObject(json); // } catch (JSONException e) { // //e.printStackTrace(); // jsonObject = new org.json.JSONObject(); // } // } // // public org.json.JSONObject getJSONObject(String name) { // if (jsonObject != null) // try { // return jsonObject.getJSONObject(name); // } catch (JSONException e) { // //e.printStackTrace(); // } // return new org.json.JSONObject(); // } // // // public String getString(String name) { // if (jsonObject != null) // try { // return jsonObject.getString(name); // } catch (JSONException e) { // //e.printStackTrace(); // } // return ""; // } // // public double getDouble(String name) { // if (jsonObject != null) // try { // return jsonObject.getDouble(name); // } catch (JSONException e) { // //e.printStackTrace(); // } // return 0; // } // // public int getInt(String name) { // if (jsonObject != null) // try { // return jsonObject.getInt(name); // } catch (JSONException e) { // //e.printStackTrace(); // } // return 0; // } // // public List<String> getStringArray(String name) { // if (jsonObject != null) // try { // JSONArray jsonArray = jsonObject.getJSONArray(name); // List<String> result = new ArrayList<>(); // for (int i = 0; i < jsonArray.length(); i++) // result.add(jsonArray.getString(i)); // return result; // } catch (JSONException e) { // //e.printStackTrace(); // } // return new ArrayList<>(); // } // // public JSONObject put(String name, Object value) { // if (jsonObject != null) // try { // jsonObject.put(name, value); // } catch (JSONException e) { // //e.printStackTrace(); // } // return this; // } // // @Override // public String toString() { // return jsonObject != null ? jsonObject.toString() : ""; // } // } // // Path: common/src/main/java/com/tresorit/zerokit/util/ZerokitJson.java // public abstract class ZerokitJson { // // public abstract <T extends ZerokitJson> T parse(String json); // // } // Path: zerokit/src/main/java/com/tresorit/zerokit/response/ResponseZerokitInternalException.java import com.tresorit.zerokit.util.JSONObject; import com.tresorit.zerokit.util.ZerokitJson; package com.tresorit.zerokit.response; public class ResponseZerokitInternalException extends ZerokitJson { private String type; private String code; @Override public String toString() { return String.format("type: %s, code: %s", type, code); } @SuppressWarnings("unchecked") @Override public ResponseZerokitInternalException parse(String json) {
JSONObject jsonobject = new JSONObject(json);
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/module/MainModule.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/MainViewModel.java // public class MainViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final BottomNavigationView.OnNavigationItemSelectedListener onNavigationItemSelectedListener; // // @Inject // public MainViewModel(final EventBus eventBus) { // onNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { // @Override // public boolean onNavigationItemSelected(@NonNull MenuItem item) { // eventBus.post(new TabSelectMessage(item.getItemId())); // return true; // } // }; // } // }
import com.tresorit.zerokitsdk.scopes.ActivityScope; import com.tresorit.zerokitsdk.viewmodel.MainViewModel; import org.greenrobot.eventbus.EventBus; import dagger.Module; import dagger.Provides;
package com.tresorit.zerokitsdk.module; @Module public class MainModule { @Provides @ActivityScope
// Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/MainViewModel.java // public class MainViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final BottomNavigationView.OnNavigationItemSelectedListener onNavigationItemSelectedListener; // // @Inject // public MainViewModel(final EventBus eventBus) { // onNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { // @Override // public boolean onNavigationItemSelected(@NonNull MenuItem item) { // eventBus.post(new TabSelectMessage(item.getItemId())); // return true; // } // }; // } // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/MainModule.java import com.tresorit.zerokitsdk.scopes.ActivityScope; import com.tresorit.zerokitsdk.viewmodel.MainViewModel; import org.greenrobot.eventbus.EventBus; import dagger.Module; import dagger.Provides; package com.tresorit.zerokitsdk.module; @Module public class MainModule { @Provides @ActivityScope
public MainViewModel provideMainViewModel(EventBus eventBus) {
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/activity/SignInActivity.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/cache/ComponentControllerActivity.java // public abstract class ComponentControllerActivity<C> extends ComponentCacheActivity { // // private final ComponentControllerDelegate<C> componentDelegate = new ComponentControllerDelegate<>(); // // @Override // @CallSuper // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // ComponentCache componentCache = this; // componentDelegate.onCreate(componentCache, savedInstanceState, componentFactory); // } // // @Override // @CallSuper // public void onResume() { // super.onResume(); // componentDelegate.onResume(); // } // // @Override // @CallSuper // public void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); // componentDelegate.onSaveInstanceState(outState); // } // // @Override // @CallSuper // public void onDestroy() { // super.onDestroy(); // componentDelegate.onDestroy(); // } // // // protected C getComponent() { // return componentDelegate.getComponent(); // } // // protected abstract C onCreateNonConfigurationComponent(); // // private final ComponentFactory<C> componentFactory = new ComponentFactory<C>() { // @NonNull // @Override // public C createComponent() { // return onCreateNonConfigurationComponent(); // } // }; // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/component/SignInComponent.java // @ActivityScope // @Component( // modules = { // SignInModule.class // }, // dependencies = { // ApplicationComponent.class // } // ) // public interface SignInComponent { // void inject(SignInActivity activity); // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/message/LoginFinisedMessage.java // public class LoginFinisedMessage { // // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/message/ShowMessageMessage.java // public class ShowMessageMessage { // // private final String message; // // public ShowMessageMessage(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/SignInViewModel.java // public class SignInViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final BottomNavigationView.OnNavigationItemSelectedListener onNavigationItemSelectedListener; // @SuppressWarnings("WeakerAccess") // public final ObservableInt displayedChild; // // @Inject // public SignInViewModel(@SuppressWarnings("UnusedParameters") EventBus eventBus) { // displayedChild = new ObservableInt(0); // onNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { // @Override // public boolean onNavigationItemSelected(@NonNull MenuItem item) { // displayedChild.set(item.getItemId() == R.id.tab_signin ? 0 : 1); // return true; // } // }; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/util/Util.java // public static float dpToPx(Context context, float valueInDp) { // DisplayMetrics metrics = context.getResources().getDisplayMetrics(); // return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics); // }
import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.view.View; import android.view.ViewTreeObserver; import com.tresorit.zerokitsdk.R; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.cache.ComponentControllerActivity; import com.tresorit.zerokitsdk.component.DaggerSignInComponent; import com.tresorit.zerokitsdk.component.SignInComponent; import com.tresorit.zerokitsdk.databinding.ActivitySigninBinding; import com.tresorit.zerokitsdk.message.LoginFinisedMessage; import com.tresorit.zerokitsdk.message.ShowMessageMessage; import com.tresorit.zerokitsdk.viewmodel.SignInViewModel; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import javax.inject.Inject; import static com.tresorit.zerokitsdk.util.Util.dpToPx;
package com.tresorit.zerokitsdk.activity; public class SignInActivity extends ComponentControllerActivity<SignInComponent> { private static final int REQ_DEFAULT = 0; @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) @Inject
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/cache/ComponentControllerActivity.java // public abstract class ComponentControllerActivity<C> extends ComponentCacheActivity { // // private final ComponentControllerDelegate<C> componentDelegate = new ComponentControllerDelegate<>(); // // @Override // @CallSuper // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // ComponentCache componentCache = this; // componentDelegate.onCreate(componentCache, savedInstanceState, componentFactory); // } // // @Override // @CallSuper // public void onResume() { // super.onResume(); // componentDelegate.onResume(); // } // // @Override // @CallSuper // public void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); // componentDelegate.onSaveInstanceState(outState); // } // // @Override // @CallSuper // public void onDestroy() { // super.onDestroy(); // componentDelegate.onDestroy(); // } // // // protected C getComponent() { // return componentDelegate.getComponent(); // } // // protected abstract C onCreateNonConfigurationComponent(); // // private final ComponentFactory<C> componentFactory = new ComponentFactory<C>() { // @NonNull // @Override // public C createComponent() { // return onCreateNonConfigurationComponent(); // } // }; // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/component/SignInComponent.java // @ActivityScope // @Component( // modules = { // SignInModule.class // }, // dependencies = { // ApplicationComponent.class // } // ) // public interface SignInComponent { // void inject(SignInActivity activity); // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/message/LoginFinisedMessage.java // public class LoginFinisedMessage { // // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/message/ShowMessageMessage.java // public class ShowMessageMessage { // // private final String message; // // public ShowMessageMessage(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/SignInViewModel.java // public class SignInViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final BottomNavigationView.OnNavigationItemSelectedListener onNavigationItemSelectedListener; // @SuppressWarnings("WeakerAccess") // public final ObservableInt displayedChild; // // @Inject // public SignInViewModel(@SuppressWarnings("UnusedParameters") EventBus eventBus) { // displayedChild = new ObservableInt(0); // onNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { // @Override // public boolean onNavigationItemSelected(@NonNull MenuItem item) { // displayedChild.set(item.getItemId() == R.id.tab_signin ? 0 : 1); // return true; // } // }; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/util/Util.java // public static float dpToPx(Context context, float valueInDp) { // DisplayMetrics metrics = context.getResources().getDisplayMetrics(); // return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics); // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/activity/SignInActivity.java import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.view.View; import android.view.ViewTreeObserver; import com.tresorit.zerokitsdk.R; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.cache.ComponentControllerActivity; import com.tresorit.zerokitsdk.component.DaggerSignInComponent; import com.tresorit.zerokitsdk.component.SignInComponent; import com.tresorit.zerokitsdk.databinding.ActivitySigninBinding; import com.tresorit.zerokitsdk.message.LoginFinisedMessage; import com.tresorit.zerokitsdk.message.ShowMessageMessage; import com.tresorit.zerokitsdk.viewmodel.SignInViewModel; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import javax.inject.Inject; import static com.tresorit.zerokitsdk.util.Util.dpToPx; package com.tresorit.zerokitsdk.activity; public class SignInActivity extends ComponentControllerActivity<SignInComponent> { private static final int REQ_DEFAULT = 0; @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) @Inject
SignInViewModel viewModel;
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/activity/SignInActivity.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/cache/ComponentControllerActivity.java // public abstract class ComponentControllerActivity<C> extends ComponentCacheActivity { // // private final ComponentControllerDelegate<C> componentDelegate = new ComponentControllerDelegate<>(); // // @Override // @CallSuper // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // ComponentCache componentCache = this; // componentDelegate.onCreate(componentCache, savedInstanceState, componentFactory); // } // // @Override // @CallSuper // public void onResume() { // super.onResume(); // componentDelegate.onResume(); // } // // @Override // @CallSuper // public void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); // componentDelegate.onSaveInstanceState(outState); // } // // @Override // @CallSuper // public void onDestroy() { // super.onDestroy(); // componentDelegate.onDestroy(); // } // // // protected C getComponent() { // return componentDelegate.getComponent(); // } // // protected abstract C onCreateNonConfigurationComponent(); // // private final ComponentFactory<C> componentFactory = new ComponentFactory<C>() { // @NonNull // @Override // public C createComponent() { // return onCreateNonConfigurationComponent(); // } // }; // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/component/SignInComponent.java // @ActivityScope // @Component( // modules = { // SignInModule.class // }, // dependencies = { // ApplicationComponent.class // } // ) // public interface SignInComponent { // void inject(SignInActivity activity); // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/message/LoginFinisedMessage.java // public class LoginFinisedMessage { // // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/message/ShowMessageMessage.java // public class ShowMessageMessage { // // private final String message; // // public ShowMessageMessage(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/SignInViewModel.java // public class SignInViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final BottomNavigationView.OnNavigationItemSelectedListener onNavigationItemSelectedListener; // @SuppressWarnings("WeakerAccess") // public final ObservableInt displayedChild; // // @Inject // public SignInViewModel(@SuppressWarnings("UnusedParameters") EventBus eventBus) { // displayedChild = new ObservableInt(0); // onNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { // @Override // public boolean onNavigationItemSelected(@NonNull MenuItem item) { // displayedChild.set(item.getItemId() == R.id.tab_signin ? 0 : 1); // return true; // } // }; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/util/Util.java // public static float dpToPx(Context context, float valueInDp) { // DisplayMetrics metrics = context.getResources().getDisplayMetrics(); // return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics); // }
import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.view.View; import android.view.ViewTreeObserver; import com.tresorit.zerokitsdk.R; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.cache.ComponentControllerActivity; import com.tresorit.zerokitsdk.component.DaggerSignInComponent; import com.tresorit.zerokitsdk.component.SignInComponent; import com.tresorit.zerokitsdk.databinding.ActivitySigninBinding; import com.tresorit.zerokitsdk.message.LoginFinisedMessage; import com.tresorit.zerokitsdk.message.ShowMessageMessage; import com.tresorit.zerokitsdk.viewmodel.SignInViewModel; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import javax.inject.Inject; import static com.tresorit.zerokitsdk.util.Util.dpToPx;
package com.tresorit.zerokitsdk.activity; public class SignInActivity extends ComponentControllerActivity<SignInComponent> { private static final int REQ_DEFAULT = 0; @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) @Inject SignInViewModel viewModel; @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) @Inject EventBus eventBus; @SuppressWarnings("WeakerAccess") ActivitySigninBinding binding; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getComponent().inject(this); binding = DataBindingUtil.setContentView(this, R.layout.activity_signin); binding.setViewmodel(viewModel); binding.container.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { binding.bottomBar.post(new Runnable() { @Override public void run() {
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/cache/ComponentControllerActivity.java // public abstract class ComponentControllerActivity<C> extends ComponentCacheActivity { // // private final ComponentControllerDelegate<C> componentDelegate = new ComponentControllerDelegate<>(); // // @Override // @CallSuper // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // ComponentCache componentCache = this; // componentDelegate.onCreate(componentCache, savedInstanceState, componentFactory); // } // // @Override // @CallSuper // public void onResume() { // super.onResume(); // componentDelegate.onResume(); // } // // @Override // @CallSuper // public void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); // componentDelegate.onSaveInstanceState(outState); // } // // @Override // @CallSuper // public void onDestroy() { // super.onDestroy(); // componentDelegate.onDestroy(); // } // // // protected C getComponent() { // return componentDelegate.getComponent(); // } // // protected abstract C onCreateNonConfigurationComponent(); // // private final ComponentFactory<C> componentFactory = new ComponentFactory<C>() { // @NonNull // @Override // public C createComponent() { // return onCreateNonConfigurationComponent(); // } // }; // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/component/SignInComponent.java // @ActivityScope // @Component( // modules = { // SignInModule.class // }, // dependencies = { // ApplicationComponent.class // } // ) // public interface SignInComponent { // void inject(SignInActivity activity); // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/message/LoginFinisedMessage.java // public class LoginFinisedMessage { // // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/message/ShowMessageMessage.java // public class ShowMessageMessage { // // private final String message; // // public ShowMessageMessage(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/SignInViewModel.java // public class SignInViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final BottomNavigationView.OnNavigationItemSelectedListener onNavigationItemSelectedListener; // @SuppressWarnings("WeakerAccess") // public final ObservableInt displayedChild; // // @Inject // public SignInViewModel(@SuppressWarnings("UnusedParameters") EventBus eventBus) { // displayedChild = new ObservableInt(0); // onNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { // @Override // public boolean onNavigationItemSelected(@NonNull MenuItem item) { // displayedChild.set(item.getItemId() == R.id.tab_signin ? 0 : 1); // return true; // } // }; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/util/Util.java // public static float dpToPx(Context context, float valueInDp) { // DisplayMetrics metrics = context.getResources().getDisplayMetrics(); // return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics); // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/activity/SignInActivity.java import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.view.View; import android.view.ViewTreeObserver; import com.tresorit.zerokitsdk.R; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.cache.ComponentControllerActivity; import com.tresorit.zerokitsdk.component.DaggerSignInComponent; import com.tresorit.zerokitsdk.component.SignInComponent; import com.tresorit.zerokitsdk.databinding.ActivitySigninBinding; import com.tresorit.zerokitsdk.message.LoginFinisedMessage; import com.tresorit.zerokitsdk.message.ShowMessageMessage; import com.tresorit.zerokitsdk.viewmodel.SignInViewModel; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import javax.inject.Inject; import static com.tresorit.zerokitsdk.util.Util.dpToPx; package com.tresorit.zerokitsdk.activity; public class SignInActivity extends ComponentControllerActivity<SignInComponent> { private static final int REQ_DEFAULT = 0; @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) @Inject SignInViewModel viewModel; @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) @Inject EventBus eventBus; @SuppressWarnings("WeakerAccess") ActivitySigninBinding binding; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getComponent().inject(this); binding = DataBindingUtil.setContentView(this, R.layout.activity_signin); binding.setViewmodel(viewModel); binding.container.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { binding.bottomBar.post(new Runnable() { @Override public void run() {
binding.bottomBar.setVisibility(binding.container.getRootView().getHeight() - binding.container.getHeight() > dpToPx(SignInActivity.this, 200) ? View.GONE : View.VISIBLE);
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/activity/SignInActivity.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/cache/ComponentControllerActivity.java // public abstract class ComponentControllerActivity<C> extends ComponentCacheActivity { // // private final ComponentControllerDelegate<C> componentDelegate = new ComponentControllerDelegate<>(); // // @Override // @CallSuper // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // ComponentCache componentCache = this; // componentDelegate.onCreate(componentCache, savedInstanceState, componentFactory); // } // // @Override // @CallSuper // public void onResume() { // super.onResume(); // componentDelegate.onResume(); // } // // @Override // @CallSuper // public void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); // componentDelegate.onSaveInstanceState(outState); // } // // @Override // @CallSuper // public void onDestroy() { // super.onDestroy(); // componentDelegate.onDestroy(); // } // // // protected C getComponent() { // return componentDelegate.getComponent(); // } // // protected abstract C onCreateNonConfigurationComponent(); // // private final ComponentFactory<C> componentFactory = new ComponentFactory<C>() { // @NonNull // @Override // public C createComponent() { // return onCreateNonConfigurationComponent(); // } // }; // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/component/SignInComponent.java // @ActivityScope // @Component( // modules = { // SignInModule.class // }, // dependencies = { // ApplicationComponent.class // } // ) // public interface SignInComponent { // void inject(SignInActivity activity); // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/message/LoginFinisedMessage.java // public class LoginFinisedMessage { // // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/message/ShowMessageMessage.java // public class ShowMessageMessage { // // private final String message; // // public ShowMessageMessage(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/SignInViewModel.java // public class SignInViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final BottomNavigationView.OnNavigationItemSelectedListener onNavigationItemSelectedListener; // @SuppressWarnings("WeakerAccess") // public final ObservableInt displayedChild; // // @Inject // public SignInViewModel(@SuppressWarnings("UnusedParameters") EventBus eventBus) { // displayedChild = new ObservableInt(0); // onNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { // @Override // public boolean onNavigationItemSelected(@NonNull MenuItem item) { // displayedChild.set(item.getItemId() == R.id.tab_signin ? 0 : 1); // return true; // } // }; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/util/Util.java // public static float dpToPx(Context context, float valueInDp) { // DisplayMetrics metrics = context.getResources().getDisplayMetrics(); // return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics); // }
import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.view.View; import android.view.ViewTreeObserver; import com.tresorit.zerokitsdk.R; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.cache.ComponentControllerActivity; import com.tresorit.zerokitsdk.component.DaggerSignInComponent; import com.tresorit.zerokitsdk.component.SignInComponent; import com.tresorit.zerokitsdk.databinding.ActivitySigninBinding; import com.tresorit.zerokitsdk.message.LoginFinisedMessage; import com.tresorit.zerokitsdk.message.ShowMessageMessage; import com.tresorit.zerokitsdk.viewmodel.SignInViewModel; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import javax.inject.Inject; import static com.tresorit.zerokitsdk.util.Util.dpToPx;
SignInViewModel viewModel; @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) @Inject EventBus eventBus; @SuppressWarnings("WeakerAccess") ActivitySigninBinding binding; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getComponent().inject(this); binding = DataBindingUtil.setContentView(this, R.layout.activity_signin); binding.setViewmodel(viewModel); binding.container.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { binding.bottomBar.post(new Runnable() { @Override public void run() { binding.bottomBar.setVisibility(binding.container.getRootView().getHeight() - binding.container.getHeight() > dpToPx(SignInActivity.this, 200) ? View.GONE : View.VISIBLE); } }); } }); } @Override protected SignInComponent onCreateNonConfigurationComponent() {
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/cache/ComponentControllerActivity.java // public abstract class ComponentControllerActivity<C> extends ComponentCacheActivity { // // private final ComponentControllerDelegate<C> componentDelegate = new ComponentControllerDelegate<>(); // // @Override // @CallSuper // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // ComponentCache componentCache = this; // componentDelegate.onCreate(componentCache, savedInstanceState, componentFactory); // } // // @Override // @CallSuper // public void onResume() { // super.onResume(); // componentDelegate.onResume(); // } // // @Override // @CallSuper // public void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); // componentDelegate.onSaveInstanceState(outState); // } // // @Override // @CallSuper // public void onDestroy() { // super.onDestroy(); // componentDelegate.onDestroy(); // } // // // protected C getComponent() { // return componentDelegate.getComponent(); // } // // protected abstract C onCreateNonConfigurationComponent(); // // private final ComponentFactory<C> componentFactory = new ComponentFactory<C>() { // @NonNull // @Override // public C createComponent() { // return onCreateNonConfigurationComponent(); // } // }; // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/component/SignInComponent.java // @ActivityScope // @Component( // modules = { // SignInModule.class // }, // dependencies = { // ApplicationComponent.class // } // ) // public interface SignInComponent { // void inject(SignInActivity activity); // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/message/LoginFinisedMessage.java // public class LoginFinisedMessage { // // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/message/ShowMessageMessage.java // public class ShowMessageMessage { // // private final String message; // // public ShowMessageMessage(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/SignInViewModel.java // public class SignInViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final BottomNavigationView.OnNavigationItemSelectedListener onNavigationItemSelectedListener; // @SuppressWarnings("WeakerAccess") // public final ObservableInt displayedChild; // // @Inject // public SignInViewModel(@SuppressWarnings("UnusedParameters") EventBus eventBus) { // displayedChild = new ObservableInt(0); // onNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { // @Override // public boolean onNavigationItemSelected(@NonNull MenuItem item) { // displayedChild.set(item.getItemId() == R.id.tab_signin ? 0 : 1); // return true; // } // }; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/util/Util.java // public static float dpToPx(Context context, float valueInDp) { // DisplayMetrics metrics = context.getResources().getDisplayMetrics(); // return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics); // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/activity/SignInActivity.java import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.view.View; import android.view.ViewTreeObserver; import com.tresorit.zerokitsdk.R; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.cache.ComponentControllerActivity; import com.tresorit.zerokitsdk.component.DaggerSignInComponent; import com.tresorit.zerokitsdk.component.SignInComponent; import com.tresorit.zerokitsdk.databinding.ActivitySigninBinding; import com.tresorit.zerokitsdk.message.LoginFinisedMessage; import com.tresorit.zerokitsdk.message.ShowMessageMessage; import com.tresorit.zerokitsdk.viewmodel.SignInViewModel; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import javax.inject.Inject; import static com.tresorit.zerokitsdk.util.Util.dpToPx; SignInViewModel viewModel; @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) @Inject EventBus eventBus; @SuppressWarnings("WeakerAccess") ActivitySigninBinding binding; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getComponent().inject(this); binding = DataBindingUtil.setContentView(this, R.layout.activity_signin); binding.setViewmodel(viewModel); binding.container.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { binding.bottomBar.post(new Runnable() { @Override public void run() { binding.bottomBar.setVisibility(binding.container.getRootView().getHeight() - binding.container.getHeight() > dpToPx(SignInActivity.this, 200) ? View.GONE : View.VISIBLE); } }); } }); } @Override protected SignInComponent onCreateNonConfigurationComponent() {
return DaggerSignInComponent.builder().applicationComponent(ZerokitApplication.get(this).component()).build();
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/activity/SignInActivity.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/cache/ComponentControllerActivity.java // public abstract class ComponentControllerActivity<C> extends ComponentCacheActivity { // // private final ComponentControllerDelegate<C> componentDelegate = new ComponentControllerDelegate<>(); // // @Override // @CallSuper // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // ComponentCache componentCache = this; // componentDelegate.onCreate(componentCache, savedInstanceState, componentFactory); // } // // @Override // @CallSuper // public void onResume() { // super.onResume(); // componentDelegate.onResume(); // } // // @Override // @CallSuper // public void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); // componentDelegate.onSaveInstanceState(outState); // } // // @Override // @CallSuper // public void onDestroy() { // super.onDestroy(); // componentDelegate.onDestroy(); // } // // // protected C getComponent() { // return componentDelegate.getComponent(); // } // // protected abstract C onCreateNonConfigurationComponent(); // // private final ComponentFactory<C> componentFactory = new ComponentFactory<C>() { // @NonNull // @Override // public C createComponent() { // return onCreateNonConfigurationComponent(); // } // }; // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/component/SignInComponent.java // @ActivityScope // @Component( // modules = { // SignInModule.class // }, // dependencies = { // ApplicationComponent.class // } // ) // public interface SignInComponent { // void inject(SignInActivity activity); // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/message/LoginFinisedMessage.java // public class LoginFinisedMessage { // // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/message/ShowMessageMessage.java // public class ShowMessageMessage { // // private final String message; // // public ShowMessageMessage(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/SignInViewModel.java // public class SignInViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final BottomNavigationView.OnNavigationItemSelectedListener onNavigationItemSelectedListener; // @SuppressWarnings("WeakerAccess") // public final ObservableInt displayedChild; // // @Inject // public SignInViewModel(@SuppressWarnings("UnusedParameters") EventBus eventBus) { // displayedChild = new ObservableInt(0); // onNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { // @Override // public boolean onNavigationItemSelected(@NonNull MenuItem item) { // displayedChild.set(item.getItemId() == R.id.tab_signin ? 0 : 1); // return true; // } // }; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/util/Util.java // public static float dpToPx(Context context, float valueInDp) { // DisplayMetrics metrics = context.getResources().getDisplayMetrics(); // return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics); // }
import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.view.View; import android.view.ViewTreeObserver; import com.tresorit.zerokitsdk.R; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.cache.ComponentControllerActivity; import com.tresorit.zerokitsdk.component.DaggerSignInComponent; import com.tresorit.zerokitsdk.component.SignInComponent; import com.tresorit.zerokitsdk.databinding.ActivitySigninBinding; import com.tresorit.zerokitsdk.message.LoginFinisedMessage; import com.tresorit.zerokitsdk.message.ShowMessageMessage; import com.tresorit.zerokitsdk.viewmodel.SignInViewModel; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import javax.inject.Inject; import static com.tresorit.zerokitsdk.util.Util.dpToPx;
@Override protected SignInComponent onCreateNonConfigurationComponent() { return DaggerSignInComponent.builder().applicationComponent(ZerokitApplication.get(this).component()).build(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQ_DEFAULT: finish(); break; } } @Override protected void onStart() { super.onStart(); eventBus.register(this); } @Override protected void onStop() { eventBus.unregister(this); super.onStop(); } @Subscribe @SuppressWarnings("unused")
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/cache/ComponentControllerActivity.java // public abstract class ComponentControllerActivity<C> extends ComponentCacheActivity { // // private final ComponentControllerDelegate<C> componentDelegate = new ComponentControllerDelegate<>(); // // @Override // @CallSuper // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // ComponentCache componentCache = this; // componentDelegate.onCreate(componentCache, savedInstanceState, componentFactory); // } // // @Override // @CallSuper // public void onResume() { // super.onResume(); // componentDelegate.onResume(); // } // // @Override // @CallSuper // public void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); // componentDelegate.onSaveInstanceState(outState); // } // // @Override // @CallSuper // public void onDestroy() { // super.onDestroy(); // componentDelegate.onDestroy(); // } // // // protected C getComponent() { // return componentDelegate.getComponent(); // } // // protected abstract C onCreateNonConfigurationComponent(); // // private final ComponentFactory<C> componentFactory = new ComponentFactory<C>() { // @NonNull // @Override // public C createComponent() { // return onCreateNonConfigurationComponent(); // } // }; // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/component/SignInComponent.java // @ActivityScope // @Component( // modules = { // SignInModule.class // }, // dependencies = { // ApplicationComponent.class // } // ) // public interface SignInComponent { // void inject(SignInActivity activity); // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/message/LoginFinisedMessage.java // public class LoginFinisedMessage { // // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/message/ShowMessageMessage.java // public class ShowMessageMessage { // // private final String message; // // public ShowMessageMessage(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/SignInViewModel.java // public class SignInViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final BottomNavigationView.OnNavigationItemSelectedListener onNavigationItemSelectedListener; // @SuppressWarnings("WeakerAccess") // public final ObservableInt displayedChild; // // @Inject // public SignInViewModel(@SuppressWarnings("UnusedParameters") EventBus eventBus) { // displayedChild = new ObservableInt(0); // onNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { // @Override // public boolean onNavigationItemSelected(@NonNull MenuItem item) { // displayedChild.set(item.getItemId() == R.id.tab_signin ? 0 : 1); // return true; // } // }; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/util/Util.java // public static float dpToPx(Context context, float valueInDp) { // DisplayMetrics metrics = context.getResources().getDisplayMetrics(); // return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics); // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/activity/SignInActivity.java import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.view.View; import android.view.ViewTreeObserver; import com.tresorit.zerokitsdk.R; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.cache.ComponentControllerActivity; import com.tresorit.zerokitsdk.component.DaggerSignInComponent; import com.tresorit.zerokitsdk.component.SignInComponent; import com.tresorit.zerokitsdk.databinding.ActivitySigninBinding; import com.tresorit.zerokitsdk.message.LoginFinisedMessage; import com.tresorit.zerokitsdk.message.ShowMessageMessage; import com.tresorit.zerokitsdk.viewmodel.SignInViewModel; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import javax.inject.Inject; import static com.tresorit.zerokitsdk.util.Util.dpToPx; @Override protected SignInComponent onCreateNonConfigurationComponent() { return DaggerSignInComponent.builder().applicationComponent(ZerokitApplication.get(this).component()).build(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQ_DEFAULT: finish(); break; } } @Override protected void onStart() { super.onStart(); eventBus.register(this); } @Override protected void onStop() { eventBus.unregister(this); super.onStop(); } @Subscribe @SuppressWarnings("unused")
public void onEvent(ShowMessageMessage message) {
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/activity/SignInActivity.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/cache/ComponentControllerActivity.java // public abstract class ComponentControllerActivity<C> extends ComponentCacheActivity { // // private final ComponentControllerDelegate<C> componentDelegate = new ComponentControllerDelegate<>(); // // @Override // @CallSuper // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // ComponentCache componentCache = this; // componentDelegate.onCreate(componentCache, savedInstanceState, componentFactory); // } // // @Override // @CallSuper // public void onResume() { // super.onResume(); // componentDelegate.onResume(); // } // // @Override // @CallSuper // public void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); // componentDelegate.onSaveInstanceState(outState); // } // // @Override // @CallSuper // public void onDestroy() { // super.onDestroy(); // componentDelegate.onDestroy(); // } // // // protected C getComponent() { // return componentDelegate.getComponent(); // } // // protected abstract C onCreateNonConfigurationComponent(); // // private final ComponentFactory<C> componentFactory = new ComponentFactory<C>() { // @NonNull // @Override // public C createComponent() { // return onCreateNonConfigurationComponent(); // } // }; // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/component/SignInComponent.java // @ActivityScope // @Component( // modules = { // SignInModule.class // }, // dependencies = { // ApplicationComponent.class // } // ) // public interface SignInComponent { // void inject(SignInActivity activity); // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/message/LoginFinisedMessage.java // public class LoginFinisedMessage { // // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/message/ShowMessageMessage.java // public class ShowMessageMessage { // // private final String message; // // public ShowMessageMessage(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/SignInViewModel.java // public class SignInViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final BottomNavigationView.OnNavigationItemSelectedListener onNavigationItemSelectedListener; // @SuppressWarnings("WeakerAccess") // public final ObservableInt displayedChild; // // @Inject // public SignInViewModel(@SuppressWarnings("UnusedParameters") EventBus eventBus) { // displayedChild = new ObservableInt(0); // onNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { // @Override // public boolean onNavigationItemSelected(@NonNull MenuItem item) { // displayedChild.set(item.getItemId() == R.id.tab_signin ? 0 : 1); // return true; // } // }; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/util/Util.java // public static float dpToPx(Context context, float valueInDp) { // DisplayMetrics metrics = context.getResources().getDisplayMetrics(); // return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics); // }
import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.view.View; import android.view.ViewTreeObserver; import com.tresorit.zerokitsdk.R; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.cache.ComponentControllerActivity; import com.tresorit.zerokitsdk.component.DaggerSignInComponent; import com.tresorit.zerokitsdk.component.SignInComponent; import com.tresorit.zerokitsdk.databinding.ActivitySigninBinding; import com.tresorit.zerokitsdk.message.LoginFinisedMessage; import com.tresorit.zerokitsdk.message.ShowMessageMessage; import com.tresorit.zerokitsdk.viewmodel.SignInViewModel; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import javax.inject.Inject; import static com.tresorit.zerokitsdk.util.Util.dpToPx;
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQ_DEFAULT: finish(); break; } } @Override protected void onStart() { super.onStart(); eventBus.register(this); } @Override protected void onStop() { eventBus.unregister(this); super.onStop(); } @Subscribe @SuppressWarnings("unused") public void onEvent(ShowMessageMessage message) { showMessage(message.getMessage()); } @Subscribe @SuppressWarnings("unused")
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/cache/ComponentControllerActivity.java // public abstract class ComponentControllerActivity<C> extends ComponentCacheActivity { // // private final ComponentControllerDelegate<C> componentDelegate = new ComponentControllerDelegate<>(); // // @Override // @CallSuper // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // ComponentCache componentCache = this; // componentDelegate.onCreate(componentCache, savedInstanceState, componentFactory); // } // // @Override // @CallSuper // public void onResume() { // super.onResume(); // componentDelegate.onResume(); // } // // @Override // @CallSuper // public void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); // componentDelegate.onSaveInstanceState(outState); // } // // @Override // @CallSuper // public void onDestroy() { // super.onDestroy(); // componentDelegate.onDestroy(); // } // // // protected C getComponent() { // return componentDelegate.getComponent(); // } // // protected abstract C onCreateNonConfigurationComponent(); // // private final ComponentFactory<C> componentFactory = new ComponentFactory<C>() { // @NonNull // @Override // public C createComponent() { // return onCreateNonConfigurationComponent(); // } // }; // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/component/SignInComponent.java // @ActivityScope // @Component( // modules = { // SignInModule.class // }, // dependencies = { // ApplicationComponent.class // } // ) // public interface SignInComponent { // void inject(SignInActivity activity); // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/message/LoginFinisedMessage.java // public class LoginFinisedMessage { // // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/message/ShowMessageMessage.java // public class ShowMessageMessage { // // private final String message; // // public ShowMessageMessage(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/SignInViewModel.java // public class SignInViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final BottomNavigationView.OnNavigationItemSelectedListener onNavigationItemSelectedListener; // @SuppressWarnings("WeakerAccess") // public final ObservableInt displayedChild; // // @Inject // public SignInViewModel(@SuppressWarnings("UnusedParameters") EventBus eventBus) { // displayedChild = new ObservableInt(0); // onNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { // @Override // public boolean onNavigationItemSelected(@NonNull MenuItem item) { // displayedChild.set(item.getItemId() == R.id.tab_signin ? 0 : 1); // return true; // } // }; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/util/Util.java // public static float dpToPx(Context context, float valueInDp) { // DisplayMetrics metrics = context.getResources().getDisplayMetrics(); // return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics); // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/activity/SignInActivity.java import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.view.View; import android.view.ViewTreeObserver; import com.tresorit.zerokitsdk.R; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.cache.ComponentControllerActivity; import com.tresorit.zerokitsdk.component.DaggerSignInComponent; import com.tresorit.zerokitsdk.component.SignInComponent; import com.tresorit.zerokitsdk.databinding.ActivitySigninBinding; import com.tresorit.zerokitsdk.message.LoginFinisedMessage; import com.tresorit.zerokitsdk.message.ShowMessageMessage; import com.tresorit.zerokitsdk.viewmodel.SignInViewModel; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import javax.inject.Inject; import static com.tresorit.zerokitsdk.util.Util.dpToPx; protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQ_DEFAULT: finish(); break; } } @Override protected void onStart() { super.onStart(); eventBus.register(this); } @Override protected void onStop() { eventBus.unregister(this); super.onStop(); } @Subscribe @SuppressWarnings("unused") public void onEvent(ShowMessageMessage message) { showMessage(message.getMessage()); } @Subscribe @SuppressWarnings("unused")
public void onEvent(@SuppressWarnings("UnusedParameters") LoginFinisedMessage message) {
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/adapter/EncryptPagerAdapter.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/CreateTresorFragment.java // public class CreateTresorFragment extends Fragment { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorViewModel viewModel; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerCreateTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentCreateTresorBinding binding = FragmentCreateTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java // public class EncryptTextFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptTextViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerEncryptTextComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentEncryptTextBinding binding = FragmentEncryptTextBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/ShareTresorFragment.java // public class ShareTresorFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // ShareTresorViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerShareTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentShareTresorBinding binding = FragmentShareTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // }
import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.component.DaggerPagerComponent; import com.tresorit.zerokitsdk.fragment.CreateTresorFragment; import com.tresorit.zerokitsdk.fragment.EncryptTextFragment; import com.tresorit.zerokitsdk.fragment.ShareTresorFragment; import javax.inject.Inject;
package com.tresorit.zerokitsdk.adapter; public class EncryptPagerAdapter extends FragmentPagerAdapter { @SuppressWarnings("WeakerAccess") @Inject
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/CreateTresorFragment.java // public class CreateTresorFragment extends Fragment { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorViewModel viewModel; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerCreateTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentCreateTresorBinding binding = FragmentCreateTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java // public class EncryptTextFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptTextViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerEncryptTextComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentEncryptTextBinding binding = FragmentEncryptTextBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/ShareTresorFragment.java // public class ShareTresorFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // ShareTresorViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerShareTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentShareTresorBinding binding = FragmentShareTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/adapter/EncryptPagerAdapter.java import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.component.DaggerPagerComponent; import com.tresorit.zerokitsdk.fragment.CreateTresorFragment; import com.tresorit.zerokitsdk.fragment.EncryptTextFragment; import com.tresorit.zerokitsdk.fragment.ShareTresorFragment; import javax.inject.Inject; package com.tresorit.zerokitsdk.adapter; public class EncryptPagerAdapter extends FragmentPagerAdapter { @SuppressWarnings("WeakerAccess") @Inject
CreateTresorFragment createTresorFragment;
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/adapter/EncryptPagerAdapter.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/CreateTresorFragment.java // public class CreateTresorFragment extends Fragment { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorViewModel viewModel; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerCreateTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentCreateTresorBinding binding = FragmentCreateTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java // public class EncryptTextFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptTextViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerEncryptTextComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentEncryptTextBinding binding = FragmentEncryptTextBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/ShareTresorFragment.java // public class ShareTresorFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // ShareTresorViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerShareTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentShareTresorBinding binding = FragmentShareTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // }
import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.component.DaggerPagerComponent; import com.tresorit.zerokitsdk.fragment.CreateTresorFragment; import com.tresorit.zerokitsdk.fragment.EncryptTextFragment; import com.tresorit.zerokitsdk.fragment.ShareTresorFragment; import javax.inject.Inject;
package com.tresorit.zerokitsdk.adapter; public class EncryptPagerAdapter extends FragmentPagerAdapter { @SuppressWarnings("WeakerAccess") @Inject CreateTresorFragment createTresorFragment; @SuppressWarnings("WeakerAccess") @Inject
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/CreateTresorFragment.java // public class CreateTresorFragment extends Fragment { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorViewModel viewModel; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerCreateTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentCreateTresorBinding binding = FragmentCreateTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java // public class EncryptTextFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptTextViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerEncryptTextComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentEncryptTextBinding binding = FragmentEncryptTextBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/ShareTresorFragment.java // public class ShareTresorFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // ShareTresorViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerShareTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentShareTresorBinding binding = FragmentShareTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/adapter/EncryptPagerAdapter.java import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.component.DaggerPagerComponent; import com.tresorit.zerokitsdk.fragment.CreateTresorFragment; import com.tresorit.zerokitsdk.fragment.EncryptTextFragment; import com.tresorit.zerokitsdk.fragment.ShareTresorFragment; import javax.inject.Inject; package com.tresorit.zerokitsdk.adapter; public class EncryptPagerAdapter extends FragmentPagerAdapter { @SuppressWarnings("WeakerAccess") @Inject CreateTresorFragment createTresorFragment; @SuppressWarnings("WeakerAccess") @Inject
EncryptTextFragment encryptTextFragment;
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/adapter/EncryptPagerAdapter.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/CreateTresorFragment.java // public class CreateTresorFragment extends Fragment { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorViewModel viewModel; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerCreateTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentCreateTresorBinding binding = FragmentCreateTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java // public class EncryptTextFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptTextViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerEncryptTextComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentEncryptTextBinding binding = FragmentEncryptTextBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/ShareTresorFragment.java // public class ShareTresorFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // ShareTresorViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerShareTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentShareTresorBinding binding = FragmentShareTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // }
import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.component.DaggerPagerComponent; import com.tresorit.zerokitsdk.fragment.CreateTresorFragment; import com.tresorit.zerokitsdk.fragment.EncryptTextFragment; import com.tresorit.zerokitsdk.fragment.ShareTresorFragment; import javax.inject.Inject;
package com.tresorit.zerokitsdk.adapter; public class EncryptPagerAdapter extends FragmentPagerAdapter { @SuppressWarnings("WeakerAccess") @Inject CreateTresorFragment createTresorFragment; @SuppressWarnings("WeakerAccess") @Inject EncryptTextFragment encryptTextFragment; @SuppressWarnings("WeakerAccess") @Inject
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/CreateTresorFragment.java // public class CreateTresorFragment extends Fragment { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorViewModel viewModel; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerCreateTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentCreateTresorBinding binding = FragmentCreateTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java // public class EncryptTextFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptTextViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerEncryptTextComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentEncryptTextBinding binding = FragmentEncryptTextBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/ShareTresorFragment.java // public class ShareTresorFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // ShareTresorViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerShareTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentShareTresorBinding binding = FragmentShareTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/adapter/EncryptPagerAdapter.java import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.component.DaggerPagerComponent; import com.tresorit.zerokitsdk.fragment.CreateTresorFragment; import com.tresorit.zerokitsdk.fragment.EncryptTextFragment; import com.tresorit.zerokitsdk.fragment.ShareTresorFragment; import javax.inject.Inject; package com.tresorit.zerokitsdk.adapter; public class EncryptPagerAdapter extends FragmentPagerAdapter { @SuppressWarnings("WeakerAccess") @Inject CreateTresorFragment createTresorFragment; @SuppressWarnings("WeakerAccess") @Inject EncryptTextFragment encryptTextFragment; @SuppressWarnings("WeakerAccess") @Inject
ShareTresorFragment shareTresorFragment;
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/adapter/EncryptPagerAdapter.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/CreateTresorFragment.java // public class CreateTresorFragment extends Fragment { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorViewModel viewModel; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerCreateTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentCreateTresorBinding binding = FragmentCreateTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java // public class EncryptTextFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptTextViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerEncryptTextComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentEncryptTextBinding binding = FragmentEncryptTextBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/ShareTresorFragment.java // public class ShareTresorFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // ShareTresorViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerShareTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentShareTresorBinding binding = FragmentShareTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // }
import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.component.DaggerPagerComponent; import com.tresorit.zerokitsdk.fragment.CreateTresorFragment; import com.tresorit.zerokitsdk.fragment.EncryptTextFragment; import com.tresorit.zerokitsdk.fragment.ShareTresorFragment; import javax.inject.Inject;
package com.tresorit.zerokitsdk.adapter; public class EncryptPagerAdapter extends FragmentPagerAdapter { @SuppressWarnings("WeakerAccess") @Inject CreateTresorFragment createTresorFragment; @SuppressWarnings("WeakerAccess") @Inject EncryptTextFragment encryptTextFragment; @SuppressWarnings("WeakerAccess") @Inject ShareTresorFragment shareTresorFragment; public EncryptPagerAdapter(Context context, FragmentManager fm) { super(fm);
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/CreateTresorFragment.java // public class CreateTresorFragment extends Fragment { // // @SuppressWarnings("WeakerAccess") // @Inject // CreateTresorViewModel viewModel; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerCreateTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentCreateTresorBinding binding = FragmentCreateTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptTextFragment.java // public class EncryptTextFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptTextViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerEncryptTextComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentEncryptTextBinding binding = FragmentEncryptTextBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/ShareTresorFragment.java // public class ShareTresorFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // ShareTresorViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // DaggerShareTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this); // FragmentShareTresorBinding binding = FragmentShareTresorBinding.inflate(inflater, container, false); // binding.setViewmodel(viewModel); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(viewModel); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(viewModel); // } // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/adapter/EncryptPagerAdapter.java import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.component.DaggerPagerComponent; import com.tresorit.zerokitsdk.fragment.CreateTresorFragment; import com.tresorit.zerokitsdk.fragment.EncryptTextFragment; import com.tresorit.zerokitsdk.fragment.ShareTresorFragment; import javax.inject.Inject; package com.tresorit.zerokitsdk.adapter; public class EncryptPagerAdapter extends FragmentPagerAdapter { @SuppressWarnings("WeakerAccess") @Inject CreateTresorFragment createTresorFragment; @SuppressWarnings("WeakerAccess") @Inject EncryptTextFragment encryptTextFragment; @SuppressWarnings("WeakerAccess") @Inject ShareTresorFragment shareTresorFragment; public EncryptPagerAdapter(Context context, FragmentManager fm) { super(fm);
DaggerPagerComponent.builder().applicationComponent(ZerokitApplication.get(context).component()).build().inject(this);
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/component/RootComponent.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/activity/RootActivity.java // public class RootActivity extends AppCompatActivity { // // private static final int REQ_DEFAULT = 0; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // Zerokit zerokit; // // private boolean start = true; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // DaggerRootComponent.builder().applicationComponent(ZerokitApplication.get(this).component()).build().inject(this); // } // // @Override // protected void onNewIntent(Intent intent) { // super.onNewIntent(intent); // start = true; // } // // @Override // protected void onStart() { // super.onStart(); // if (!start) finish(); // else { // start = false; // zerokit.whoAmI().enqueue(new Action<String>() { // @Override // public void call(String response) { // if ("null".equals(response)) // startActivityForResult(new Intent(RootActivity.this, SignInActivity.class), REQ_DEFAULT); // else // startActivityForResult(new Intent(RootActivity.this, MainActivity.class), REQ_DEFAULT); // } // }, new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError responseZerokitError) { // Toast.makeText(RootActivity.this, responseZerokitError.getDescription(), Toast.LENGTH_SHORT).show(); // startActivityForResult(new Intent(RootActivity.this, SignInActivity.class), REQ_DEFAULT); // } // }); // // } // } // }
import com.tresorit.zerokitsdk.activity.RootActivity; import com.tresorit.zerokitsdk.scopes.ActivityScope; import dagger.Component;
package com.tresorit.zerokitsdk.component; @ActivityScope @Component( dependencies = { ApplicationComponent.class } ) public interface RootComponent {
// Path: sample/src/main/java/com/tresorit/zerokitsdk/activity/RootActivity.java // public class RootActivity extends AppCompatActivity { // // private static final int REQ_DEFAULT = 0; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // Zerokit zerokit; // // private boolean start = true; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // DaggerRootComponent.builder().applicationComponent(ZerokitApplication.get(this).component()).build().inject(this); // } // // @Override // protected void onNewIntent(Intent intent) { // super.onNewIntent(intent); // start = true; // } // // @Override // protected void onStart() { // super.onStart(); // if (!start) finish(); // else { // start = false; // zerokit.whoAmI().enqueue(new Action<String>() { // @Override // public void call(String response) { // if ("null".equals(response)) // startActivityForResult(new Intent(RootActivity.this, SignInActivity.class), REQ_DEFAULT); // else // startActivityForResult(new Intent(RootActivity.this, MainActivity.class), REQ_DEFAULT); // } // }, new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError responseZerokitError) { // Toast.makeText(RootActivity.this, responseZerokitError.getDescription(), Toast.LENGTH_SHORT).show(); // startActivityForResult(new Intent(RootActivity.this, SignInActivity.class), REQ_DEFAULT); // } // }); // // } // } // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/component/RootComponent.java import com.tresorit.zerokitsdk.activity.RootActivity; import com.tresorit.zerokitsdk.scopes.ActivityScope; import dagger.Component; package com.tresorit.zerokitsdk.component; @ActivityScope @Component( dependencies = { ApplicationComponent.class } ) public interface RootComponent {
void inject(RootActivity activity);
tresorit/ZeroKit-Android-SDK
zerokit/src/main/java/com/tresorit/zerokit/response/Feedback.java
// Path: zerokit/src/main/java/com/tresorit/zerokit/util/JSONObject.java // public class JSONObject { // // private org.json.JSONObject jsonObject; // // public JSONObject() { // jsonObject = new org.json.JSONObject(); // } // // public JSONObject(String json) { // try { // jsonObject = new org.json.JSONObject(json); // } catch (JSONException e) { // //e.printStackTrace(); // jsonObject = new org.json.JSONObject(); // } // } // // public org.json.JSONObject getJSONObject(String name) { // if (jsonObject != null) // try { // return jsonObject.getJSONObject(name); // } catch (JSONException e) { // //e.printStackTrace(); // } // return new org.json.JSONObject(); // } // // // public String getString(String name) { // if (jsonObject != null) // try { // return jsonObject.getString(name); // } catch (JSONException e) { // //e.printStackTrace(); // } // return ""; // } // // public double getDouble(String name) { // if (jsonObject != null) // try { // return jsonObject.getDouble(name); // } catch (JSONException e) { // //e.printStackTrace(); // } // return 0; // } // // public int getInt(String name) { // if (jsonObject != null) // try { // return jsonObject.getInt(name); // } catch (JSONException e) { // //e.printStackTrace(); // } // return 0; // } // // public List<String> getStringArray(String name) { // if (jsonObject != null) // try { // JSONArray jsonArray = jsonObject.getJSONArray(name); // List<String> result = new ArrayList<>(); // for (int i = 0; i < jsonArray.length(); i++) // result.add(jsonArray.getString(i)); // return result; // } catch (JSONException e) { // //e.printStackTrace(); // } // return new ArrayList<>(); // } // // public JSONObject put(String name, Object value) { // if (jsonObject != null) // try { // jsonObject.put(name, value); // } catch (JSONException e) { // //e.printStackTrace(); // } // return this; // } // // @Override // public String toString() { // return jsonObject != null ? jsonObject.toString() : ""; // } // } // // Path: common/src/main/java/com/tresorit/zerokit/util/ZerokitJson.java // public abstract class ZerokitJson { // // public abstract <T extends ZerokitJson> T parse(String json); // // }
import android.text.TextUtils; import com.tresorit.zerokit.util.JSONObject; import com.tresorit.zerokit.util.ZerokitJson; import java.util.List;
package com.tresorit.zerokit.response; @SuppressWarnings("WeakerAccess") public class Feedback extends ZerokitJson { private List<String> suggestions; private String warning; public List<String> getSuggestions() { return suggestions; } public String getWarning() { return warning; } @Override public String toString() { return String.format("suggestions: %s, warning: %s", TextUtils.join(", ", suggestions), warning); } @SuppressWarnings("unchecked") @Override public <T extends ZerokitJson> T parse(String json) {
// Path: zerokit/src/main/java/com/tresorit/zerokit/util/JSONObject.java // public class JSONObject { // // private org.json.JSONObject jsonObject; // // public JSONObject() { // jsonObject = new org.json.JSONObject(); // } // // public JSONObject(String json) { // try { // jsonObject = new org.json.JSONObject(json); // } catch (JSONException e) { // //e.printStackTrace(); // jsonObject = new org.json.JSONObject(); // } // } // // public org.json.JSONObject getJSONObject(String name) { // if (jsonObject != null) // try { // return jsonObject.getJSONObject(name); // } catch (JSONException e) { // //e.printStackTrace(); // } // return new org.json.JSONObject(); // } // // // public String getString(String name) { // if (jsonObject != null) // try { // return jsonObject.getString(name); // } catch (JSONException e) { // //e.printStackTrace(); // } // return ""; // } // // public double getDouble(String name) { // if (jsonObject != null) // try { // return jsonObject.getDouble(name); // } catch (JSONException e) { // //e.printStackTrace(); // } // return 0; // } // // public int getInt(String name) { // if (jsonObject != null) // try { // return jsonObject.getInt(name); // } catch (JSONException e) { // //e.printStackTrace(); // } // return 0; // } // // public List<String> getStringArray(String name) { // if (jsonObject != null) // try { // JSONArray jsonArray = jsonObject.getJSONArray(name); // List<String> result = new ArrayList<>(); // for (int i = 0; i < jsonArray.length(); i++) // result.add(jsonArray.getString(i)); // return result; // } catch (JSONException e) { // //e.printStackTrace(); // } // return new ArrayList<>(); // } // // public JSONObject put(String name, Object value) { // if (jsonObject != null) // try { // jsonObject.put(name, value); // } catch (JSONException e) { // //e.printStackTrace(); // } // return this; // } // // @Override // public String toString() { // return jsonObject != null ? jsonObject.toString() : ""; // } // } // // Path: common/src/main/java/com/tresorit/zerokit/util/ZerokitJson.java // public abstract class ZerokitJson { // // public abstract <T extends ZerokitJson> T parse(String json); // // } // Path: zerokit/src/main/java/com/tresorit/zerokit/response/Feedback.java import android.text.TextUtils; import com.tresorit.zerokit.util.JSONObject; import com.tresorit.zerokit.util.ZerokitJson; import java.util.List; package com.tresorit.zerokit.response; @SuppressWarnings("WeakerAccess") public class Feedback extends ZerokitJson { private List<String> suggestions; private String warning; public List<String> getSuggestions() { return suggestions; } public String getWarning() { return warning; } @Override public String toString() { return String.format("suggestions: %s, warning: %s", TextUtils.join(", ", suggestions), warning); } @SuppressWarnings("unchecked") @Override public <T extends ZerokitJson> T parse(String json) {
JSONObject jsonObject = new JSONObject(json);
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/module/EncryptModule.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/EncryptViewModel.java // public class EncryptViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final EncryptPagerAdapter pagerAdapter; // @SuppressWarnings("WeakerAccess") // public final ViewPager.OnPageChangeListener pageChangeListener; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Drawable> drawableDot1; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Drawable> drawableDot2; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Drawable> drawableDot3; // // // public EncryptViewModel(final Context context, FragmentManager fragmentManager) { // pagerAdapter = new EncryptPagerAdapter(context, fragmentManager); // pageChangeListener = new ViewPager.SimpleOnPageChangeListener() { // // @Override // public void onPageSelected(int position) { // drawableDot1.set(context.getResources().getDrawable(position == 0 ? R.drawable.selecteditem_dot : R.drawable.nonselecteditem_dot)); // drawableDot2.set(context.getResources().getDrawable(position == 1 ? R.drawable.selecteditem_dot : R.drawable.nonselecteditem_dot)); // drawableDot3.set(context.getResources().getDrawable(position == 2 ? R.drawable.selecteditem_dot : R.drawable.nonselecteditem_dot)); // } // // }; // // drawableDot1 = new ObservableField<>(context.getResources().getDrawable(R.drawable.selecteditem_dot)); // drawableDot2 = new ObservableField<>(context.getResources().getDrawable(R.drawable.nonselecteditem_dot)); // drawableDot3 = new ObservableField<>(context.getResources().getDrawable(R.drawable.nonselecteditem_dot)); // } // // // // }
import android.content.Context; import android.support.v4.app.FragmentManager; import com.tresorit.zerokitsdk.scopes.ActivityScope; import com.tresorit.zerokitsdk.viewmodel.EncryptViewModel; import dagger.Module; import dagger.Provides;
package com.tresorit.zerokitsdk.module; @Module public class EncryptModule { private final FragmentManager fragmentManager; public EncryptModule(FragmentManager fragmentManager) { this.fragmentManager = fragmentManager; } @Provides @ActivityScope
// Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/EncryptViewModel.java // public class EncryptViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final EncryptPagerAdapter pagerAdapter; // @SuppressWarnings("WeakerAccess") // public final ViewPager.OnPageChangeListener pageChangeListener; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Drawable> drawableDot1; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Drawable> drawableDot2; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Drawable> drawableDot3; // // // public EncryptViewModel(final Context context, FragmentManager fragmentManager) { // pagerAdapter = new EncryptPagerAdapter(context, fragmentManager); // pageChangeListener = new ViewPager.SimpleOnPageChangeListener() { // // @Override // public void onPageSelected(int position) { // drawableDot1.set(context.getResources().getDrawable(position == 0 ? R.drawable.selecteditem_dot : R.drawable.nonselecteditem_dot)); // drawableDot2.set(context.getResources().getDrawable(position == 1 ? R.drawable.selecteditem_dot : R.drawable.nonselecteditem_dot)); // drawableDot3.set(context.getResources().getDrawable(position == 2 ? R.drawable.selecteditem_dot : R.drawable.nonselecteditem_dot)); // } // // }; // // drawableDot1 = new ObservableField<>(context.getResources().getDrawable(R.drawable.selecteditem_dot)); // drawableDot2 = new ObservableField<>(context.getResources().getDrawable(R.drawable.nonselecteditem_dot)); // drawableDot3 = new ObservableField<>(context.getResources().getDrawable(R.drawable.nonselecteditem_dot)); // } // // // // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/EncryptModule.java import android.content.Context; import android.support.v4.app.FragmentManager; import com.tresorit.zerokitsdk.scopes.ActivityScope; import com.tresorit.zerokitsdk.viewmodel.EncryptViewModel; import dagger.Module; import dagger.Provides; package com.tresorit.zerokitsdk.module; @Module public class EncryptModule { private final FragmentManager fragmentManager; public EncryptModule(FragmentManager fragmentManager) { this.fragmentManager = fragmentManager; } @Provides @ActivityScope
public EncryptViewModel provideEncryptViewModel(Context context) {
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/fragment/CreateTresorFragment.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/CreateTresorViewModel.java // public class CreateTresorViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListener; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgress; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> tresorId; // // private final Zerokit zerokit; // // @SuppressWarnings("WeakerAccess") // final AdminApi adminApi; // @SuppressWarnings("WeakerAccess") // final EventBus eventBus; // // @SuppressWarnings("WeakerAccess") // final Action<ResponseZerokitError> errorResponseHandlerSdk; // @SuppressWarnings("WeakerAccess") // final Action<ResponseAdminApiError> errorResponseHandlerAdminapi; // // // @Inject // public CreateTresorViewModel(final Zerokit zerokit, final AdminApi adminApi, final EventBus eventBus) { // this.zerokit = zerokit; // this.adminApi = adminApi; // this.eventBus = eventBus; // // // this.inProgress = new ObservableField<>(false); // this.tresorId = new ObservableField<>(""); // this.clickListener = new View.OnClickListener() { // @Override // public void onClick(View v) { // createTresor(); // inProgress.set(true); // } // }; // // errorResponseHandlerSdk = new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // errorResponseHandlerAdminapi = new Action<ResponseAdminApiError>() { // @Override // public void call(ResponseAdminApiError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // } // // @SuppressWarnings("WeakerAccess") // void createTresor() { // inProgress.set(true); // this.zerokit.createTresor().enqueue(new Action<String>() { // @Override // public void call(final String tresorId) { // adminApi.createdTresor(tresorId).enqueue(new Action<Void>() { // @Override // public void call(Void res) { // CreateTresorViewModel.this.inProgress.set(false); // CreateTresorViewModel.this.tresorId.set("Tresor Id: " + tresorId); // CreateTresorViewModel.this.eventBus.post(new CreateTresorFinishedMessage(tresorId)); // } // }, errorResponseHandlerAdminapi); // } // }, errorResponseHandlerSdk); // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.component.DaggerCreateTresorComponent; import com.tresorit.zerokitsdk.databinding.FragmentCreateTresorBinding; import com.tresorit.zerokitsdk.viewmodel.CreateTresorViewModel; import javax.inject.Inject;
package com.tresorit.zerokitsdk.fragment; public class CreateTresorFragment extends Fragment { @SuppressWarnings("WeakerAccess") @Inject
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/CreateTresorViewModel.java // public class CreateTresorViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListener; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgress; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> tresorId; // // private final Zerokit zerokit; // // @SuppressWarnings("WeakerAccess") // final AdminApi adminApi; // @SuppressWarnings("WeakerAccess") // final EventBus eventBus; // // @SuppressWarnings("WeakerAccess") // final Action<ResponseZerokitError> errorResponseHandlerSdk; // @SuppressWarnings("WeakerAccess") // final Action<ResponseAdminApiError> errorResponseHandlerAdminapi; // // // @Inject // public CreateTresorViewModel(final Zerokit zerokit, final AdminApi adminApi, final EventBus eventBus) { // this.zerokit = zerokit; // this.adminApi = adminApi; // this.eventBus = eventBus; // // // this.inProgress = new ObservableField<>(false); // this.tresorId = new ObservableField<>(""); // this.clickListener = new View.OnClickListener() { // @Override // public void onClick(View v) { // createTresor(); // inProgress.set(true); // } // }; // // errorResponseHandlerSdk = new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // errorResponseHandlerAdminapi = new Action<ResponseAdminApiError>() { // @Override // public void call(ResponseAdminApiError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // } // // @SuppressWarnings("WeakerAccess") // void createTresor() { // inProgress.set(true); // this.zerokit.createTresor().enqueue(new Action<String>() { // @Override // public void call(final String tresorId) { // adminApi.createdTresor(tresorId).enqueue(new Action<Void>() { // @Override // public void call(Void res) { // CreateTresorViewModel.this.inProgress.set(false); // CreateTresorViewModel.this.tresorId.set("Tresor Id: " + tresorId); // CreateTresorViewModel.this.eventBus.post(new CreateTresorFinishedMessage(tresorId)); // } // }, errorResponseHandlerAdminapi); // } // }, errorResponseHandlerSdk); // } // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/CreateTresorFragment.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.component.DaggerCreateTresorComponent; import com.tresorit.zerokitsdk.databinding.FragmentCreateTresorBinding; import com.tresorit.zerokitsdk.viewmodel.CreateTresorViewModel; import javax.inject.Inject; package com.tresorit.zerokitsdk.fragment; public class CreateTresorFragment extends Fragment { @SuppressWarnings("WeakerAccess") @Inject
CreateTresorViewModel viewModel;
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/fragment/CreateTresorFragment.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/CreateTresorViewModel.java // public class CreateTresorViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListener; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgress; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> tresorId; // // private final Zerokit zerokit; // // @SuppressWarnings("WeakerAccess") // final AdminApi adminApi; // @SuppressWarnings("WeakerAccess") // final EventBus eventBus; // // @SuppressWarnings("WeakerAccess") // final Action<ResponseZerokitError> errorResponseHandlerSdk; // @SuppressWarnings("WeakerAccess") // final Action<ResponseAdminApiError> errorResponseHandlerAdminapi; // // // @Inject // public CreateTresorViewModel(final Zerokit zerokit, final AdminApi adminApi, final EventBus eventBus) { // this.zerokit = zerokit; // this.adminApi = adminApi; // this.eventBus = eventBus; // // // this.inProgress = new ObservableField<>(false); // this.tresorId = new ObservableField<>(""); // this.clickListener = new View.OnClickListener() { // @Override // public void onClick(View v) { // createTresor(); // inProgress.set(true); // } // }; // // errorResponseHandlerSdk = new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // errorResponseHandlerAdminapi = new Action<ResponseAdminApiError>() { // @Override // public void call(ResponseAdminApiError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // } // // @SuppressWarnings("WeakerAccess") // void createTresor() { // inProgress.set(true); // this.zerokit.createTresor().enqueue(new Action<String>() { // @Override // public void call(final String tresorId) { // adminApi.createdTresor(tresorId).enqueue(new Action<Void>() { // @Override // public void call(Void res) { // CreateTresorViewModel.this.inProgress.set(false); // CreateTresorViewModel.this.tresorId.set("Tresor Id: " + tresorId); // CreateTresorViewModel.this.eventBus.post(new CreateTresorFinishedMessage(tresorId)); // } // }, errorResponseHandlerAdminapi); // } // }, errorResponseHandlerSdk); // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.component.DaggerCreateTresorComponent; import com.tresorit.zerokitsdk.databinding.FragmentCreateTresorBinding; import com.tresorit.zerokitsdk.viewmodel.CreateTresorViewModel; import javax.inject.Inject;
package com.tresorit.zerokitsdk.fragment; public class CreateTresorFragment extends Fragment { @SuppressWarnings("WeakerAccess") @Inject CreateTresorViewModel viewModel; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Path: sample/src/main/java/com/tresorit/zerokitsdk/ZerokitApplication.java // public class ZerokitApplication extends Application { // // private ApplicationComponent component; // // public static ZerokitApplication get(Context context) { // return (ZerokitApplication) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // component = DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .adminApiModule(new AdminApiModule(BuildConfig.APP_BACKEND, BuildConfig.CLIENT_ID)) // .build(); // } // // public ApplicationComponent component() { // return component; // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/CreateTresorViewModel.java // public class CreateTresorViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final View.OnClickListener clickListener; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Boolean> inProgress; // @SuppressWarnings("WeakerAccess") // public final ObservableField<String> tresorId; // // private final Zerokit zerokit; // // @SuppressWarnings("WeakerAccess") // final AdminApi adminApi; // @SuppressWarnings("WeakerAccess") // final EventBus eventBus; // // @SuppressWarnings("WeakerAccess") // final Action<ResponseZerokitError> errorResponseHandlerSdk; // @SuppressWarnings("WeakerAccess") // final Action<ResponseAdminApiError> errorResponseHandlerAdminapi; // // // @Inject // public CreateTresorViewModel(final Zerokit zerokit, final AdminApi adminApi, final EventBus eventBus) { // this.zerokit = zerokit; // this.adminApi = adminApi; // this.eventBus = eventBus; // // // this.inProgress = new ObservableField<>(false); // this.tresorId = new ObservableField<>(""); // this.clickListener = new View.OnClickListener() { // @Override // public void onClick(View v) { // createTresor(); // inProgress.set(true); // } // }; // // errorResponseHandlerSdk = new Action<ResponseZerokitError>() { // @Override // public void call(ResponseZerokitError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // errorResponseHandlerAdminapi = new Action<ResponseAdminApiError>() { // @Override // public void call(ResponseAdminApiError errorResponse) { // inProgress.set(false); // eventBus.post(new ShowMessageMessage(errorResponse.toString())); // } // }; // } // // @SuppressWarnings("WeakerAccess") // void createTresor() { // inProgress.set(true); // this.zerokit.createTresor().enqueue(new Action<String>() { // @Override // public void call(final String tresorId) { // adminApi.createdTresor(tresorId).enqueue(new Action<Void>() { // @Override // public void call(Void res) { // CreateTresorViewModel.this.inProgress.set(false); // CreateTresorViewModel.this.tresorId.set("Tresor Id: " + tresorId); // CreateTresorViewModel.this.eventBus.post(new CreateTresorFinishedMessage(tresorId)); // } // }, errorResponseHandlerAdminapi); // } // }, errorResponseHandlerSdk); // } // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/CreateTresorFragment.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.tresorit.zerokitsdk.ZerokitApplication; import com.tresorit.zerokitsdk.component.DaggerCreateTresorComponent; import com.tresorit.zerokitsdk.databinding.FragmentCreateTresorBinding; import com.tresorit.zerokitsdk.viewmodel.CreateTresorViewModel; import javax.inject.Inject; package com.tresorit.zerokitsdk.fragment; public class CreateTresorFragment extends Fragment { @SuppressWarnings("WeakerAccess") @Inject CreateTresorViewModel viewModel; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
DaggerCreateTresorComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).build().inject(this);
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/component/EncryptComponent.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptFragment.java // public class EncryptFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @SuppressWarnings("WeakerAccess") // FragmentEncryptBinding binding; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // binding = FragmentEncryptBinding.inflate(inflater, container, false); // DaggerEncryptComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).encryptModule(new EncryptModule(getChildFragmentManager())).build().inject(this); // binding.setViewmodel(viewModel); // binding.pager.setPagingEnabled(false); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(this); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(this); // } // // @Subscribe // @SuppressWarnings("unused") // public void onEvent(@SuppressWarnings("UnusedParameters") CreateTresorFinishedMessage message){ // binding.pager.setPagingEnabled(true); // binding.pager.postDelayed(new Runnable() { // @Override // public void run() { // binding.pager.setCurrentItem(1); // } // }, 500); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/EncryptModule.java // @Module // public class EncryptModule { // // private final FragmentManager fragmentManager; // // public EncryptModule(FragmentManager fragmentManager) { // this.fragmentManager = fragmentManager; // } // // @Provides // @ActivityScope // public EncryptViewModel provideEncryptViewModel(Context context) { // return new EncryptViewModel(context, fragmentManager); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/EncryptViewModel.java // public class EncryptViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final EncryptPagerAdapter pagerAdapter; // @SuppressWarnings("WeakerAccess") // public final ViewPager.OnPageChangeListener pageChangeListener; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Drawable> drawableDot1; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Drawable> drawableDot2; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Drawable> drawableDot3; // // // public EncryptViewModel(final Context context, FragmentManager fragmentManager) { // pagerAdapter = new EncryptPagerAdapter(context, fragmentManager); // pageChangeListener = new ViewPager.SimpleOnPageChangeListener() { // // @Override // public void onPageSelected(int position) { // drawableDot1.set(context.getResources().getDrawable(position == 0 ? R.drawable.selecteditem_dot : R.drawable.nonselecteditem_dot)); // drawableDot2.set(context.getResources().getDrawable(position == 1 ? R.drawable.selecteditem_dot : R.drawable.nonselecteditem_dot)); // drawableDot3.set(context.getResources().getDrawable(position == 2 ? R.drawable.selecteditem_dot : R.drawable.nonselecteditem_dot)); // } // // }; // // drawableDot1 = new ObservableField<>(context.getResources().getDrawable(R.drawable.selecteditem_dot)); // drawableDot2 = new ObservableField<>(context.getResources().getDrawable(R.drawable.nonselecteditem_dot)); // drawableDot3 = new ObservableField<>(context.getResources().getDrawable(R.drawable.nonselecteditem_dot)); // } // // // // }
import com.tresorit.zerokitsdk.fragment.EncryptFragment; import com.tresorit.zerokitsdk.module.EncryptModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import com.tresorit.zerokitsdk.viewmodel.EncryptViewModel; import dagger.Component;
package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = {
// Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptFragment.java // public class EncryptFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @SuppressWarnings("WeakerAccess") // FragmentEncryptBinding binding; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // binding = FragmentEncryptBinding.inflate(inflater, container, false); // DaggerEncryptComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).encryptModule(new EncryptModule(getChildFragmentManager())).build().inject(this); // binding.setViewmodel(viewModel); // binding.pager.setPagingEnabled(false); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(this); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(this); // } // // @Subscribe // @SuppressWarnings("unused") // public void onEvent(@SuppressWarnings("UnusedParameters") CreateTresorFinishedMessage message){ // binding.pager.setPagingEnabled(true); // binding.pager.postDelayed(new Runnable() { // @Override // public void run() { // binding.pager.setCurrentItem(1); // } // }, 500); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/EncryptModule.java // @Module // public class EncryptModule { // // private final FragmentManager fragmentManager; // // public EncryptModule(FragmentManager fragmentManager) { // this.fragmentManager = fragmentManager; // } // // @Provides // @ActivityScope // public EncryptViewModel provideEncryptViewModel(Context context) { // return new EncryptViewModel(context, fragmentManager); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/EncryptViewModel.java // public class EncryptViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final EncryptPagerAdapter pagerAdapter; // @SuppressWarnings("WeakerAccess") // public final ViewPager.OnPageChangeListener pageChangeListener; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Drawable> drawableDot1; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Drawable> drawableDot2; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Drawable> drawableDot3; // // // public EncryptViewModel(final Context context, FragmentManager fragmentManager) { // pagerAdapter = new EncryptPagerAdapter(context, fragmentManager); // pageChangeListener = new ViewPager.SimpleOnPageChangeListener() { // // @Override // public void onPageSelected(int position) { // drawableDot1.set(context.getResources().getDrawable(position == 0 ? R.drawable.selecteditem_dot : R.drawable.nonselecteditem_dot)); // drawableDot2.set(context.getResources().getDrawable(position == 1 ? R.drawable.selecteditem_dot : R.drawable.nonselecteditem_dot)); // drawableDot3.set(context.getResources().getDrawable(position == 2 ? R.drawable.selecteditem_dot : R.drawable.nonselecteditem_dot)); // } // // }; // // drawableDot1 = new ObservableField<>(context.getResources().getDrawable(R.drawable.selecteditem_dot)); // drawableDot2 = new ObservableField<>(context.getResources().getDrawable(R.drawable.nonselecteditem_dot)); // drawableDot3 = new ObservableField<>(context.getResources().getDrawable(R.drawable.nonselecteditem_dot)); // } // // // // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/component/EncryptComponent.java import com.tresorit.zerokitsdk.fragment.EncryptFragment; import com.tresorit.zerokitsdk.module.EncryptModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import com.tresorit.zerokitsdk.viewmodel.EncryptViewModel; import dagger.Component; package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = {
EncryptModule.class
tresorit/ZeroKit-Android-SDK
sample/src/main/java/com/tresorit/zerokitsdk/component/EncryptComponent.java
// Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptFragment.java // public class EncryptFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @SuppressWarnings("WeakerAccess") // FragmentEncryptBinding binding; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // binding = FragmentEncryptBinding.inflate(inflater, container, false); // DaggerEncryptComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).encryptModule(new EncryptModule(getChildFragmentManager())).build().inject(this); // binding.setViewmodel(viewModel); // binding.pager.setPagingEnabled(false); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(this); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(this); // } // // @Subscribe // @SuppressWarnings("unused") // public void onEvent(@SuppressWarnings("UnusedParameters") CreateTresorFinishedMessage message){ // binding.pager.setPagingEnabled(true); // binding.pager.postDelayed(new Runnable() { // @Override // public void run() { // binding.pager.setCurrentItem(1); // } // }, 500); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/EncryptModule.java // @Module // public class EncryptModule { // // private final FragmentManager fragmentManager; // // public EncryptModule(FragmentManager fragmentManager) { // this.fragmentManager = fragmentManager; // } // // @Provides // @ActivityScope // public EncryptViewModel provideEncryptViewModel(Context context) { // return new EncryptViewModel(context, fragmentManager); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/EncryptViewModel.java // public class EncryptViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final EncryptPagerAdapter pagerAdapter; // @SuppressWarnings("WeakerAccess") // public final ViewPager.OnPageChangeListener pageChangeListener; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Drawable> drawableDot1; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Drawable> drawableDot2; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Drawable> drawableDot3; // // // public EncryptViewModel(final Context context, FragmentManager fragmentManager) { // pagerAdapter = new EncryptPagerAdapter(context, fragmentManager); // pageChangeListener = new ViewPager.SimpleOnPageChangeListener() { // // @Override // public void onPageSelected(int position) { // drawableDot1.set(context.getResources().getDrawable(position == 0 ? R.drawable.selecteditem_dot : R.drawable.nonselecteditem_dot)); // drawableDot2.set(context.getResources().getDrawable(position == 1 ? R.drawable.selecteditem_dot : R.drawable.nonselecteditem_dot)); // drawableDot3.set(context.getResources().getDrawable(position == 2 ? R.drawable.selecteditem_dot : R.drawable.nonselecteditem_dot)); // } // // }; // // drawableDot1 = new ObservableField<>(context.getResources().getDrawable(R.drawable.selecteditem_dot)); // drawableDot2 = new ObservableField<>(context.getResources().getDrawable(R.drawable.nonselecteditem_dot)); // drawableDot3 = new ObservableField<>(context.getResources().getDrawable(R.drawable.nonselecteditem_dot)); // } // // // // }
import com.tresorit.zerokitsdk.fragment.EncryptFragment; import com.tresorit.zerokitsdk.module.EncryptModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import com.tresorit.zerokitsdk.viewmodel.EncryptViewModel; import dagger.Component;
package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = { EncryptModule.class }, dependencies = { ApplicationComponent.class } ) public interface EncryptComponent {
// Path: sample/src/main/java/com/tresorit/zerokitsdk/fragment/EncryptFragment.java // public class EncryptFragment extends Fragment { // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EncryptViewModel viewModel; // // @SuppressWarnings({"WeakerAccess", "CanBeFinal"}) // @Inject // EventBus eventBus; // // @SuppressWarnings("WeakerAccess") // FragmentEncryptBinding binding; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // binding = FragmentEncryptBinding.inflate(inflater, container, false); // DaggerEncryptComponent.builder().applicationComponent(ZerokitApplication.get(getActivity()).component()).encryptModule(new EncryptModule(getChildFragmentManager())).build().inject(this); // binding.setViewmodel(viewModel); // binding.pager.setPagingEnabled(false); // return binding.getRoot(); // } // // @Override // public void onStart() { // super.onStart(); // eventBus.register(this); // } // // @Override // public void onStop() { // super.onStop(); // eventBus.unregister(this); // } // // @Subscribe // @SuppressWarnings("unused") // public void onEvent(@SuppressWarnings("UnusedParameters") CreateTresorFinishedMessage message){ // binding.pager.setPagingEnabled(true); // binding.pager.postDelayed(new Runnable() { // @Override // public void run() { // binding.pager.setCurrentItem(1); // } // }, 500); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/module/EncryptModule.java // @Module // public class EncryptModule { // // private final FragmentManager fragmentManager; // // public EncryptModule(FragmentManager fragmentManager) { // this.fragmentManager = fragmentManager; // } // // @Provides // @ActivityScope // public EncryptViewModel provideEncryptViewModel(Context context) { // return new EncryptViewModel(context, fragmentManager); // } // } // // Path: sample/src/main/java/com/tresorit/zerokitsdk/viewmodel/EncryptViewModel.java // public class EncryptViewModel extends BaseObservable { // // @SuppressWarnings("WeakerAccess") // public final EncryptPagerAdapter pagerAdapter; // @SuppressWarnings("WeakerAccess") // public final ViewPager.OnPageChangeListener pageChangeListener; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Drawable> drawableDot1; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Drawable> drawableDot2; // @SuppressWarnings("WeakerAccess") // public final ObservableField<Drawable> drawableDot3; // // // public EncryptViewModel(final Context context, FragmentManager fragmentManager) { // pagerAdapter = new EncryptPagerAdapter(context, fragmentManager); // pageChangeListener = new ViewPager.SimpleOnPageChangeListener() { // // @Override // public void onPageSelected(int position) { // drawableDot1.set(context.getResources().getDrawable(position == 0 ? R.drawable.selecteditem_dot : R.drawable.nonselecteditem_dot)); // drawableDot2.set(context.getResources().getDrawable(position == 1 ? R.drawable.selecteditem_dot : R.drawable.nonselecteditem_dot)); // drawableDot3.set(context.getResources().getDrawable(position == 2 ? R.drawable.selecteditem_dot : R.drawable.nonselecteditem_dot)); // } // // }; // // drawableDot1 = new ObservableField<>(context.getResources().getDrawable(R.drawable.selecteditem_dot)); // drawableDot2 = new ObservableField<>(context.getResources().getDrawable(R.drawable.nonselecteditem_dot)); // drawableDot3 = new ObservableField<>(context.getResources().getDrawable(R.drawable.nonselecteditem_dot)); // } // // // // } // Path: sample/src/main/java/com/tresorit/zerokitsdk/component/EncryptComponent.java import com.tresorit.zerokitsdk.fragment.EncryptFragment; import com.tresorit.zerokitsdk.module.EncryptModule; import com.tresorit.zerokitsdk.scopes.ActivityScope; import com.tresorit.zerokitsdk.viewmodel.EncryptViewModel; import dagger.Component; package com.tresorit.zerokitsdk.component; @ActivityScope @Component( modules = { EncryptModule.class }, dependencies = { ApplicationComponent.class } ) public interface EncryptComponent {
void inject(EncryptFragment fragment);