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 |
|---|---|---|---|---|---|---|
edmcouncil/rdf-toolkit | src/main/java/org/edmcouncil/rdf_toolkit/model/SortedTurtleResourceList.java | // Path: src/main/java/org/edmcouncil/rdf_toolkit/comparator/ComparisonContext.java
// public class ComparisonContext {
//
// private final boolean shouldInlineBlankNodes;
// private final UnsortedTurtleSubjectPredicateObjectMap unsortedTripleMap;
//
// public ComparisonContext(boolean shouldInlineBlankNodesX, UnsortedTurtleSubjectPredicateObjectMap unsortedTripleMap) {
// this.shouldInlineBlankNodes = shouldInlineBlankNodesX;
// this.unsortedTripleMap = unsortedTripleMap;
// }
//
// public boolean getShouldInlineBlankNodes() {
// return shouldInlineBlankNodes;
// }
//
// public UnsortedTurtleSubjectPredicateObjectMap getUnsortedTripleMap() {
// return unsortedTripleMap;
// }
// }
//
// Path: src/main/java/org/edmcouncil/rdf_toolkit/comparator/ResourceComparator.java
// public class ResourceComparator implements Comparator<Resource> {
//
// private final BNodeComparator blankNodeComparator;
// private final IRIComparator iriComparator = new IRIComparator();
// private Class<Value> collectionClass = Value.class;
//
// public ResourceComparator(ComparisonContext comparisonContext) {
// this.blankNodeComparator = new BNodeComparator(collectionClass, comparisonContext);
// }
//
// public ResourceComparator(Class<Value> collectionClass, ComparisonContext comparisonContext) {
// this(comparisonContext);
// this.collectionClass = collectionClass;
// }
//
// @Override
// public int compare(Resource resource1, Resource resource2) {
// return compare(resource1, resource2, new ArrayList<>());
// }
//
// private int compare(Resource resource1, Resource resource2, List<Object> excludedList) {
// if (resource1 == resource2) {
// return 0;
// }
//
// if ((resource1 == null) || excludedList.contains(resource1)) {
// if ((resource2 == null) || excludedList.contains(resource2)) {
// return 0; // two null/excluded resources are equal
// } else {
// return -1; // null/excluded resource comes before non-null/excluded resource
// }
// } else {
// if ((resource2 == null) || excludedList.contains(resource2)) {
// return 1; // non-null/excluded resource comes before null/excluded resource
// } else {
// // Order blank nodes so that they come after other values.
// if (resource1 instanceof BNode) {
// if (resource2 instanceof BNode) {
// int cmp = blankNodeComparator.compare((BNode) resource1, (BNode) resource2, excludedList);
// if (cmp != 0) {
// return cmp;
// } else {
// // to make sure that the sorted blank node list doesn't exclude a blank node just because it has the
// // same content as another
// return resource1.stringValue().compareTo(resource2.stringValue());
// }
// } else {
// return 1; // blank node resource1 comes after resource2 (which is not a blank node).
// }
// } else {
// if (resource2 instanceof BNode) {
// return -1; // resource1 (which is not a blank node) comes before blank node resource2.
// } else { // compare non-blank-node resources.
// if ((resource1 instanceof IRI) && (resource2 instanceof IRI)) { // compare IRIs
// return iriComparator.compare((IRI) resource1, (IRI) resource2, excludedList);
// } else {
// return resource1.stringValue().compareTo(resource2.stringValue());
// }
// }
// }
// }
// }
// }
// }
| import org.eclipse.rdf4j.model.Resource;
import org.edmcouncil.rdf_toolkit.comparator.ComparisonContext;
import org.edmcouncil.rdf_toolkit.comparator.ResourceComparator;
import java.util.TreeSet; | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Enterprise Data Management Council
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.edmcouncil.rdf_toolkit.model;
/**
* A sorted list of RDF resource values.
*/
public class SortedTurtleResourceList extends TreeSet<Resource> {
public SortedTurtleResourceList(Class collectionClass, ComparisonContext comparisonContext) { // TODO | // Path: src/main/java/org/edmcouncil/rdf_toolkit/comparator/ComparisonContext.java
// public class ComparisonContext {
//
// private final boolean shouldInlineBlankNodes;
// private final UnsortedTurtleSubjectPredicateObjectMap unsortedTripleMap;
//
// public ComparisonContext(boolean shouldInlineBlankNodesX, UnsortedTurtleSubjectPredicateObjectMap unsortedTripleMap) {
// this.shouldInlineBlankNodes = shouldInlineBlankNodesX;
// this.unsortedTripleMap = unsortedTripleMap;
// }
//
// public boolean getShouldInlineBlankNodes() {
// return shouldInlineBlankNodes;
// }
//
// public UnsortedTurtleSubjectPredicateObjectMap getUnsortedTripleMap() {
// return unsortedTripleMap;
// }
// }
//
// Path: src/main/java/org/edmcouncil/rdf_toolkit/comparator/ResourceComparator.java
// public class ResourceComparator implements Comparator<Resource> {
//
// private final BNodeComparator blankNodeComparator;
// private final IRIComparator iriComparator = new IRIComparator();
// private Class<Value> collectionClass = Value.class;
//
// public ResourceComparator(ComparisonContext comparisonContext) {
// this.blankNodeComparator = new BNodeComparator(collectionClass, comparisonContext);
// }
//
// public ResourceComparator(Class<Value> collectionClass, ComparisonContext comparisonContext) {
// this(comparisonContext);
// this.collectionClass = collectionClass;
// }
//
// @Override
// public int compare(Resource resource1, Resource resource2) {
// return compare(resource1, resource2, new ArrayList<>());
// }
//
// private int compare(Resource resource1, Resource resource2, List<Object> excludedList) {
// if (resource1 == resource2) {
// return 0;
// }
//
// if ((resource1 == null) || excludedList.contains(resource1)) {
// if ((resource2 == null) || excludedList.contains(resource2)) {
// return 0; // two null/excluded resources are equal
// } else {
// return -1; // null/excluded resource comes before non-null/excluded resource
// }
// } else {
// if ((resource2 == null) || excludedList.contains(resource2)) {
// return 1; // non-null/excluded resource comes before null/excluded resource
// } else {
// // Order blank nodes so that they come after other values.
// if (resource1 instanceof BNode) {
// if (resource2 instanceof BNode) {
// int cmp = blankNodeComparator.compare((BNode) resource1, (BNode) resource2, excludedList);
// if (cmp != 0) {
// return cmp;
// } else {
// // to make sure that the sorted blank node list doesn't exclude a blank node just because it has the
// // same content as another
// return resource1.stringValue().compareTo(resource2.stringValue());
// }
// } else {
// return 1; // blank node resource1 comes after resource2 (which is not a blank node).
// }
// } else {
// if (resource2 instanceof BNode) {
// return -1; // resource1 (which is not a blank node) comes before blank node resource2.
// } else { // compare non-blank-node resources.
// if ((resource1 instanceof IRI) && (resource2 instanceof IRI)) { // compare IRIs
// return iriComparator.compare((IRI) resource1, (IRI) resource2, excludedList);
// } else {
// return resource1.stringValue().compareTo(resource2.stringValue());
// }
// }
// }
// }
// }
// }
// }
// Path: src/main/java/org/edmcouncil/rdf_toolkit/model/SortedTurtleResourceList.java
import org.eclipse.rdf4j.model.Resource;
import org.edmcouncil.rdf_toolkit.comparator.ComparisonContext;
import org.edmcouncil.rdf_toolkit.comparator.ResourceComparator;
import java.util.TreeSet;
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Enterprise Data Management Council
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.edmcouncil.rdf_toolkit.model;
/**
* A sorted list of RDF resource values.
*/
public class SortedTurtleResourceList extends TreeSet<Resource> {
public SortedTurtleResourceList(Class collectionClass, ComparisonContext comparisonContext) { // TODO | super(new ResourceComparator(collectionClass, comparisonContext)); |
edmcouncil/rdf-toolkit | src/main/java/org/edmcouncil/rdf_toolkit/comparator/TurtlePredicateObjectMapComparator.java | // Path: src/main/java/org/edmcouncil/rdf_toolkit/model/SortedTurtleObjectList.java
// public class SortedTurtleObjectList extends TreeSet<Value> {
//
// public SortedTurtleObjectList(ComparisonContext comparisonContext) {
// super(new ValueComparator(comparisonContext));
// }
//
// public SortedTurtleObjectList(Class<Value> collectionClass,
// ComparisonContext comparisonContext) {
// super(new ValueComparator(collectionClass, comparisonContext));
// }
// }
//
// Path: src/main/java/org/edmcouncil/rdf_toolkit/model/SortedTurtlePredicateObjectMap.java
// public class SortedTurtlePredicateObjectMap extends SortedHashMap<IRI, SortedTurtleObjectList> {
//
// public SortedTurtlePredicateObjectMap() {
// super(new IRIComparator());
// }
//
// public int fullSize() {
// int result = 0;
// for (Resource pred : keySet()) {
// result += get(pred).size();
// }
// return result;
// }
// }
| import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.eclipse.rdf4j.model.BNode;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Value;
import org.edmcouncil.rdf_toolkit.model.SortedTurtleObjectList;
import org.edmcouncil.rdf_toolkit.model.SortedTurtlePredicateObjectMap;
import java.util.ArrayList; | if ((map1 == null) || excludedList.contains(map1)) {
if ((map2 == null) || excludedList.contains(map2)) {
return 0; // two null/excluded maps are equal
} else {
return -1; // null/excluded map comes before non-null/excluded map
}
} else {
if ((map2 == null) || excludedList.contains(map2)) {
return 1; // non-null/excluded map comes before null/excluded map
} else {
Iterator<IRI> iter1 = map1.sortedKeys().iterator();
Iterator<IRI> iter2 = map2.sortedKeys().iterator();
return compare(map1, iter1, map2, iter2, excludedList);
}
}
}
private int compare(SortedTurtlePredicateObjectMap map1, Iterator<IRI> iter1,
SortedTurtlePredicateObjectMap map2, Iterator<IRI> iter2,
List<Object> excludedList) {
if (iter1.hasNext()) {
if (iter2.hasNext()) {
IRI key1 = iter1.next();
IRI key2 = iter2.next();
excludedList.add(map1);
excludedList.add(map2);
int cmp = iriComparator.compare(key1, key2, excludedList);
if (cmp != 0) {
return cmp;
} else { // predicate keys are the same, so test object values | // Path: src/main/java/org/edmcouncil/rdf_toolkit/model/SortedTurtleObjectList.java
// public class SortedTurtleObjectList extends TreeSet<Value> {
//
// public SortedTurtleObjectList(ComparisonContext comparisonContext) {
// super(new ValueComparator(comparisonContext));
// }
//
// public SortedTurtleObjectList(Class<Value> collectionClass,
// ComparisonContext comparisonContext) {
// super(new ValueComparator(collectionClass, comparisonContext));
// }
// }
//
// Path: src/main/java/org/edmcouncil/rdf_toolkit/model/SortedTurtlePredicateObjectMap.java
// public class SortedTurtlePredicateObjectMap extends SortedHashMap<IRI, SortedTurtleObjectList> {
//
// public SortedTurtlePredicateObjectMap() {
// super(new IRIComparator());
// }
//
// public int fullSize() {
// int result = 0;
// for (Resource pred : keySet()) {
// result += get(pred).size();
// }
// return result;
// }
// }
// Path: src/main/java/org/edmcouncil/rdf_toolkit/comparator/TurtlePredicateObjectMapComparator.java
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.eclipse.rdf4j.model.BNode;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Value;
import org.edmcouncil.rdf_toolkit.model.SortedTurtleObjectList;
import org.edmcouncil.rdf_toolkit.model.SortedTurtlePredicateObjectMap;
import java.util.ArrayList;
if ((map1 == null) || excludedList.contains(map1)) {
if ((map2 == null) || excludedList.contains(map2)) {
return 0; // two null/excluded maps are equal
} else {
return -1; // null/excluded map comes before non-null/excluded map
}
} else {
if ((map2 == null) || excludedList.contains(map2)) {
return 1; // non-null/excluded map comes before null/excluded map
} else {
Iterator<IRI> iter1 = map1.sortedKeys().iterator();
Iterator<IRI> iter2 = map2.sortedKeys().iterator();
return compare(map1, iter1, map2, iter2, excludedList);
}
}
}
private int compare(SortedTurtlePredicateObjectMap map1, Iterator<IRI> iter1,
SortedTurtlePredicateObjectMap map2, Iterator<IRI> iter2,
List<Object> excludedList) {
if (iter1.hasNext()) {
if (iter2.hasNext()) {
IRI key1 = iter1.next();
IRI key2 = iter2.next();
excludedList.add(map1);
excludedList.add(map2);
int cmp = iriComparator.compare(key1, key2, excludedList);
if (cmp != 0) {
return cmp;
} else { // predicate keys are the same, so test object values | SortedTurtleObjectList values1 = map1.get(key1); |
edmcouncil/rdf-toolkit | src/test/java/org/edmcouncil/rdf_toolkit/comparator/ComparisonUtilsTest.java | // Path: src/main/java/org/edmcouncil/rdf_toolkit/comparator/ComparisonUtils.java
// public static boolean isCollection(ComparisonContext comparisonContext,
// BNode bnode,
// Class<Value> collectionClass) {
// var unsortedTripleMap = comparisonContext.getUnsortedTripleMap();
// var poMap = unsortedTripleMap.getSorted(bnode, collectionClass, comparisonContext);
// if (poMap != null) {
// Set<IRI> predicates = poMap.keySet();
// int firstCount = predicates.contains(Constants.rdfFirst) ? 1 : 0;
// int restCount = predicates.contains(Constants.rdfRest) ? 1 : 0;
// int typeCount = predicates.contains(Constants.RDF_TYPE) ? 1 : 0;
// if (predicates.size() == firstCount + restCount + typeCount) {
// SortedTurtleObjectList firstValues = poMap.get(Constants.rdfFirst);
// for (Value value : firstValues) {
// // all collection members must match the collection class type
// if (!collectionClass.isInstance(value)) { return false; }
// }
// if (restCount >= 1) {
// SortedTurtleObjectList rest = poMap.get(Constants.rdfRest);
// if (rest.size() == 1) {
// for (Value value : rest) {
// if (Constants.rdfNil.equals(value)) {
// return true;
// }
// if (value instanceof BNode) {
// return isCollection(comparisonContext, (BNode) value, collectionClass);
// }
// }
// }
// }
// }
// }
// return false;
// }
| import org.eclipse.rdf4j.model.Value;
import org.eclipse.rdf4j.model.ValueFactory;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.model.util.ModelBuilder;
import org.eclipse.rdf4j.model.util.RDFCollections;
import org.eclipse.rdf4j.model.vocabulary.FOAF;
import org.eclipse.rdf4j.model.vocabulary.RDF;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.edmcouncil.rdf_toolkit.comparator.ComparisonUtils.isCollection;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.eclipse.rdf4j.model.BNode;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Model; | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Enterprise Data Management Council
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.edmcouncil.rdf_toolkit.comparator;
class ComparisonUtilsTest extends AbstractComparatorTest {
@Test
void shouldReturnFalseWhenBlankNodeDoesNotRepresentCollection() {
var valueFactory = SimpleValueFactory.getInstance();
var model = prepareModel(valueFactory);
| // Path: src/main/java/org/edmcouncil/rdf_toolkit/comparator/ComparisonUtils.java
// public static boolean isCollection(ComparisonContext comparisonContext,
// BNode bnode,
// Class<Value> collectionClass) {
// var unsortedTripleMap = comparisonContext.getUnsortedTripleMap();
// var poMap = unsortedTripleMap.getSorted(bnode, collectionClass, comparisonContext);
// if (poMap != null) {
// Set<IRI> predicates = poMap.keySet();
// int firstCount = predicates.contains(Constants.rdfFirst) ? 1 : 0;
// int restCount = predicates.contains(Constants.rdfRest) ? 1 : 0;
// int typeCount = predicates.contains(Constants.RDF_TYPE) ? 1 : 0;
// if (predicates.size() == firstCount + restCount + typeCount) {
// SortedTurtleObjectList firstValues = poMap.get(Constants.rdfFirst);
// for (Value value : firstValues) {
// // all collection members must match the collection class type
// if (!collectionClass.isInstance(value)) { return false; }
// }
// if (restCount >= 1) {
// SortedTurtleObjectList rest = poMap.get(Constants.rdfRest);
// if (rest.size() == 1) {
// for (Value value : rest) {
// if (Constants.rdfNil.equals(value)) {
// return true;
// }
// if (value instanceof BNode) {
// return isCollection(comparisonContext, (BNode) value, collectionClass);
// }
// }
// }
// }
// }
// }
// return false;
// }
// Path: src/test/java/org/edmcouncil/rdf_toolkit/comparator/ComparisonUtilsTest.java
import org.eclipse.rdf4j.model.Value;
import org.eclipse.rdf4j.model.ValueFactory;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.model.util.ModelBuilder;
import org.eclipse.rdf4j.model.util.RDFCollections;
import org.eclipse.rdf4j.model.vocabulary.FOAF;
import org.eclipse.rdf4j.model.vocabulary.RDF;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.edmcouncil.rdf_toolkit.comparator.ComparisonUtils.isCollection;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.eclipse.rdf4j.model.BNode;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Model;
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Enterprise Data Management Council
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.edmcouncil.rdf_toolkit.comparator;
class ComparisonUtilsTest extends AbstractComparatorTest {
@Test
void shouldReturnFalseWhenBlankNodeDoesNotRepresentCollection() {
var valueFactory = SimpleValueFactory.getInstance();
var model = prepareModel(valueFactory);
| var actualResult = isCollection( |
edmcouncil/rdf-toolkit | src/main/java/org/edmcouncil/rdf_toolkit/comparator/ValueComparator.java | // Path: src/main/java/org/edmcouncil/rdf_toolkit/comparator/ComparisonUtils.java
// public static int compareSimpleValue(Literal literal1, Literal literal2) {
// // TODO: support natural ordering of non-string literals
// int cmp = literal1.stringValue().compareTo(literal2.stringValue());
// if (cmp != 0) {
// return cmp;
// } else {
// if (literal1.getLanguage().isPresent()) {
// if (literal2.getLanguage().isPresent()) {
// int cmp2 = literal1.getLanguage().toString().compareTo(literal2.getLanguage().toString());
// if (cmp2 != 0) {
// return cmp2;
// }
// } else { // !literal2.getLanguage().isPresent()
// return -1; // literal1 with language comes before literal2 without language
// }
// } else { // !literal1.getLanguage().isPresent()
// if (literal2.getLanguage().isPresent()) {
// return 1; // literal1 without language comes after literal2 with language
// } else { // !literal2.getLanguage().isPresent()
// // neither literal has a language to compare
// }
// }
// if (literal1.getDatatype() != null) {
// if (literal2.getDatatype() != null) {
// int cmp2 = literal1.getDatatype().stringValue().compareTo(literal2.getDatatype().stringValue());
// if (cmp2 != 0) {
// return cmp2;
// }
// } else { // literal2.getDatatype() == null
// return -1; // literal1 with data type comes before literal2 without data type
// }
// } else { // literal1.getDatatype() == null
// if (literal2.getDatatype() != null) {
// return 1; // literal1 without data type comes after literal2 with data type
// } else { // literal2.getDatatype().isPresent() == null
// // neither literal has a data type to compare
// }
// }
// return 0; // no difference in value, language nor datatype
// }
// }
| import java.util.List;
import static org.edmcouncil.rdf_toolkit.comparator.ComparisonUtils.compareSimpleValue;
import org.eclipse.rdf4j.model.BNode;
import org.eclipse.rdf4j.model.Literal;
import org.eclipse.rdf4j.model.Value;
import java.util.ArrayList;
import java.util.Comparator; | } else {
return -1; // null/excluded value comes before non-null/excluded value
}
} else {
if ((value2 == null) || excludedList.contains(value2)) {
return 1; // non-null/excluded value comes before null/excluded value
}
}
return compareExistingValues(value1, value2, excludedList);
}
public int compareExistingValues(Value value1, Value value2, List<Object> excludedList) {
// We assume here that both blank nodes are non-null/excluded
if (value1 == null || value2 == null || excludedList.contains(value1) || excludedList.contains(value2)) {
throw new IllegalStateException("value1 and value2 should not be null or in the excluded list.");
}
// Order blank nodes so that they come after other values.
if (value1 instanceof BNode) {
if (value2 instanceof BNode) {
return compareTwoBlankNodes((BNode) value1, (BNode) value2, excludedList);
} else {
return 1; // blank node value1 comes after value2.
}
} else {
if (value2 instanceof BNode) {
return -1; // value1 comes before blank node value2.
} else { // compare non-blank-node values.
if ((value1 instanceof Literal) && (value2 instanceof Literal)) { | // Path: src/main/java/org/edmcouncil/rdf_toolkit/comparator/ComparisonUtils.java
// public static int compareSimpleValue(Literal literal1, Literal literal2) {
// // TODO: support natural ordering of non-string literals
// int cmp = literal1.stringValue().compareTo(literal2.stringValue());
// if (cmp != 0) {
// return cmp;
// } else {
// if (literal1.getLanguage().isPresent()) {
// if (literal2.getLanguage().isPresent()) {
// int cmp2 = literal1.getLanguage().toString().compareTo(literal2.getLanguage().toString());
// if (cmp2 != 0) {
// return cmp2;
// }
// } else { // !literal2.getLanguage().isPresent()
// return -1; // literal1 with language comes before literal2 without language
// }
// } else { // !literal1.getLanguage().isPresent()
// if (literal2.getLanguage().isPresent()) {
// return 1; // literal1 without language comes after literal2 with language
// } else { // !literal2.getLanguage().isPresent()
// // neither literal has a language to compare
// }
// }
// if (literal1.getDatatype() != null) {
// if (literal2.getDatatype() != null) {
// int cmp2 = literal1.getDatatype().stringValue().compareTo(literal2.getDatatype().stringValue());
// if (cmp2 != 0) {
// return cmp2;
// }
// } else { // literal2.getDatatype() == null
// return -1; // literal1 with data type comes before literal2 without data type
// }
// } else { // literal1.getDatatype() == null
// if (literal2.getDatatype() != null) {
// return 1; // literal1 without data type comes after literal2 with data type
// } else { // literal2.getDatatype().isPresent() == null
// // neither literal has a data type to compare
// }
// }
// return 0; // no difference in value, language nor datatype
// }
// }
// Path: src/main/java/org/edmcouncil/rdf_toolkit/comparator/ValueComparator.java
import java.util.List;
import static org.edmcouncil.rdf_toolkit.comparator.ComparisonUtils.compareSimpleValue;
import org.eclipse.rdf4j.model.BNode;
import org.eclipse.rdf4j.model.Literal;
import org.eclipse.rdf4j.model.Value;
import java.util.ArrayList;
import java.util.Comparator;
} else {
return -1; // null/excluded value comes before non-null/excluded value
}
} else {
if ((value2 == null) || excludedList.contains(value2)) {
return 1; // non-null/excluded value comes before null/excluded value
}
}
return compareExistingValues(value1, value2, excludedList);
}
public int compareExistingValues(Value value1, Value value2, List<Object> excludedList) {
// We assume here that both blank nodes are non-null/excluded
if (value1 == null || value2 == null || excludedList.contains(value1) || excludedList.contains(value2)) {
throw new IllegalStateException("value1 and value2 should not be null or in the excluded list.");
}
// Order blank nodes so that they come after other values.
if (value1 instanceof BNode) {
if (value2 instanceof BNode) {
return compareTwoBlankNodes((BNode) value1, (BNode) value2, excludedList);
} else {
return 1; // blank node value1 comes after value2.
}
} else {
if (value2 instanceof BNode) {
return -1; // value1 comes before blank node value2.
} else { // compare non-blank-node values.
if ((value1 instanceof Literal) && (value2 instanceof Literal)) { | return compareSimpleValue((Literal) value1, (Literal) value2); |
edmcouncil/rdf-toolkit | src/main/java/org/edmcouncil/rdf_toolkit/model/UnsortedTurtleSubjectPredicateObjectMap.java | // Path: src/main/java/org/edmcouncil/rdf_toolkit/comparator/ComparisonContext.java
// public class ComparisonContext {
//
// private final boolean shouldInlineBlankNodes;
// private final UnsortedTurtleSubjectPredicateObjectMap unsortedTripleMap;
//
// public ComparisonContext(boolean shouldInlineBlankNodesX, UnsortedTurtleSubjectPredicateObjectMap unsortedTripleMap) {
// this.shouldInlineBlankNodes = shouldInlineBlankNodesX;
// this.unsortedTripleMap = unsortedTripleMap;
// }
//
// public boolean getShouldInlineBlankNodes() {
// return shouldInlineBlankNodes;
// }
//
// public UnsortedTurtleSubjectPredicateObjectMap getUnsortedTripleMap() {
// return unsortedTripleMap;
// }
// }
| import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.model.Value;
import org.edmcouncil.rdf_toolkit.comparator.ComparisonContext;
import java.util.HashMap; | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Enterprise Data Management Council
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.edmcouncil.rdf_toolkit.model;
/**
* An unsorted map from subject resources to predicate/object pairs.
*/
public class UnsortedTurtleSubjectPredicateObjectMap extends HashMap<Resource, UnsortedTurtlePredicateObjectMap> {
public SortedTurtlePredicateObjectMap getSorted(Resource subject,
Class<Value> collectionClass, | // Path: src/main/java/org/edmcouncil/rdf_toolkit/comparator/ComparisonContext.java
// public class ComparisonContext {
//
// private final boolean shouldInlineBlankNodes;
// private final UnsortedTurtleSubjectPredicateObjectMap unsortedTripleMap;
//
// public ComparisonContext(boolean shouldInlineBlankNodesX, UnsortedTurtleSubjectPredicateObjectMap unsortedTripleMap) {
// this.shouldInlineBlankNodes = shouldInlineBlankNodesX;
// this.unsortedTripleMap = unsortedTripleMap;
// }
//
// public boolean getShouldInlineBlankNodes() {
// return shouldInlineBlankNodes;
// }
//
// public UnsortedTurtleSubjectPredicateObjectMap getUnsortedTripleMap() {
// return unsortedTripleMap;
// }
// }
// Path: src/main/java/org/edmcouncil/rdf_toolkit/model/UnsortedTurtleSubjectPredicateObjectMap.java
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.model.Value;
import org.edmcouncil.rdf_toolkit.comparator.ComparisonContext;
import java.util.HashMap;
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Enterprise Data Management Council
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.edmcouncil.rdf_toolkit.model;
/**
* An unsorted map from subject resources to predicate/object pairs.
*/
public class UnsortedTurtleSubjectPredicateObjectMap extends HashMap<Resource, UnsortedTurtlePredicateObjectMap> {
public SortedTurtlePredicateObjectMap getSorted(Resource subject,
Class<Value> collectionClass, | ComparisonContext comparisonContext) { |
edmcouncil/rdf-toolkit | src/main/java/org/edmcouncil/rdf_toolkit/model/SortedTurtlePredicateObjectMap.java | // Path: src/main/java/org/edmcouncil/rdf_toolkit/comparator/IRIComparator.java
// public class IRIComparator implements Comparator<IRI> {
//
// @Override
// public int compare(IRI iri1, IRI iri2) {
// return compare(iri1, iri2, new ArrayList<>());
// }
//
// public int compare(IRI iri1, IRI iri2, List<Object> excludedList) {
// if ((iri1 == null) || excludedList.contains(iri1)) {
// if ((iri2 == null) || excludedList.contains(iri2)) {
// return 0; // two null/excluded IRIs are equal
// } else {
// return -1; // null/excluded IRI comes before non-null/excluded IRI
// }
// } else {
// if ((iri2 == null) || excludedList.contains(iri2)) {
// return 1; // non-null/excluded IRI comes before null/excluded IRI
// } else {
// if (iri1 == iri2) {
// return 0;
// } else {
// return iri1.stringValue().compareTo(iri2.stringValue());
// }
// }
// }
// }
// }
| import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Resource;
import org.edmcouncil.rdf_toolkit.comparator.IRIComparator; | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Enterprise Data Management Council
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.edmcouncil.rdf_toolkit.model;
/**
* A sorted map from predicate IRIs to lists of object values.
*/
public class SortedTurtlePredicateObjectMap extends SortedHashMap<IRI, SortedTurtleObjectList> {
public SortedTurtlePredicateObjectMap() { | // Path: src/main/java/org/edmcouncil/rdf_toolkit/comparator/IRIComparator.java
// public class IRIComparator implements Comparator<IRI> {
//
// @Override
// public int compare(IRI iri1, IRI iri2) {
// return compare(iri1, iri2, new ArrayList<>());
// }
//
// public int compare(IRI iri1, IRI iri2, List<Object> excludedList) {
// if ((iri1 == null) || excludedList.contains(iri1)) {
// if ((iri2 == null) || excludedList.contains(iri2)) {
// return 0; // two null/excluded IRIs are equal
// } else {
// return -1; // null/excluded IRI comes before non-null/excluded IRI
// }
// } else {
// if ((iri2 == null) || excludedList.contains(iri2)) {
// return 1; // non-null/excluded IRI comes before null/excluded IRI
// } else {
// if (iri1 == iri2) {
// return 0;
// } else {
// return iri1.stringValue().compareTo(iri2.stringValue());
// }
// }
// }
// }
// }
// Path: src/main/java/org/edmcouncil/rdf_toolkit/model/SortedTurtlePredicateObjectMap.java
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Resource;
import org.edmcouncil.rdf_toolkit.comparator.IRIComparator;
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Enterprise Data Management Council
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.edmcouncil.rdf_toolkit.model;
/**
* A sorted map from predicate IRIs to lists of object values.
*/
public class SortedTurtlePredicateObjectMap extends SortedHashMap<IRI, SortedTurtleObjectList> {
public SortedTurtlePredicateObjectMap() { | super(new IRIComparator()); |
KyleCe/ScreenLocker2 | app/src/main/java/com/ce/game/screenlocker/view/RippleView.java | // Path: app/src/main/java/com/ce/game/screenlocker/inter/RippleAnimationListener.java
// public interface RippleAnimationListener {
//
// /**
// * Allow to listen to the end of the ripple animation
// */
// void onRippleAnimationEnd();
// }
| import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ListView;
import android.widget.RelativeLayout;
import com.ce.game.screenlocker.R;
import com.ce.game.screenlocker.inter.RippleAnimationListener; | package com.ce.game.screenlocker.view;
/**
* Created by KyleCe on 2016/5/25.
*
* @author: KyleCe
*/
public class RippleView extends RelativeLayout {
private static final String TAG = RippleView.class.getSimpleName();
private int WIDTH;
private int HEIGHT;
private int FRAME_RATE = 10;
private int DURATION = 400;
private int PAINT_ALPHA = 90;
private Handler canvasHandler;
private float radiusMax = 0;
private boolean animationRunning = false;
private int timer = 0;
private float x = -1;
private float y = -1;
private Boolean isCentered;
private Integer rippleType;
private Paint paint;
private Bitmap originBitmap;
private int rippleColor;
private int ripplePadding;
private GestureDetector gestureDetector; | // Path: app/src/main/java/com/ce/game/screenlocker/inter/RippleAnimationListener.java
// public interface RippleAnimationListener {
//
// /**
// * Allow to listen to the end of the ripple animation
// */
// void onRippleAnimationEnd();
// }
// Path: app/src/main/java/com/ce/game/screenlocker/view/RippleView.java
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ListView;
import android.widget.RelativeLayout;
import com.ce.game.screenlocker.R;
import com.ce.game.screenlocker.inter.RippleAnimationListener;
package com.ce.game.screenlocker.view;
/**
* Created by KyleCe on 2016/5/25.
*
* @author: KyleCe
*/
public class RippleView extends RelativeLayout {
private static final String TAG = RippleView.class.getSimpleName();
private int WIDTH;
private int HEIGHT;
private int FRAME_RATE = 10;
private int DURATION = 400;
private int PAINT_ALPHA = 90;
private Handler canvasHandler;
private float radiusMax = 0;
private boolean animationRunning = false;
private int timer = 0;
private float x = -1;
private float y = -1;
private Boolean isCentered;
private Integer rippleType;
private Paint paint;
private Bitmap originBitmap;
private int rippleColor;
private int ripplePadding;
private GestureDetector gestureDetector; | private RippleAnimationListener mAnimationListener; |
KyleCe/ScreenLocker2 | app/src/main/java/com/ce/game/screenlocker/view/KeyboardView.java | // Path: app/src/main/java/com/ce/game/screenlocker/inter/Clickable.java
// public interface Clickable {
// boolean clickable();
// }
//
// Path: app/src/main/java/com/ce/game/screenlocker/inter/KeyboardButtonClickedListener.java
// public interface KeyboardButtonClickedListener {
//
// /**
// * Receive the click of a button, just after a {@link android.view.View.OnClickListener} has fired.
// * Called before {@link #onRippleAnimationEnd()}.
// * @param keyboardButtonEnum The organized enum of the clicked button
// */
// void onKeyboardClick(@KeyboardButtonView.KeyType int keyboardButtonEnum);
//
// /**
// */
// void onRippleAnimationEnd();
//
// }
| import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
import com.ce.game.screenlocker.R;
import com.ce.game.screenlocker.inter.Clickable;
import com.ce.game.screenlocker.inter.KeyboardButtonClickedListener;
import com.ce.game.screenlocker.view.KeyboardButtonView.KeyType;
import java.util.ArrayList;
import java.util.List; | package com.ce.game.screenlocker.view;
/**
* Created by KyleCe on 2016/5/25.
*
* @author: KyleCe
*/
public class KeyboardView extends RelativeLayout implements View.OnClickListener {
private Context mContext; | // Path: app/src/main/java/com/ce/game/screenlocker/inter/Clickable.java
// public interface Clickable {
// boolean clickable();
// }
//
// Path: app/src/main/java/com/ce/game/screenlocker/inter/KeyboardButtonClickedListener.java
// public interface KeyboardButtonClickedListener {
//
// /**
// * Receive the click of a button, just after a {@link android.view.View.OnClickListener} has fired.
// * Called before {@link #onRippleAnimationEnd()}.
// * @param keyboardButtonEnum The organized enum of the clicked button
// */
// void onKeyboardClick(@KeyboardButtonView.KeyType int keyboardButtonEnum);
//
// /**
// */
// void onRippleAnimationEnd();
//
// }
// Path: app/src/main/java/com/ce/game/screenlocker/view/KeyboardView.java
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
import com.ce.game.screenlocker.R;
import com.ce.game.screenlocker.inter.Clickable;
import com.ce.game.screenlocker.inter.KeyboardButtonClickedListener;
import com.ce.game.screenlocker.view.KeyboardButtonView.KeyType;
import java.util.ArrayList;
import java.util.List;
package com.ce.game.screenlocker.view;
/**
* Created by KyleCe on 2016/5/25.
*
* @author: KyleCe
*/
public class KeyboardView extends RelativeLayout implements View.OnClickListener {
private Context mContext; | private KeyboardButtonClickedListener mKeyboardButtonClickedListener; |
KyleCe/ScreenLocker2 | app/src/main/java/com/ce/game/screenlocker/view/KeyboardView.java | // Path: app/src/main/java/com/ce/game/screenlocker/inter/Clickable.java
// public interface Clickable {
// boolean clickable();
// }
//
// Path: app/src/main/java/com/ce/game/screenlocker/inter/KeyboardButtonClickedListener.java
// public interface KeyboardButtonClickedListener {
//
// /**
// * Receive the click of a button, just after a {@link android.view.View.OnClickListener} has fired.
// * Called before {@link #onRippleAnimationEnd()}.
// * @param keyboardButtonEnum The organized enum of the clicked button
// */
// void onKeyboardClick(@KeyboardButtonView.KeyType int keyboardButtonEnum);
//
// /**
// */
// void onRippleAnimationEnd();
//
// }
| import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
import com.ce.game.screenlocker.R;
import com.ce.game.screenlocker.inter.Clickable;
import com.ce.game.screenlocker.inter.KeyboardButtonClickedListener;
import com.ce.game.screenlocker.view.KeyboardButtonView.KeyType;
import java.util.ArrayList;
import java.util.List; | package com.ce.game.screenlocker.view;
/**
* Created by KyleCe on 2016/5/25.
*
* @author: KyleCe
*/
public class KeyboardView extends RelativeLayout implements View.OnClickListener {
private Context mContext;
private KeyboardButtonClickedListener mKeyboardButtonClickedListener;
private List<KeyboardButtonView> mButtons;
| // Path: app/src/main/java/com/ce/game/screenlocker/inter/Clickable.java
// public interface Clickable {
// boolean clickable();
// }
//
// Path: app/src/main/java/com/ce/game/screenlocker/inter/KeyboardButtonClickedListener.java
// public interface KeyboardButtonClickedListener {
//
// /**
// * Receive the click of a button, just after a {@link android.view.View.OnClickListener} has fired.
// * Called before {@link #onRippleAnimationEnd()}.
// * @param keyboardButtonEnum The organized enum of the clicked button
// */
// void onKeyboardClick(@KeyboardButtonView.KeyType int keyboardButtonEnum);
//
// /**
// */
// void onRippleAnimationEnd();
//
// }
// Path: app/src/main/java/com/ce/game/screenlocker/view/KeyboardView.java
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
import com.ce.game.screenlocker.R;
import com.ce.game.screenlocker.inter.Clickable;
import com.ce.game.screenlocker.inter.KeyboardButtonClickedListener;
import com.ce.game.screenlocker.view.KeyboardButtonView.KeyType;
import java.util.ArrayList;
import java.util.List;
package com.ce.game.screenlocker.view;
/**
* Created by KyleCe on 2016/5/25.
*
* @author: KyleCe
*/
public class KeyboardView extends RelativeLayout implements View.OnClickListener {
private Context mContext;
private KeyboardButtonClickedListener mKeyboardButtonClickedListener;
private List<KeyboardButtonView> mButtons;
| private Clickable mClickableController; |
KyleCe/ScreenLocker2 | app/src/main/java/com/ce/game/screenlocker/util/LockAffairs.java | // Path: app/src/main/java/com/ce/game/screenlocker/common/Const.java
// public class Const {
// // For Activity Result
// public static final String REQUEST_ROLE = "role";
// public static final int REQUEST_USER_ROLE_CODE = 20;
//
// public static final String REQUEST_CITY_INFO = "city";
// public static final int REQUEST_CITY_INFO_CODE = 20;
//
// public static final String REQUEST_ACTIVITY_EXIT = "exit";
// public static final int REQUEST_ACTIVITY_EXIT_CODE = 20;
//
// public static final String REQUEST_CITY_PICKER_INFO = "city_picker";
// public static final int REQUEST_ACTIVITY_CITY = 23;
//
// public static final String NOW_CITY = "location";
// public static final String SAVE_CITY_LIST = "save_city_list";
//
// public static final String APP_HIDE = "Hide Apps";
// public static final String APP_TITLE = "app_title";
//
// public static final int MESSAGE_HIDE_APP = 24;
//
// // For Activity Arguments
// // Action Bar
// public static final String ARGU_ACTION_BAR = "back";
// public static final int ACTION_BAR_FROM_CREATE = 20;
// public static final int ACTION_BAR_FROM_EDIT = 21;
//
// // wallpaper
// public static final int IMAGE_PICK = 5;
// public static final String DEFAULT_WALLPAPER_THUMBNAIL = "default_thumb2.jpg";
// public static final String DEFAULT_WALLPAPER_THUMBNAIL_OLD = "default_thumb.jpg";
// public static final String DIR_ROOT = "blablalauncher";
// public static final String SCREEN_LOCK_WALLPAPER = "/screen_lock_wallpaper";
// public static final String DEFAULT_WALLPAPER_DIRECTORY = "/default-wallpaper";
// public static final String DEFAULT_WALLPAPER_NAME = "default.png";
// public static final String SYSTEM_DEFAULT_WALLPAPER_NAME = "system-default.png";
// public static final String USER_WALLPAPER_NAME = "wallpaper-";
// public static final String USER_WALLPAPER_NAME_SUFFIX = ".png";
// public static final String GUEST_ENIGMA_RESULT = "guest";
// public static final String SCREEN_LOCK_WALLPAPER_THUMBNAIL = "screen_lock_thumb.png";
// public static final String SCREEN_LOCK_WALLPAPER_THUMBNAIL_BLURRED = "screen_lock_thumb_blurred.png";
// public static final String EXCLUDE_DIRECTORY_FROM_GALLERY_TRICK_FILE = ".nomedia";
// public static final String WALLPAPER_TRIGGER_SOURCE = "wallpaper_trigger_source";
// public static final String WALLPAPER_NOT_MYSELF_PASSWORD = "wallpaper_not_myself_password";
// public static final String EMPTY_PASSWORD_ENIGMA_RESULT = "empty";
//
// // retrieve password
// public static class OAuth2Credentials {
// public static final String URL_START = "https://accounts.google.com/o/oauth2/v2/auth?";
// public static final String CLIENT_ID = "294554247866-47jje3ufmkkvtlhkioqtcf43vi7c51to.apps.googleusercontent.com";
// public static final String REDIRECT_URI = "http%3A%2F%2Flocalhost%2F__%2Fauth%2Fhandler";
// public static final String SCOPE = "https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile";
// }
// }
| import android.app.KeyguardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Vibrator;
import android.util.Log;
import com.ce.game.screenlocker.R;
import com.ce.game.screenlocker.common.Const;
import junit.framework.Assert;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream; | package com.ce.game.screenlocker.util;
/**
* Created by KyleCe on 2016/7/6.
*
* @author: KyleCe
*/
public class LockAffairs {
private static final String TAG = LockAffairs.class.getSimpleName();
public static void vibrate(Context mContext, long milliseconds) {
if (mContext == null) return;
Vibrator v = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(milliseconds == 0 ? 500 : milliseconds);
}
@Deprecated
public static final void disableKeyguard(Context context) {
Assert.assertNotNull(context);
final KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
final KeyguardManager.KeyguardLock keyguardLock = keyguardManager.newKeyguardLock("KeyguardLock");
keyguardLock.disableKeyguard();
}
public Bitmap parseCustomBackground(Context context) {
Assert.assertNotNull(context);
try { | // Path: app/src/main/java/com/ce/game/screenlocker/common/Const.java
// public class Const {
// // For Activity Result
// public static final String REQUEST_ROLE = "role";
// public static final int REQUEST_USER_ROLE_CODE = 20;
//
// public static final String REQUEST_CITY_INFO = "city";
// public static final int REQUEST_CITY_INFO_CODE = 20;
//
// public static final String REQUEST_ACTIVITY_EXIT = "exit";
// public static final int REQUEST_ACTIVITY_EXIT_CODE = 20;
//
// public static final String REQUEST_CITY_PICKER_INFO = "city_picker";
// public static final int REQUEST_ACTIVITY_CITY = 23;
//
// public static final String NOW_CITY = "location";
// public static final String SAVE_CITY_LIST = "save_city_list";
//
// public static final String APP_HIDE = "Hide Apps";
// public static final String APP_TITLE = "app_title";
//
// public static final int MESSAGE_HIDE_APP = 24;
//
// // For Activity Arguments
// // Action Bar
// public static final String ARGU_ACTION_BAR = "back";
// public static final int ACTION_BAR_FROM_CREATE = 20;
// public static final int ACTION_BAR_FROM_EDIT = 21;
//
// // wallpaper
// public static final int IMAGE_PICK = 5;
// public static final String DEFAULT_WALLPAPER_THUMBNAIL = "default_thumb2.jpg";
// public static final String DEFAULT_WALLPAPER_THUMBNAIL_OLD = "default_thumb.jpg";
// public static final String DIR_ROOT = "blablalauncher";
// public static final String SCREEN_LOCK_WALLPAPER = "/screen_lock_wallpaper";
// public static final String DEFAULT_WALLPAPER_DIRECTORY = "/default-wallpaper";
// public static final String DEFAULT_WALLPAPER_NAME = "default.png";
// public static final String SYSTEM_DEFAULT_WALLPAPER_NAME = "system-default.png";
// public static final String USER_WALLPAPER_NAME = "wallpaper-";
// public static final String USER_WALLPAPER_NAME_SUFFIX = ".png";
// public static final String GUEST_ENIGMA_RESULT = "guest";
// public static final String SCREEN_LOCK_WALLPAPER_THUMBNAIL = "screen_lock_thumb.png";
// public static final String SCREEN_LOCK_WALLPAPER_THUMBNAIL_BLURRED = "screen_lock_thumb_blurred.png";
// public static final String EXCLUDE_DIRECTORY_FROM_GALLERY_TRICK_FILE = ".nomedia";
// public static final String WALLPAPER_TRIGGER_SOURCE = "wallpaper_trigger_source";
// public static final String WALLPAPER_NOT_MYSELF_PASSWORD = "wallpaper_not_myself_password";
// public static final String EMPTY_PASSWORD_ENIGMA_RESULT = "empty";
//
// // retrieve password
// public static class OAuth2Credentials {
// public static final String URL_START = "https://accounts.google.com/o/oauth2/v2/auth?";
// public static final String CLIENT_ID = "294554247866-47jje3ufmkkvtlhkioqtcf43vi7c51to.apps.googleusercontent.com";
// public static final String REDIRECT_URI = "http%3A%2F%2Flocalhost%2F__%2Fauth%2Fhandler";
// public static final String SCOPE = "https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile";
// }
// }
// Path: app/src/main/java/com/ce/game/screenlocker/util/LockAffairs.java
import android.app.KeyguardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Vibrator;
import android.util.Log;
import com.ce.game.screenlocker.R;
import com.ce.game.screenlocker.common.Const;
import junit.framework.Assert;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
package com.ce.game.screenlocker.util;
/**
* Created by KyleCe on 2016/7/6.
*
* @author: KyleCe
*/
public class LockAffairs {
private static final String TAG = LockAffairs.class.getSimpleName();
public static void vibrate(Context mContext, long milliseconds) {
if (mContext == null) return;
Vibrator v = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(milliseconds == 0 ? 500 : milliseconds);
}
@Deprecated
public static final void disableKeyguard(Context context) {
Assert.assertNotNull(context);
final KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
final KeyguardManager.KeyguardLock keyguardLock = keyguardManager.newKeyguardLock("KeyguardLock");
keyguardLock.disableKeyguard();
}
public Bitmap parseCustomBackground(Context context) {
Assert.assertNotNull(context);
try { | File fileDir = WallpaperSlaver.getAvailableStoreDirFile(Const.DIR_ROOT + Const.SCREEN_LOCK_WALLPAPER, context); |
ErikGartner/xeed | src/main/java/forms/TemplateItemPalettForm.java | // Path: src/main/java/forms/TemplateCreatorForm.java
// public class TreeItem {
//
// String szName;
// String szData;
// int intType;
// boolean boolRoot = false;
//
// @Override
// public String toString() {
// return szName;
// }
// }
| import java.awt.Color;
import java.awt.Image;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import forms.TemplateCreatorForm.TreeItem;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package forms;
/**
*
* @author Erik
*/
public class TemplateItemPalettForm extends javax.swing.JFrame {
DefaultMutableTreeNode editingNode;
| // Path: src/main/java/forms/TemplateCreatorForm.java
// public class TreeItem {
//
// String szName;
// String szData;
// int intType;
// boolean boolRoot = false;
//
// @Override
// public String toString() {
// return szName;
// }
// }
// Path: src/main/java/forms/TemplateItemPalettForm.java
import java.awt.Color;
import java.awt.Image;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import forms.TemplateCreatorForm.TreeItem;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package forms;
/**
*
* @author Erik
*/
public class TemplateItemPalettForm extends javax.swing.JFrame {
DefaultMutableTreeNode editingNode;
| TreeItem editingItem;
|
jeick/jamod | src/main/java/net/wimpi/modbus/net/UDPTerminal.java | // Path: src/main/java/net/wimpi/modbus/io/ModbusUDPTransport.java
// public class ModbusUDPTransport implements ModbusTransport {
//
// // instance attributes
// private UDPTerminal m_Terminal;
// private BytesOutputStream m_ByteOut;
// private BytesInputStream m_ByteIn;
//
// /**
// * Constructs a new <tt>ModbusTransport</tt> instance, for a given
// * <tt>UDPTerminal</tt>.
// * <p>
// *
// * @param terminal
// * the <tt>UDPTerminal</tt> used for message transport.
// */
// public ModbusUDPTransport(UDPTerminal terminal) {
// m_Terminal = terminal;
// m_ByteOut = new BytesOutputStream(Modbus.MAX_IP_MESSAGE_LENGTH);
// m_ByteIn = new BytesInputStream(Modbus.MAX_IP_MESSAGE_LENGTH);
// }// constructor
//
// public void close() throws IOException {
// // ?
// }// close
//
// public void writeMessage(ModbusMessage msg) throws ModbusIOException {
// try {
// synchronized (m_ByteOut) {
// m_ByteOut.reset();
// msg.writeTo((DataOutput) m_ByteOut);
// m_Terminal.sendMessage(m_ByteOut.toByteArray());
// }
// } catch (Exception ex) {
// throw new ModbusIOException("I/O exception - failed to write.");
// }
// }// write
//
// public ModbusRequest readRequest() throws ModbusIOException {
// try {
// ModbusRequest req = null;
// synchronized (m_ByteIn) {
// m_ByteIn.reset(m_Terminal.receiveMessage());
// m_ByteIn.skip(7);
// int functionCode = m_ByteIn.readUnsignedByte();
// m_ByteIn.reset();
// req = ModbusRequest.createModbusRequest(functionCode);
// req.readFrom(m_ByteIn);
// }
// return req;
// } catch (Exception ex) {
// throw new ModbusIOException("I/O exception - failed to read.");
// }
// }// readRequest
//
// public ModbusResponse readResponse() throws ModbusIOException {
//
// try {
// ModbusResponse res = null;
// synchronized (m_ByteIn) {
// m_ByteIn.reset(m_Terminal.receiveMessage());
// m_ByteIn.skip(7);
// int functionCode = m_ByteIn.readUnsignedByte();
// m_ByteIn.reset();
// res = ModbusResponse.createModbusResponse(functionCode);
// res.readFrom(m_ByteIn);
// }
// return res;
// } catch (InterruptedIOException ioex) {
// throw new ModbusIOException("Socket timed out.");
// } catch (Exception ex) {
// ex.printStackTrace();
// throw new ModbusIOException("I/O exception - failed to read.");
// }
// }// readResponse
//
// @Override
// public void flush() {
// m_ByteIn.skip(m_ByteIn.available());
// }
//
// }// class ModbusUDPTransport
| import java.net.InetAddress;
import net.wimpi.modbus.io.ModbusUDPTransport; | /***
* Copyright 2002-2010 jamod development team
*
* 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 net.wimpi.modbus.net;
/**
* Interface defining a <tt>UDPTerminal</tt>.
*
* @author Dieter Wimberger
* @version @version@ (@date@)
*/
public interface UDPTerminal {
/**
* Returns the local address of this <tt>UDPTerminal</tt>.
*
* @return an <tt>InetAddress</tt> instance.
*/
public InetAddress getLocalAddress();
/**
* Returns the local port of this <tt>UDPTerminal</tt>.
*
* @return the local port as <tt>int</tt>.
*/
public int getLocalPort();
/**
* Tests if this <tt>UDPTerminal</tt> is active.
*
* @return <tt>true</tt> if active, <tt>false</tt> otherwise.
*/
public boolean isActive();
/**
* Activate this <tt>UDPTerminal</tt>.
*
* @throws java.lang.Exception
* if there is a network failure.
*/
public void activate() throws Exception;
/**
* Deactivates this <tt>UDPTerminal</tt>.
*/
public void deactivate();
/**
* Returns the <tt>ModbusTransport</tt> associated with this
* <tt>UDPTerminal</tt>.
*
* @return a <tt>ModbusTransport</tt> instance.
*/ | // Path: src/main/java/net/wimpi/modbus/io/ModbusUDPTransport.java
// public class ModbusUDPTransport implements ModbusTransport {
//
// // instance attributes
// private UDPTerminal m_Terminal;
// private BytesOutputStream m_ByteOut;
// private BytesInputStream m_ByteIn;
//
// /**
// * Constructs a new <tt>ModbusTransport</tt> instance, for a given
// * <tt>UDPTerminal</tt>.
// * <p>
// *
// * @param terminal
// * the <tt>UDPTerminal</tt> used for message transport.
// */
// public ModbusUDPTransport(UDPTerminal terminal) {
// m_Terminal = terminal;
// m_ByteOut = new BytesOutputStream(Modbus.MAX_IP_MESSAGE_LENGTH);
// m_ByteIn = new BytesInputStream(Modbus.MAX_IP_MESSAGE_LENGTH);
// }// constructor
//
// public void close() throws IOException {
// // ?
// }// close
//
// public void writeMessage(ModbusMessage msg) throws ModbusIOException {
// try {
// synchronized (m_ByteOut) {
// m_ByteOut.reset();
// msg.writeTo((DataOutput) m_ByteOut);
// m_Terminal.sendMessage(m_ByteOut.toByteArray());
// }
// } catch (Exception ex) {
// throw new ModbusIOException("I/O exception - failed to write.");
// }
// }// write
//
// public ModbusRequest readRequest() throws ModbusIOException {
// try {
// ModbusRequest req = null;
// synchronized (m_ByteIn) {
// m_ByteIn.reset(m_Terminal.receiveMessage());
// m_ByteIn.skip(7);
// int functionCode = m_ByteIn.readUnsignedByte();
// m_ByteIn.reset();
// req = ModbusRequest.createModbusRequest(functionCode);
// req.readFrom(m_ByteIn);
// }
// return req;
// } catch (Exception ex) {
// throw new ModbusIOException("I/O exception - failed to read.");
// }
// }// readRequest
//
// public ModbusResponse readResponse() throws ModbusIOException {
//
// try {
// ModbusResponse res = null;
// synchronized (m_ByteIn) {
// m_ByteIn.reset(m_Terminal.receiveMessage());
// m_ByteIn.skip(7);
// int functionCode = m_ByteIn.readUnsignedByte();
// m_ByteIn.reset();
// res = ModbusResponse.createModbusResponse(functionCode);
// res.readFrom(m_ByteIn);
// }
// return res;
// } catch (InterruptedIOException ioex) {
// throw new ModbusIOException("Socket timed out.");
// } catch (Exception ex) {
// ex.printStackTrace();
// throw new ModbusIOException("I/O exception - failed to read.");
// }
// }// readResponse
//
// @Override
// public void flush() {
// m_ByteIn.skip(m_ByteIn.available());
// }
//
// }// class ModbusUDPTransport
// Path: src/main/java/net/wimpi/modbus/net/UDPTerminal.java
import java.net.InetAddress;
import net.wimpi.modbus.io.ModbusUDPTransport;
/***
* Copyright 2002-2010 jamod development team
*
* 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 net.wimpi.modbus.net;
/**
* Interface defining a <tt>UDPTerminal</tt>.
*
* @author Dieter Wimberger
* @version @version@ (@date@)
*/
public interface UDPTerminal {
/**
* Returns the local address of this <tt>UDPTerminal</tt>.
*
* @return an <tt>InetAddress</tt> instance.
*/
public InetAddress getLocalAddress();
/**
* Returns the local port of this <tt>UDPTerminal</tt>.
*
* @return the local port as <tt>int</tt>.
*/
public int getLocalPort();
/**
* Tests if this <tt>UDPTerminal</tt> is active.
*
* @return <tt>true</tt> if active, <tt>false</tt> otherwise.
*/
public boolean isActive();
/**
* Activate this <tt>UDPTerminal</tt>.
*
* @throws java.lang.Exception
* if there is a network failure.
*/
public void activate() throws Exception;
/**
* Deactivates this <tt>UDPTerminal</tt>.
*/
public void deactivate();
/**
* Returns the <tt>ModbusTransport</tt> associated with this
* <tt>UDPTerminal</tt>.
*
* @return a <tt>ModbusTransport</tt> instance.
*/ | public ModbusUDPTransport getModbusTransport(); |
urbanairship/datacube | src/main/java/com/urbanairship/datacube/ops/LongOp.java | // Path: src/main/java/com/urbanairship/datacube/Deserializer.java
// public interface Deserializer<O extends Op> {
// O fromBytes(byte[] bytes);
// }
//
// Path: src/main/java/com/urbanairship/datacube/Op.java
// public interface Op extends CSerializable {
// /**
// * @return an Op that combines the effect of this and otherOp.
// */
// Op add(Op otherOp);
//
// /**
// * Return the difference between this op and the given one.
// *
// * This should satisfy the following property:
// * y + x.subtract(y) = x
// *
// * This holds for integers, e.g. 10 + (15 - 10) = 15
// *
// * An example using LongOp:
// * assert new LongOp(10).add(new LongOp(15).subtract(10).equals(15)
// */
// Op subtract(Op otherOp);
//
// /**
// * Subclasses must override equals() and hashCode().
// */
// @Override
// boolean equals(Object other);
//
// @Override
// int hashCode();
// }
//
// Path: src/main/java/com/urbanairship/datacube/Util.java
// public class Util {
// public static byte[] longToBytes(long l) {
// return ByteBuffer.allocate(8).putLong(l).array();
// }
//
// /**
// * Write a big-endian integer into the least significant bytes of a byte array.
// */
// public static byte[] intToBytesWithLen(int x, int len) {
// if(len <= 4) {
// return trailingBytes(intToBytes(x), len);
// } else {
// ByteBuffer bb = ByteBuffer.allocate(len);
// bb.position(len-4);
// bb.putInt(x);
// assert bb.remaining() == 0;
// return bb.array();
// }
// }
//
// public static long bytesToLong(byte[] bytes) {
// if(bytes.length < 8) {
// throw new IllegalArgumentException("Input array was too small: " +
// Arrays.toString(bytes));
// }
//
// return ByteBuffer.wrap(bytes).getLong();
// }
//
// /**
// * Call this if you have a byte array to convert to long, but your array might need
// * to be left-padded with zeros (if it is less than 8 bytes long).
// */
// public static long bytesToLongPad(byte[] bytes) {
// final int padZeros = Math.max(8-bytes.length, 0);
// ByteBuffer bb = ByteBuffer.allocate(8);
// for(int i=0; i<padZeros; i++) {
// bb.put((byte)0);
// }
// bb.put(bytes, 0, 8-padZeros);
// bb.flip();
// return bb.getLong();
// }
//
// public static byte[] intToBytes(int x) {
// ByteBuffer bb = ByteBuffer.allocate(4);
// bb.putInt(x);
// return bb.array();
// }
//
// public static int bytesToInt(byte[] bytes) {
// return ByteBuffer.wrap(bytes).getInt();
// }
//
// public static byte[] leastSignificantBytes(long l, int numBytes) {
// byte[] all8Bytes = Util.longToBytes(l);
// return trailingBytes(all8Bytes, numBytes);
// }
//
// public static byte[] trailingBytes(byte[] bs, int numBytes) {
// return Arrays.copyOfRange(bs, bs.length-numBytes, bs.length);
// }
//
// /**
// * A utility to allow hashing of a portion of an array without having to copy it.
// * @param array
// * @param startInclusive
// * @param endExclusive
// * @return hash byte
// */
// public static byte hashByteArray(byte[] array, int startInclusive, int endExclusive) {
// if (array == null) {
// return 0;
// }
//
// int range = endExclusive - startInclusive;
// if (range < 0) {
// throw new IllegalArgumentException(startInclusive + " > " + endExclusive);
// }
//
// int result = 1;
// for (int i=startInclusive; i<endExclusive; i++){
// result = 31 * result + array[i];
// }
//
// return (byte)result;
// }
//
// /**
// * Only use this for testing/debugging. Inefficient.
// */
// public static long countRows(Configuration conf, byte[] tableName) throws IOException {
// HTable hTable = null;
// ResultScanner rs = null;
// long count = 0;
// try {
// hTable = new HTable(conf, tableName);
// rs = hTable.getScanner(new Scan());
// for(@SuppressWarnings("unused") Result r: rs) {
// count++;
// }
// return count;
// } finally {
// if(hTable != null) {
// hTable.close();
// }
// if(rs != null) {
// rs.close();
// }
// }
// }
// }
| import com.urbanairship.datacube.Util;
import com.urbanairship.datacube.Deserializer;
import com.urbanairship.datacube.Op; | /**
* Eclipse auto-generated
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (val ^ (val >>> 32));
return result;
}
/**
* Eclipse auto-generated
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
LongOp other = (LongOp) obj;
if (val != other.val)
return false;
return true;
}
@Override
public byte[] serialize() { | // Path: src/main/java/com/urbanairship/datacube/Deserializer.java
// public interface Deserializer<O extends Op> {
// O fromBytes(byte[] bytes);
// }
//
// Path: src/main/java/com/urbanairship/datacube/Op.java
// public interface Op extends CSerializable {
// /**
// * @return an Op that combines the effect of this and otherOp.
// */
// Op add(Op otherOp);
//
// /**
// * Return the difference between this op and the given one.
// *
// * This should satisfy the following property:
// * y + x.subtract(y) = x
// *
// * This holds for integers, e.g. 10 + (15 - 10) = 15
// *
// * An example using LongOp:
// * assert new LongOp(10).add(new LongOp(15).subtract(10).equals(15)
// */
// Op subtract(Op otherOp);
//
// /**
// * Subclasses must override equals() and hashCode().
// */
// @Override
// boolean equals(Object other);
//
// @Override
// int hashCode();
// }
//
// Path: src/main/java/com/urbanairship/datacube/Util.java
// public class Util {
// public static byte[] longToBytes(long l) {
// return ByteBuffer.allocate(8).putLong(l).array();
// }
//
// /**
// * Write a big-endian integer into the least significant bytes of a byte array.
// */
// public static byte[] intToBytesWithLen(int x, int len) {
// if(len <= 4) {
// return trailingBytes(intToBytes(x), len);
// } else {
// ByteBuffer bb = ByteBuffer.allocate(len);
// bb.position(len-4);
// bb.putInt(x);
// assert bb.remaining() == 0;
// return bb.array();
// }
// }
//
// public static long bytesToLong(byte[] bytes) {
// if(bytes.length < 8) {
// throw new IllegalArgumentException("Input array was too small: " +
// Arrays.toString(bytes));
// }
//
// return ByteBuffer.wrap(bytes).getLong();
// }
//
// /**
// * Call this if you have a byte array to convert to long, but your array might need
// * to be left-padded with zeros (if it is less than 8 bytes long).
// */
// public static long bytesToLongPad(byte[] bytes) {
// final int padZeros = Math.max(8-bytes.length, 0);
// ByteBuffer bb = ByteBuffer.allocate(8);
// for(int i=0; i<padZeros; i++) {
// bb.put((byte)0);
// }
// bb.put(bytes, 0, 8-padZeros);
// bb.flip();
// return bb.getLong();
// }
//
// public static byte[] intToBytes(int x) {
// ByteBuffer bb = ByteBuffer.allocate(4);
// bb.putInt(x);
// return bb.array();
// }
//
// public static int bytesToInt(byte[] bytes) {
// return ByteBuffer.wrap(bytes).getInt();
// }
//
// public static byte[] leastSignificantBytes(long l, int numBytes) {
// byte[] all8Bytes = Util.longToBytes(l);
// return trailingBytes(all8Bytes, numBytes);
// }
//
// public static byte[] trailingBytes(byte[] bs, int numBytes) {
// return Arrays.copyOfRange(bs, bs.length-numBytes, bs.length);
// }
//
// /**
// * A utility to allow hashing of a portion of an array without having to copy it.
// * @param array
// * @param startInclusive
// * @param endExclusive
// * @return hash byte
// */
// public static byte hashByteArray(byte[] array, int startInclusive, int endExclusive) {
// if (array == null) {
// return 0;
// }
//
// int range = endExclusive - startInclusive;
// if (range < 0) {
// throw new IllegalArgumentException(startInclusive + " > " + endExclusive);
// }
//
// int result = 1;
// for (int i=startInclusive; i<endExclusive; i++){
// result = 31 * result + array[i];
// }
//
// return (byte)result;
// }
//
// /**
// * Only use this for testing/debugging. Inefficient.
// */
// public static long countRows(Configuration conf, byte[] tableName) throws IOException {
// HTable hTable = null;
// ResultScanner rs = null;
// long count = 0;
// try {
// hTable = new HTable(conf, tableName);
// rs = hTable.getScanner(new Scan());
// for(@SuppressWarnings("unused") Result r: rs) {
// count++;
// }
// return count;
// } finally {
// if(hTable != null) {
// hTable.close();
// }
// if(rs != null) {
// rs.close();
// }
// }
// }
// }
// Path: src/main/java/com/urbanairship/datacube/ops/LongOp.java
import com.urbanairship.datacube.Util;
import com.urbanairship.datacube.Deserializer;
import com.urbanairship.datacube.Op;
/**
* Eclipse auto-generated
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (val ^ (val >>> 32));
return result;
}
/**
* Eclipse auto-generated
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
LongOp other = (LongOp) obj;
if (val != other.val)
return false;
return true;
}
@Override
public byte[] serialize() { | return Util.longToBytes(val); |
urbanairship/datacube | src/main/java/com/urbanairship/datacube/ops/LongOp.java | // Path: src/main/java/com/urbanairship/datacube/Deserializer.java
// public interface Deserializer<O extends Op> {
// O fromBytes(byte[] bytes);
// }
//
// Path: src/main/java/com/urbanairship/datacube/Op.java
// public interface Op extends CSerializable {
// /**
// * @return an Op that combines the effect of this and otherOp.
// */
// Op add(Op otherOp);
//
// /**
// * Return the difference between this op and the given one.
// *
// * This should satisfy the following property:
// * y + x.subtract(y) = x
// *
// * This holds for integers, e.g. 10 + (15 - 10) = 15
// *
// * An example using LongOp:
// * assert new LongOp(10).add(new LongOp(15).subtract(10).equals(15)
// */
// Op subtract(Op otherOp);
//
// /**
// * Subclasses must override equals() and hashCode().
// */
// @Override
// boolean equals(Object other);
//
// @Override
// int hashCode();
// }
//
// Path: src/main/java/com/urbanairship/datacube/Util.java
// public class Util {
// public static byte[] longToBytes(long l) {
// return ByteBuffer.allocate(8).putLong(l).array();
// }
//
// /**
// * Write a big-endian integer into the least significant bytes of a byte array.
// */
// public static byte[] intToBytesWithLen(int x, int len) {
// if(len <= 4) {
// return trailingBytes(intToBytes(x), len);
// } else {
// ByteBuffer bb = ByteBuffer.allocate(len);
// bb.position(len-4);
// bb.putInt(x);
// assert bb.remaining() == 0;
// return bb.array();
// }
// }
//
// public static long bytesToLong(byte[] bytes) {
// if(bytes.length < 8) {
// throw new IllegalArgumentException("Input array was too small: " +
// Arrays.toString(bytes));
// }
//
// return ByteBuffer.wrap(bytes).getLong();
// }
//
// /**
// * Call this if you have a byte array to convert to long, but your array might need
// * to be left-padded with zeros (if it is less than 8 bytes long).
// */
// public static long bytesToLongPad(byte[] bytes) {
// final int padZeros = Math.max(8-bytes.length, 0);
// ByteBuffer bb = ByteBuffer.allocate(8);
// for(int i=0; i<padZeros; i++) {
// bb.put((byte)0);
// }
// bb.put(bytes, 0, 8-padZeros);
// bb.flip();
// return bb.getLong();
// }
//
// public static byte[] intToBytes(int x) {
// ByteBuffer bb = ByteBuffer.allocate(4);
// bb.putInt(x);
// return bb.array();
// }
//
// public static int bytesToInt(byte[] bytes) {
// return ByteBuffer.wrap(bytes).getInt();
// }
//
// public static byte[] leastSignificantBytes(long l, int numBytes) {
// byte[] all8Bytes = Util.longToBytes(l);
// return trailingBytes(all8Bytes, numBytes);
// }
//
// public static byte[] trailingBytes(byte[] bs, int numBytes) {
// return Arrays.copyOfRange(bs, bs.length-numBytes, bs.length);
// }
//
// /**
// * A utility to allow hashing of a portion of an array without having to copy it.
// * @param array
// * @param startInclusive
// * @param endExclusive
// * @return hash byte
// */
// public static byte hashByteArray(byte[] array, int startInclusive, int endExclusive) {
// if (array == null) {
// return 0;
// }
//
// int range = endExclusive - startInclusive;
// if (range < 0) {
// throw new IllegalArgumentException(startInclusive + " > " + endExclusive);
// }
//
// int result = 1;
// for (int i=startInclusive; i<endExclusive; i++){
// result = 31 * result + array[i];
// }
//
// return (byte)result;
// }
//
// /**
// * Only use this for testing/debugging. Inefficient.
// */
// public static long countRows(Configuration conf, byte[] tableName) throws IOException {
// HTable hTable = null;
// ResultScanner rs = null;
// long count = 0;
// try {
// hTable = new HTable(conf, tableName);
// rs = hTable.getScanner(new Scan());
// for(@SuppressWarnings("unused") Result r: rs) {
// count++;
// }
// return count;
// } finally {
// if(hTable != null) {
// hTable.close();
// }
// if(rs != null) {
// rs.close();
// }
// }
// }
// }
| import com.urbanairship.datacube.Util;
import com.urbanairship.datacube.Deserializer;
import com.urbanairship.datacube.Op; | @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (val ^ (val >>> 32));
return result;
}
/**
* Eclipse auto-generated
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
LongOp other = (LongOp) obj;
if (val != other.val)
return false;
return true;
}
@Override
public byte[] serialize() {
return Util.longToBytes(val);
}
| // Path: src/main/java/com/urbanairship/datacube/Deserializer.java
// public interface Deserializer<O extends Op> {
// O fromBytes(byte[] bytes);
// }
//
// Path: src/main/java/com/urbanairship/datacube/Op.java
// public interface Op extends CSerializable {
// /**
// * @return an Op that combines the effect of this and otherOp.
// */
// Op add(Op otherOp);
//
// /**
// * Return the difference between this op and the given one.
// *
// * This should satisfy the following property:
// * y + x.subtract(y) = x
// *
// * This holds for integers, e.g. 10 + (15 - 10) = 15
// *
// * An example using LongOp:
// * assert new LongOp(10).add(new LongOp(15).subtract(10).equals(15)
// */
// Op subtract(Op otherOp);
//
// /**
// * Subclasses must override equals() and hashCode().
// */
// @Override
// boolean equals(Object other);
//
// @Override
// int hashCode();
// }
//
// Path: src/main/java/com/urbanairship/datacube/Util.java
// public class Util {
// public static byte[] longToBytes(long l) {
// return ByteBuffer.allocate(8).putLong(l).array();
// }
//
// /**
// * Write a big-endian integer into the least significant bytes of a byte array.
// */
// public static byte[] intToBytesWithLen(int x, int len) {
// if(len <= 4) {
// return trailingBytes(intToBytes(x), len);
// } else {
// ByteBuffer bb = ByteBuffer.allocate(len);
// bb.position(len-4);
// bb.putInt(x);
// assert bb.remaining() == 0;
// return bb.array();
// }
// }
//
// public static long bytesToLong(byte[] bytes) {
// if(bytes.length < 8) {
// throw new IllegalArgumentException("Input array was too small: " +
// Arrays.toString(bytes));
// }
//
// return ByteBuffer.wrap(bytes).getLong();
// }
//
// /**
// * Call this if you have a byte array to convert to long, but your array might need
// * to be left-padded with zeros (if it is less than 8 bytes long).
// */
// public static long bytesToLongPad(byte[] bytes) {
// final int padZeros = Math.max(8-bytes.length, 0);
// ByteBuffer bb = ByteBuffer.allocate(8);
// for(int i=0; i<padZeros; i++) {
// bb.put((byte)0);
// }
// bb.put(bytes, 0, 8-padZeros);
// bb.flip();
// return bb.getLong();
// }
//
// public static byte[] intToBytes(int x) {
// ByteBuffer bb = ByteBuffer.allocate(4);
// bb.putInt(x);
// return bb.array();
// }
//
// public static int bytesToInt(byte[] bytes) {
// return ByteBuffer.wrap(bytes).getInt();
// }
//
// public static byte[] leastSignificantBytes(long l, int numBytes) {
// byte[] all8Bytes = Util.longToBytes(l);
// return trailingBytes(all8Bytes, numBytes);
// }
//
// public static byte[] trailingBytes(byte[] bs, int numBytes) {
// return Arrays.copyOfRange(bs, bs.length-numBytes, bs.length);
// }
//
// /**
// * A utility to allow hashing of a portion of an array without having to copy it.
// * @param array
// * @param startInclusive
// * @param endExclusive
// * @return hash byte
// */
// public static byte hashByteArray(byte[] array, int startInclusive, int endExclusive) {
// if (array == null) {
// return 0;
// }
//
// int range = endExclusive - startInclusive;
// if (range < 0) {
// throw new IllegalArgumentException(startInclusive + " > " + endExclusive);
// }
//
// int result = 1;
// for (int i=startInclusive; i<endExclusive; i++){
// result = 31 * result + array[i];
// }
//
// return (byte)result;
// }
//
// /**
// * Only use this for testing/debugging. Inefficient.
// */
// public static long countRows(Configuration conf, byte[] tableName) throws IOException {
// HTable hTable = null;
// ResultScanner rs = null;
// long count = 0;
// try {
// hTable = new HTable(conf, tableName);
// rs = hTable.getScanner(new Scan());
// for(@SuppressWarnings("unused") Result r: rs) {
// count++;
// }
// return count;
// } finally {
// if(hTable != null) {
// hTable.close();
// }
// if(rs != null) {
// rs.close();
// }
// }
// }
// }
// Path: src/main/java/com/urbanairship/datacube/ops/LongOp.java
import com.urbanairship.datacube.Util;
import com.urbanairship.datacube.Deserializer;
import com.urbanairship.datacube.Op;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (val ^ (val >>> 32));
return result;
}
/**
* Eclipse auto-generated
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
LongOp other = (LongOp) obj;
if (val != other.val)
return false;
return true;
}
@Override
public byte[] serialize() {
return Util.longToBytes(val);
}
| public static class LongOpDeserializer implements Deserializer<LongOp> { |
urbanairship/datacube | src/test/java/com/urbanairship/datacube/CollectionWritableTest.java | // Path: src/main/java/com/urbanairship/datacube/backfill/CollectionWritable.java
// public class CollectionWritable implements Writable {
// private Collection<? extends Writable> collection;
// private Class<? extends Writable> elementClass;
//
// public CollectionWritable() { } // No-op constructor is required for deserializing
//
// public CollectionWritable(Class<? extends Writable> elementClass,
// Collection<? extends Writable> collection) {
// this.elementClass = elementClass;
// this.collection = collection;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public void readFields(DataInput in) throws IOException {
// try {
// String valueClassName = in.readUTF();
// elementClass = (Class<? extends Writable>)Class.forName(valueClassName);
// if(!Writable.class.isAssignableFrom(elementClass)) {
// throw new RuntimeException("valueClass is not writable: " + valueClassName);
// }
// int numElements = in.readInt();
// List<Writable> newList = new ArrayList<Writable>(numElements);
// for(int i=0; i<numElements; i++) {
// Writable instance = elementClass.newInstance();
// instance.readFields(in);
// newList.add(instance);
// }
// collection = newList;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// @Override
// public void write(DataOutput out) throws IOException {
// out.writeUTF(elementClass.getName());
// out.writeInt(collection.size());
// for(Writable writable: collection) {
// writable.write(out);
// }
// }
//
// public Collection<? extends Writable> getCollection() {
// return collection;
// }
// }
| import com.urbanairship.datacube.backfill.CollectionWritable;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.io.DataInputBuffer;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Writable;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List; | /*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube;
public class CollectionWritableTest {
@Test
public void basicTest() throws Exception {
List<IntWritable> list = new ArrayList<IntWritable>();
list.add(new IntWritable(1));
list.add(new IntWritable(2));
list.add(new IntWritable(3));
| // Path: src/main/java/com/urbanairship/datacube/backfill/CollectionWritable.java
// public class CollectionWritable implements Writable {
// private Collection<? extends Writable> collection;
// private Class<? extends Writable> elementClass;
//
// public CollectionWritable() { } // No-op constructor is required for deserializing
//
// public CollectionWritable(Class<? extends Writable> elementClass,
// Collection<? extends Writable> collection) {
// this.elementClass = elementClass;
// this.collection = collection;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public void readFields(DataInput in) throws IOException {
// try {
// String valueClassName = in.readUTF();
// elementClass = (Class<? extends Writable>)Class.forName(valueClassName);
// if(!Writable.class.isAssignableFrom(elementClass)) {
// throw new RuntimeException("valueClass is not writable: " + valueClassName);
// }
// int numElements = in.readInt();
// List<Writable> newList = new ArrayList<Writable>(numElements);
// for(int i=0; i<numElements; i++) {
// Writable instance = elementClass.newInstance();
// instance.readFields(in);
// newList.add(instance);
// }
// collection = newList;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// @Override
// public void write(DataOutput out) throws IOException {
// out.writeUTF(elementClass.getName());
// out.writeInt(collection.size());
// for(Writable writable: collection) {
// writable.write(out);
// }
// }
//
// public Collection<? extends Writable> getCollection() {
// return collection;
// }
// }
// Path: src/test/java/com/urbanairship/datacube/CollectionWritableTest.java
import com.urbanairship.datacube.backfill.CollectionWritable;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.io.DataInputBuffer;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Writable;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
/*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube;
public class CollectionWritableTest {
@Test
public void basicTest() throws Exception {
List<IntWritable> list = new ArrayList<IntWritable>();
list.add(new IntWritable(1));
list.add(new IntWritable(2));
list.add(new IntWritable(3));
| CollectionWritable c = new CollectionWritable(IntWritable.class, list); |
urbanairship/datacube | src/main/java/com/urbanairship/datacube/bucketers/AbstractIdentityBucketer.java | // Path: src/main/java/com/urbanairship/datacube/BucketType.java
// public class BucketType {
// public static final BucketType IDENTITY = new BucketType("nobucket", new byte[]{});
// public static final BucketType WILDCARD = new BucketType("wildcard", new byte[]{});
//
// private final String nameInErrMsgs;
// private final byte[] uniqueId;
//
// public BucketType(String nameInErrMsgs, byte[] uniqueId) {
// this.nameInErrMsgs = nameInErrMsgs;
// this.uniqueId = uniqueId;
// }
//
// public byte[] getUniqueId() {
// return uniqueId;
// }
//
// public String getNameInErrMsgs() {
// return nameInErrMsgs;
// }
//
// public String toString() {
// return nameInErrMsgs;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof BucketType)) return false;
// BucketType that = (BucketType) o;
// return Objects.equals(nameInErrMsgs, that.nameInErrMsgs) &&
// Arrays.equals(uniqueId, that.uniqueId);
// }
//
// @Override
// public int hashCode() {
//
// int result = Objects.hash(nameInErrMsgs);
// result = 31 * result + Arrays.hashCode(uniqueId);
// return result;
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/Bucketer.java
// public interface Bucketer<F> {
// /**
// * When writing to the cube at some address, the address will have one coordinate for each
// * dimension in the cube, for example (time: 348524388, location: portland). For each
// * dimension, for each bucket type within that dimension, the bucketer must transform the
// * input data into the bucket that should be used to store the data.
// */
// SetMultimap<BucketType, CSerializable> bucketForWrite(F coordinate);
//
// /**
// * When reading from the cube, the reader specifies some coordinates from which to read.
// * The bucketer can choose which cube coordinates to read from based on these input
// * coordinates. For example, if the reader asks for hourly counts (the Hourly BucketType) and
// * passes a timestamp, the bucketer could return the timestamp rounded down to the hour floor.
// */
// CSerializable bucketForRead(Object coordinate, BucketType bucketType);
//
// /**
// * Return all bucket types that exist in this dimension.
// */
// List<BucketType> getBucketTypes();
//
//
// /**
// * This identity/no-op bucketer class is implicitly used for dimensions that don't choose a
// * bucketer.
// */
// class IdentityBucketer implements Bucketer<CSerializable> {
// private final List<BucketType> bucketTypes = ImmutableList.of(BucketType.IDENTITY);
//
// @Override
// public SetMultimap<BucketType, CSerializable> bucketForWrite(CSerializable coordinate) {
// return ImmutableSetMultimap.of(BucketType.IDENTITY, coordinate);
// }
//
// @Override
// public CSerializable bucketForRead(Object coordinateField, BucketType bucketType) {
// return (CSerializable) coordinateField;
// }
//
// @Override
// public List<BucketType> getBucketTypes() {
// return bucketTypes;
// }
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
| import java.util.List;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.SetMultimap;
import com.urbanairship.datacube.BucketType;
import com.urbanairship.datacube.Bucketer;
import com.urbanairship.datacube.CSerializable; | package com.urbanairship.datacube.bucketers;
/**
* An implementation of the {@link Bucketer} to make it easy to create a bucketer that
* always uses the identity bucket type ({@link BucketType#IDENTITY}).
*/
public abstract class AbstractIdentityBucketer<T> implements Bucketer<T> {
private final List<BucketType> bucketTypes = ImmutableList.of(BucketType.IDENTITY);
@Override
public List<BucketType> getBucketTypes() {
return bucketTypes;
}
@Override | // Path: src/main/java/com/urbanairship/datacube/BucketType.java
// public class BucketType {
// public static final BucketType IDENTITY = new BucketType("nobucket", new byte[]{});
// public static final BucketType WILDCARD = new BucketType("wildcard", new byte[]{});
//
// private final String nameInErrMsgs;
// private final byte[] uniqueId;
//
// public BucketType(String nameInErrMsgs, byte[] uniqueId) {
// this.nameInErrMsgs = nameInErrMsgs;
// this.uniqueId = uniqueId;
// }
//
// public byte[] getUniqueId() {
// return uniqueId;
// }
//
// public String getNameInErrMsgs() {
// return nameInErrMsgs;
// }
//
// public String toString() {
// return nameInErrMsgs;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof BucketType)) return false;
// BucketType that = (BucketType) o;
// return Objects.equals(nameInErrMsgs, that.nameInErrMsgs) &&
// Arrays.equals(uniqueId, that.uniqueId);
// }
//
// @Override
// public int hashCode() {
//
// int result = Objects.hash(nameInErrMsgs);
// result = 31 * result + Arrays.hashCode(uniqueId);
// return result;
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/Bucketer.java
// public interface Bucketer<F> {
// /**
// * When writing to the cube at some address, the address will have one coordinate for each
// * dimension in the cube, for example (time: 348524388, location: portland). For each
// * dimension, for each bucket type within that dimension, the bucketer must transform the
// * input data into the bucket that should be used to store the data.
// */
// SetMultimap<BucketType, CSerializable> bucketForWrite(F coordinate);
//
// /**
// * When reading from the cube, the reader specifies some coordinates from which to read.
// * The bucketer can choose which cube coordinates to read from based on these input
// * coordinates. For example, if the reader asks for hourly counts (the Hourly BucketType) and
// * passes a timestamp, the bucketer could return the timestamp rounded down to the hour floor.
// */
// CSerializable bucketForRead(Object coordinate, BucketType bucketType);
//
// /**
// * Return all bucket types that exist in this dimension.
// */
// List<BucketType> getBucketTypes();
//
//
// /**
// * This identity/no-op bucketer class is implicitly used for dimensions that don't choose a
// * bucketer.
// */
// class IdentityBucketer implements Bucketer<CSerializable> {
// private final List<BucketType> bucketTypes = ImmutableList.of(BucketType.IDENTITY);
//
// @Override
// public SetMultimap<BucketType, CSerializable> bucketForWrite(CSerializable coordinate) {
// return ImmutableSetMultimap.of(BucketType.IDENTITY, coordinate);
// }
//
// @Override
// public CSerializable bucketForRead(Object coordinateField, BucketType bucketType) {
// return (CSerializable) coordinateField;
// }
//
// @Override
// public List<BucketType> getBucketTypes() {
// return bucketTypes;
// }
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
// Path: src/main/java/com/urbanairship/datacube/bucketers/AbstractIdentityBucketer.java
import java.util.List;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.SetMultimap;
import com.urbanairship.datacube.BucketType;
import com.urbanairship.datacube.Bucketer;
import com.urbanairship.datacube.CSerializable;
package com.urbanairship.datacube.bucketers;
/**
* An implementation of the {@link Bucketer} to make it easy to create a bucketer that
* always uses the identity bucket type ({@link BucketType#IDENTITY}).
*/
public abstract class AbstractIdentityBucketer<T> implements Bucketer<T> {
private final List<BucketType> bucketTypes = ImmutableList.of(BucketType.IDENTITY);
@Override
public List<BucketType> getBucketTypes() {
return bucketTypes;
}
@Override | public SetMultimap<BucketType, CSerializable> bucketForWrite(T coordinate) { |
urbanairship/datacube | src/main/java/com/urbanairship/datacube/collectioninputformat/CollectionInputFormat.java | // Path: src/main/java/com/urbanairship/datacube/backfill/CollectionWritable.java
// public class CollectionWritable implements Writable {
// private Collection<? extends Writable> collection;
// private Class<? extends Writable> elementClass;
//
// public CollectionWritable() { } // No-op constructor is required for deserializing
//
// public CollectionWritable(Class<? extends Writable> elementClass,
// Collection<? extends Writable> collection) {
// this.elementClass = elementClass;
// this.collection = collection;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public void readFields(DataInput in) throws IOException {
// try {
// String valueClassName = in.readUTF();
// elementClass = (Class<? extends Writable>)Class.forName(valueClassName);
// if(!Writable.class.isAssignableFrom(elementClass)) {
// throw new RuntimeException("valueClass is not writable: " + valueClassName);
// }
// int numElements = in.readInt();
// List<Writable> newList = new ArrayList<Writable>(numElements);
// for(int i=0; i<numElements; i++) {
// Writable instance = elementClass.newInstance();
// instance.readFields(in);
// newList.add(instance);
// }
// collection = newList;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// @Override
// public void write(DataOutput out) throws IOException {
// out.writeUTF(elementClass.getName());
// out.writeInt(collection.size());
// for(Writable writable: collection) {
// writable.write(out);
// }
// }
//
// public Collection<? extends Writable> getCollection() {
// return collection;
// }
// }
| import com.urbanairship.datacube.backfill.CollectionWritable;
import org.apache.commons.codec.binary.Base64;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.DataInputBuffer;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List; | /*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.collectioninputformat;
/**
* A Hadoop InputFormat that lets you use an arbitrary Collection as input to a mapreduce job.
* Each item in the input Collection will be given to a single map() call as its key.
*/
public class CollectionInputFormat extends InputFormat<Writable, NullWritable> {
public static final String CONFKEY_COLLECTION = "collectioninputformat.collectionitems";
public static final String CONFKEY_VALCLASS = "collectioninputformat.valueclass";
/**
* Stores the given collection as a configuration value. When getSplits() runs later,
* it will be able to deserialize the collection and use it.
*/
public static <T extends Writable> void setCollection(Job job, Class<T> valueClass,
Collection<T> collection) throws IOException {
setCollection(job.getConfiguration(), valueClass, collection);
}
public static <T extends Writable> void setCollection(Configuration conf, Class<T> valueClass,
Collection<T> collection) throws IOException {
conf.set(CONFKEY_COLLECTION, toBase64(valueClass, collection));
conf.set(CONFKEY_VALCLASS, valueClass.getName());
}
public static <T extends Writable> String toBase64(Class<T> valueClass,
Collection<? extends Writable> collection) throws IOException {
DataOutputBuffer out = new DataOutputBuffer(); | // Path: src/main/java/com/urbanairship/datacube/backfill/CollectionWritable.java
// public class CollectionWritable implements Writable {
// private Collection<? extends Writable> collection;
// private Class<? extends Writable> elementClass;
//
// public CollectionWritable() { } // No-op constructor is required for deserializing
//
// public CollectionWritable(Class<? extends Writable> elementClass,
// Collection<? extends Writable> collection) {
// this.elementClass = elementClass;
// this.collection = collection;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public void readFields(DataInput in) throws IOException {
// try {
// String valueClassName = in.readUTF();
// elementClass = (Class<? extends Writable>)Class.forName(valueClassName);
// if(!Writable.class.isAssignableFrom(elementClass)) {
// throw new RuntimeException("valueClass is not writable: " + valueClassName);
// }
// int numElements = in.readInt();
// List<Writable> newList = new ArrayList<Writable>(numElements);
// for(int i=0; i<numElements; i++) {
// Writable instance = elementClass.newInstance();
// instance.readFields(in);
// newList.add(instance);
// }
// collection = newList;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// @Override
// public void write(DataOutput out) throws IOException {
// out.writeUTF(elementClass.getName());
// out.writeInt(collection.size());
// for(Writable writable: collection) {
// writable.write(out);
// }
// }
//
// public Collection<? extends Writable> getCollection() {
// return collection;
// }
// }
// Path: src/main/java/com/urbanairship/datacube/collectioninputformat/CollectionInputFormat.java
import com.urbanairship.datacube.backfill.CollectionWritable;
import org.apache.commons.codec.binary.Base64;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.DataInputBuffer;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.collectioninputformat;
/**
* A Hadoop InputFormat that lets you use an arbitrary Collection as input to a mapreduce job.
* Each item in the input Collection will be given to a single map() call as its key.
*/
public class CollectionInputFormat extends InputFormat<Writable, NullWritable> {
public static final String CONFKEY_COLLECTION = "collectioninputformat.collectionitems";
public static final String CONFKEY_VALCLASS = "collectioninputformat.valueclass";
/**
* Stores the given collection as a configuration value. When getSplits() runs later,
* it will be able to deserialize the collection and use it.
*/
public static <T extends Writable> void setCollection(Job job, Class<T> valueClass,
Collection<T> collection) throws IOException {
setCollection(job.getConfiguration(), valueClass, collection);
}
public static <T extends Writable> void setCollection(Configuration conf, Class<T> valueClass,
Collection<T> collection) throws IOException {
conf.set(CONFKEY_COLLECTION, toBase64(valueClass, collection));
conf.set(CONFKEY_VALCLASS, valueClass.getName());
}
public static <T extends Writable> String toBase64(Class<T> valueClass,
Collection<? extends Writable> collection) throws IOException {
DataOutputBuffer out = new DataOutputBuffer(); | new CollectionWritable(valueClass, collection).write(out); |
urbanairship/datacube | src/test/java/com/urbanairship/datacube/tweetcountexample/tests/TweetParseTest.java | // Path: src/test/java/com/urbanairship/datacube/tweetcountexample/Tweet.java
// public class Tweet {
// private static final Pattern hashtagPattern = Pattern.compile("#(\\w+)");
// private static final Pattern retweetFromPattern = Pattern.compile("RT @(\\w+)");
//
// public final DateTime time;
// public final String username;
// public final Optional<String> retweetedFrom;
// public final String text;
// public final Set<String> hashTags;
//
// public Tweet(String fileLine) {
// String[] tokens = fileLine.split("\\t");
//
// time = new DateTime(Date.parse(tokens[1]), DateTimeZone.UTC);
// username = tokens[2];
// text = tokens[3];
//
// hashTags = new HashSet<String>(0);
// Matcher hashtagMatcher = hashtagPattern.matcher(text);
// while (hashtagMatcher.find()) {
// hashTags.add(hashtagMatcher.group(1));
// }
//
// Matcher retweetMatcher = retweetFromPattern.matcher(text);
// if (retweetMatcher.find()) {
// retweetedFrom = Optional.of(retweetMatcher.group(1));
// } else {
// retweetedFrom = Optional.absent();
// }
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("(username:" + username);
// sb.append(", time:" + time);
// sb.append(", retweeted:" + retweetedFrom);
// sb.append(", text:" + text);
// sb.append(", hashtags:" + hashTags);
// sb.append(")");
// return sb.toString();
// }
// }
| import com.google.common.base.Optional;
import com.google.common.collect.Sets;
import com.urbanairship.datacube.tweetcountexample.Tweet;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Assert;
import org.junit.Test; | package com.urbanairship.datacube.tweetcountexample.tests;
public class TweetParseTest {
@Test
public void testParsing() {
String inputLine = "35720274552823808 Thu, 10 Feb 2011 15:22:31 +0000 iran88 RT @TehranBureau: As #Karroubi placed under house arrest after #25Bahman rally call, lead adviser detained. http://to.pbs.org/fsWae4 #Iran #IranElection"; | // Path: src/test/java/com/urbanairship/datacube/tweetcountexample/Tweet.java
// public class Tweet {
// private static final Pattern hashtagPattern = Pattern.compile("#(\\w+)");
// private static final Pattern retweetFromPattern = Pattern.compile("RT @(\\w+)");
//
// public final DateTime time;
// public final String username;
// public final Optional<String> retweetedFrom;
// public final String text;
// public final Set<String> hashTags;
//
// public Tweet(String fileLine) {
// String[] tokens = fileLine.split("\\t");
//
// time = new DateTime(Date.parse(tokens[1]), DateTimeZone.UTC);
// username = tokens[2];
// text = tokens[3];
//
// hashTags = new HashSet<String>(0);
// Matcher hashtagMatcher = hashtagPattern.matcher(text);
// while (hashtagMatcher.find()) {
// hashTags.add(hashtagMatcher.group(1));
// }
//
// Matcher retweetMatcher = retweetFromPattern.matcher(text);
// if (retweetMatcher.find()) {
// retweetedFrom = Optional.of(retweetMatcher.group(1));
// } else {
// retweetedFrom = Optional.absent();
// }
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("(username:" + username);
// sb.append(", time:" + time);
// sb.append(", retweeted:" + retweetedFrom);
// sb.append(", text:" + text);
// sb.append(", hashtags:" + hashTags);
// sb.append(")");
// return sb.toString();
// }
// }
// Path: src/test/java/com/urbanairship/datacube/tweetcountexample/tests/TweetParseTest.java
import com.google.common.base.Optional;
import com.google.common.collect.Sets;
import com.urbanairship.datacube.tweetcountexample.Tweet;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Assert;
import org.junit.Test;
package com.urbanairship.datacube.tweetcountexample.tests;
public class TweetParseTest {
@Test
public void testParsing() {
String inputLine = "35720274552823808 Thu, 10 Feb 2011 15:22:31 +0000 iran88 RT @TehranBureau: As #Karroubi placed under house arrest after #25Bahman rally call, lead adviser detained. http://to.pbs.org/fsWae4 #Iran #IranElection"; | Tweet tweet = new Tweet(inputLine); |
urbanairship/datacube | src/main/java/com/urbanairship/datacube/backfill/HBaseBackfill.java | // Path: src/main/java/com/urbanairship/datacube/Deserializer.java
// public interface Deserializer<O extends Op> {
// O fromBytes(byte[] bytes);
// }
| import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.ArrayUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.io.hfile.Compression.Algorithm;
import org.apache.hadoop.hbase.regionserver.StoreFile.BloomType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.urbanairship.datacube.Deserializer; | /*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.backfill;
public class HBaseBackfill implements Runnable {
private static final Logger log = LoggerFactory.getLogger(HBaseBackfill.class);
private final Configuration conf;
private final HBaseBackfillCallback backfillCallback;
private final byte[] liveDataTableName;
private final byte[] snapshotTableName;
private final byte[] backfillTableName;
private final byte[] cf; | // Path: src/main/java/com/urbanairship/datacube/Deserializer.java
// public interface Deserializer<O extends Op> {
// O fromBytes(byte[] bytes);
// }
// Path: src/main/java/com/urbanairship/datacube/backfill/HBaseBackfill.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.ArrayUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.io.hfile.Compression.Algorithm;
import org.apache.hadoop.hbase.regionserver.StoreFile.BloomType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.urbanairship.datacube.Deserializer;
/*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.backfill;
public class HBaseBackfill implements Runnable {
private static final Logger log = LoggerFactory.getLogger(HBaseBackfill.class);
private final Configuration conf;
private final HBaseBackfillCallback backfillCallback;
private final byte[] liveDataTableName;
private final byte[] snapshotTableName;
private final byte[] backfillTableName;
private final byte[] cf; | Class<? extends Deserializer<?>> opDeserializerCls; |
urbanairship/datacube | src/main/java/com/urbanairship/datacube/ops/DoubleOp.java | // Path: src/main/java/com/urbanairship/datacube/Deserializer.java
// public interface Deserializer<O extends Op> {
// O fromBytes(byte[] bytes);
// }
//
// Path: src/main/java/com/urbanairship/datacube/Op.java
// public interface Op extends CSerializable {
// /**
// * @return an Op that combines the effect of this and otherOp.
// */
// Op add(Op otherOp);
//
// /**
// * Return the difference between this op and the given one.
// *
// * This should satisfy the following property:
// * y + x.subtract(y) = x
// *
// * This holds for integers, e.g. 10 + (15 - 10) = 15
// *
// * An example using LongOp:
// * assert new LongOp(10).add(new LongOp(15).subtract(10).equals(15)
// */
// Op subtract(Op otherOp);
//
// /**
// * Subclasses must override equals() and hashCode().
// */
// @Override
// boolean equals(Object other);
//
// @Override
// int hashCode();
// }
//
// Path: src/main/java/com/urbanairship/datacube/Util.java
// public class Util {
// public static byte[] longToBytes(long l) {
// return ByteBuffer.allocate(8).putLong(l).array();
// }
//
// /**
// * Write a big-endian integer into the least significant bytes of a byte array.
// */
// public static byte[] intToBytesWithLen(int x, int len) {
// if(len <= 4) {
// return trailingBytes(intToBytes(x), len);
// } else {
// ByteBuffer bb = ByteBuffer.allocate(len);
// bb.position(len-4);
// bb.putInt(x);
// assert bb.remaining() == 0;
// return bb.array();
// }
// }
//
// public static long bytesToLong(byte[] bytes) {
// if(bytes.length < 8) {
// throw new IllegalArgumentException("Input array was too small: " +
// Arrays.toString(bytes));
// }
//
// return ByteBuffer.wrap(bytes).getLong();
// }
//
// /**
// * Call this if you have a byte array to convert to long, but your array might need
// * to be left-padded with zeros (if it is less than 8 bytes long).
// */
// public static long bytesToLongPad(byte[] bytes) {
// final int padZeros = Math.max(8-bytes.length, 0);
// ByteBuffer bb = ByteBuffer.allocate(8);
// for(int i=0; i<padZeros; i++) {
// bb.put((byte)0);
// }
// bb.put(bytes, 0, 8-padZeros);
// bb.flip();
// return bb.getLong();
// }
//
// public static byte[] intToBytes(int x) {
// ByteBuffer bb = ByteBuffer.allocate(4);
// bb.putInt(x);
// return bb.array();
// }
//
// public static int bytesToInt(byte[] bytes) {
// return ByteBuffer.wrap(bytes).getInt();
// }
//
// public static byte[] leastSignificantBytes(long l, int numBytes) {
// byte[] all8Bytes = Util.longToBytes(l);
// return trailingBytes(all8Bytes, numBytes);
// }
//
// public static byte[] trailingBytes(byte[] bs, int numBytes) {
// return Arrays.copyOfRange(bs, bs.length-numBytes, bs.length);
// }
//
// /**
// * A utility to allow hashing of a portion of an array without having to copy it.
// * @param array
// * @param startInclusive
// * @param endExclusive
// * @return hash byte
// */
// public static byte hashByteArray(byte[] array, int startInclusive, int endExclusive) {
// if (array == null) {
// return 0;
// }
//
// int range = endExclusive - startInclusive;
// if (range < 0) {
// throw new IllegalArgumentException(startInclusive + " > " + endExclusive);
// }
//
// int result = 1;
// for (int i=startInclusive; i<endExclusive; i++){
// result = 31 * result + array[i];
// }
//
// return (byte)result;
// }
//
// /**
// * Only use this for testing/debugging. Inefficient.
// */
// public static long countRows(Configuration conf, byte[] tableName) throws IOException {
// HTable hTable = null;
// ResultScanner rs = null;
// long count = 0;
// try {
// hTable = new HTable(conf, tableName);
// rs = hTable.getScanner(new Scan());
// for(@SuppressWarnings("unused") Result r: rs) {
// count++;
// }
// return count;
// } finally {
// if(hTable != null) {
// hTable.close();
// }
// if(rs != null) {
// rs.close();
// }
// }
// }
// }
| import com.urbanairship.datacube.Util;
import com.urbanairship.datacube.Deserializer;
import com.urbanairship.datacube.Op; | throw new RuntimeException();
}
return new DoubleOp(this.val - ((DoubleOp) otherOp).val);
}
@Override
public int hashCode() {
long temp = val != +0.0d ? Double.doubleToLongBits(val) : 0L;
return (int) (temp ^ (temp >>> 32));
}
/**
* Eclipse auto-generated
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DoubleOp other = (DoubleOp) obj;
if (val != other.val)
return false;
return true;
}
@Override
public byte[] serialize() { | // Path: src/main/java/com/urbanairship/datacube/Deserializer.java
// public interface Deserializer<O extends Op> {
// O fromBytes(byte[] bytes);
// }
//
// Path: src/main/java/com/urbanairship/datacube/Op.java
// public interface Op extends CSerializable {
// /**
// * @return an Op that combines the effect of this and otherOp.
// */
// Op add(Op otherOp);
//
// /**
// * Return the difference between this op and the given one.
// *
// * This should satisfy the following property:
// * y + x.subtract(y) = x
// *
// * This holds for integers, e.g. 10 + (15 - 10) = 15
// *
// * An example using LongOp:
// * assert new LongOp(10).add(new LongOp(15).subtract(10).equals(15)
// */
// Op subtract(Op otherOp);
//
// /**
// * Subclasses must override equals() and hashCode().
// */
// @Override
// boolean equals(Object other);
//
// @Override
// int hashCode();
// }
//
// Path: src/main/java/com/urbanairship/datacube/Util.java
// public class Util {
// public static byte[] longToBytes(long l) {
// return ByteBuffer.allocate(8).putLong(l).array();
// }
//
// /**
// * Write a big-endian integer into the least significant bytes of a byte array.
// */
// public static byte[] intToBytesWithLen(int x, int len) {
// if(len <= 4) {
// return trailingBytes(intToBytes(x), len);
// } else {
// ByteBuffer bb = ByteBuffer.allocate(len);
// bb.position(len-4);
// bb.putInt(x);
// assert bb.remaining() == 0;
// return bb.array();
// }
// }
//
// public static long bytesToLong(byte[] bytes) {
// if(bytes.length < 8) {
// throw new IllegalArgumentException("Input array was too small: " +
// Arrays.toString(bytes));
// }
//
// return ByteBuffer.wrap(bytes).getLong();
// }
//
// /**
// * Call this if you have a byte array to convert to long, but your array might need
// * to be left-padded with zeros (if it is less than 8 bytes long).
// */
// public static long bytesToLongPad(byte[] bytes) {
// final int padZeros = Math.max(8-bytes.length, 0);
// ByteBuffer bb = ByteBuffer.allocate(8);
// for(int i=0; i<padZeros; i++) {
// bb.put((byte)0);
// }
// bb.put(bytes, 0, 8-padZeros);
// bb.flip();
// return bb.getLong();
// }
//
// public static byte[] intToBytes(int x) {
// ByteBuffer bb = ByteBuffer.allocate(4);
// bb.putInt(x);
// return bb.array();
// }
//
// public static int bytesToInt(byte[] bytes) {
// return ByteBuffer.wrap(bytes).getInt();
// }
//
// public static byte[] leastSignificantBytes(long l, int numBytes) {
// byte[] all8Bytes = Util.longToBytes(l);
// return trailingBytes(all8Bytes, numBytes);
// }
//
// public static byte[] trailingBytes(byte[] bs, int numBytes) {
// return Arrays.copyOfRange(bs, bs.length-numBytes, bs.length);
// }
//
// /**
// * A utility to allow hashing of a portion of an array without having to copy it.
// * @param array
// * @param startInclusive
// * @param endExclusive
// * @return hash byte
// */
// public static byte hashByteArray(byte[] array, int startInclusive, int endExclusive) {
// if (array == null) {
// return 0;
// }
//
// int range = endExclusive - startInclusive;
// if (range < 0) {
// throw new IllegalArgumentException(startInclusive + " > " + endExclusive);
// }
//
// int result = 1;
// for (int i=startInclusive; i<endExclusive; i++){
// result = 31 * result + array[i];
// }
//
// return (byte)result;
// }
//
// /**
// * Only use this for testing/debugging. Inefficient.
// */
// public static long countRows(Configuration conf, byte[] tableName) throws IOException {
// HTable hTable = null;
// ResultScanner rs = null;
// long count = 0;
// try {
// hTable = new HTable(conf, tableName);
// rs = hTable.getScanner(new Scan());
// for(@SuppressWarnings("unused") Result r: rs) {
// count++;
// }
// return count;
// } finally {
// if(hTable != null) {
// hTable.close();
// }
// if(rs != null) {
// rs.close();
// }
// }
// }
// }
// Path: src/main/java/com/urbanairship/datacube/ops/DoubleOp.java
import com.urbanairship.datacube.Util;
import com.urbanairship.datacube.Deserializer;
import com.urbanairship.datacube.Op;
throw new RuntimeException();
}
return new DoubleOp(this.val - ((DoubleOp) otherOp).val);
}
@Override
public int hashCode() {
long temp = val != +0.0d ? Double.doubleToLongBits(val) : 0L;
return (int) (temp ^ (temp >>> 32));
}
/**
* Eclipse auto-generated
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DoubleOp other = (DoubleOp) obj;
if (val != other.val)
return false;
return true;
}
@Override
public byte[] serialize() { | return Util.longToBytes(Double.doubleToRawLongBits(val)); |
urbanairship/datacube | src/main/java/com/urbanairship/datacube/ops/DoubleOp.java | // Path: src/main/java/com/urbanairship/datacube/Deserializer.java
// public interface Deserializer<O extends Op> {
// O fromBytes(byte[] bytes);
// }
//
// Path: src/main/java/com/urbanairship/datacube/Op.java
// public interface Op extends CSerializable {
// /**
// * @return an Op that combines the effect of this and otherOp.
// */
// Op add(Op otherOp);
//
// /**
// * Return the difference between this op and the given one.
// *
// * This should satisfy the following property:
// * y + x.subtract(y) = x
// *
// * This holds for integers, e.g. 10 + (15 - 10) = 15
// *
// * An example using LongOp:
// * assert new LongOp(10).add(new LongOp(15).subtract(10).equals(15)
// */
// Op subtract(Op otherOp);
//
// /**
// * Subclasses must override equals() and hashCode().
// */
// @Override
// boolean equals(Object other);
//
// @Override
// int hashCode();
// }
//
// Path: src/main/java/com/urbanairship/datacube/Util.java
// public class Util {
// public static byte[] longToBytes(long l) {
// return ByteBuffer.allocate(8).putLong(l).array();
// }
//
// /**
// * Write a big-endian integer into the least significant bytes of a byte array.
// */
// public static byte[] intToBytesWithLen(int x, int len) {
// if(len <= 4) {
// return trailingBytes(intToBytes(x), len);
// } else {
// ByteBuffer bb = ByteBuffer.allocate(len);
// bb.position(len-4);
// bb.putInt(x);
// assert bb.remaining() == 0;
// return bb.array();
// }
// }
//
// public static long bytesToLong(byte[] bytes) {
// if(bytes.length < 8) {
// throw new IllegalArgumentException("Input array was too small: " +
// Arrays.toString(bytes));
// }
//
// return ByteBuffer.wrap(bytes).getLong();
// }
//
// /**
// * Call this if you have a byte array to convert to long, but your array might need
// * to be left-padded with zeros (if it is less than 8 bytes long).
// */
// public static long bytesToLongPad(byte[] bytes) {
// final int padZeros = Math.max(8-bytes.length, 0);
// ByteBuffer bb = ByteBuffer.allocate(8);
// for(int i=0; i<padZeros; i++) {
// bb.put((byte)0);
// }
// bb.put(bytes, 0, 8-padZeros);
// bb.flip();
// return bb.getLong();
// }
//
// public static byte[] intToBytes(int x) {
// ByteBuffer bb = ByteBuffer.allocate(4);
// bb.putInt(x);
// return bb.array();
// }
//
// public static int bytesToInt(byte[] bytes) {
// return ByteBuffer.wrap(bytes).getInt();
// }
//
// public static byte[] leastSignificantBytes(long l, int numBytes) {
// byte[] all8Bytes = Util.longToBytes(l);
// return trailingBytes(all8Bytes, numBytes);
// }
//
// public static byte[] trailingBytes(byte[] bs, int numBytes) {
// return Arrays.copyOfRange(bs, bs.length-numBytes, bs.length);
// }
//
// /**
// * A utility to allow hashing of a portion of an array without having to copy it.
// * @param array
// * @param startInclusive
// * @param endExclusive
// * @return hash byte
// */
// public static byte hashByteArray(byte[] array, int startInclusive, int endExclusive) {
// if (array == null) {
// return 0;
// }
//
// int range = endExclusive - startInclusive;
// if (range < 0) {
// throw new IllegalArgumentException(startInclusive + " > " + endExclusive);
// }
//
// int result = 1;
// for (int i=startInclusive; i<endExclusive; i++){
// result = 31 * result + array[i];
// }
//
// return (byte)result;
// }
//
// /**
// * Only use this for testing/debugging. Inefficient.
// */
// public static long countRows(Configuration conf, byte[] tableName) throws IOException {
// HTable hTable = null;
// ResultScanner rs = null;
// long count = 0;
// try {
// hTable = new HTable(conf, tableName);
// rs = hTable.getScanner(new Scan());
// for(@SuppressWarnings("unused") Result r: rs) {
// count++;
// }
// return count;
// } finally {
// if(hTable != null) {
// hTable.close();
// }
// if(rs != null) {
// rs.close();
// }
// }
// }
// }
| import com.urbanairship.datacube.Util;
import com.urbanairship.datacube.Deserializer;
import com.urbanairship.datacube.Op; | }
@Override
public int hashCode() {
long temp = val != +0.0d ? Double.doubleToLongBits(val) : 0L;
return (int) (temp ^ (temp >>> 32));
}
/**
* Eclipse auto-generated
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DoubleOp other = (DoubleOp) obj;
if (val != other.val)
return false;
return true;
}
@Override
public byte[] serialize() {
return Util.longToBytes(Double.doubleToRawLongBits(val));
}
| // Path: src/main/java/com/urbanairship/datacube/Deserializer.java
// public interface Deserializer<O extends Op> {
// O fromBytes(byte[] bytes);
// }
//
// Path: src/main/java/com/urbanairship/datacube/Op.java
// public interface Op extends CSerializable {
// /**
// * @return an Op that combines the effect of this and otherOp.
// */
// Op add(Op otherOp);
//
// /**
// * Return the difference between this op and the given one.
// *
// * This should satisfy the following property:
// * y + x.subtract(y) = x
// *
// * This holds for integers, e.g. 10 + (15 - 10) = 15
// *
// * An example using LongOp:
// * assert new LongOp(10).add(new LongOp(15).subtract(10).equals(15)
// */
// Op subtract(Op otherOp);
//
// /**
// * Subclasses must override equals() and hashCode().
// */
// @Override
// boolean equals(Object other);
//
// @Override
// int hashCode();
// }
//
// Path: src/main/java/com/urbanairship/datacube/Util.java
// public class Util {
// public static byte[] longToBytes(long l) {
// return ByteBuffer.allocate(8).putLong(l).array();
// }
//
// /**
// * Write a big-endian integer into the least significant bytes of a byte array.
// */
// public static byte[] intToBytesWithLen(int x, int len) {
// if(len <= 4) {
// return trailingBytes(intToBytes(x), len);
// } else {
// ByteBuffer bb = ByteBuffer.allocate(len);
// bb.position(len-4);
// bb.putInt(x);
// assert bb.remaining() == 0;
// return bb.array();
// }
// }
//
// public static long bytesToLong(byte[] bytes) {
// if(bytes.length < 8) {
// throw new IllegalArgumentException("Input array was too small: " +
// Arrays.toString(bytes));
// }
//
// return ByteBuffer.wrap(bytes).getLong();
// }
//
// /**
// * Call this if you have a byte array to convert to long, but your array might need
// * to be left-padded with zeros (if it is less than 8 bytes long).
// */
// public static long bytesToLongPad(byte[] bytes) {
// final int padZeros = Math.max(8-bytes.length, 0);
// ByteBuffer bb = ByteBuffer.allocate(8);
// for(int i=0; i<padZeros; i++) {
// bb.put((byte)0);
// }
// bb.put(bytes, 0, 8-padZeros);
// bb.flip();
// return bb.getLong();
// }
//
// public static byte[] intToBytes(int x) {
// ByteBuffer bb = ByteBuffer.allocate(4);
// bb.putInt(x);
// return bb.array();
// }
//
// public static int bytesToInt(byte[] bytes) {
// return ByteBuffer.wrap(bytes).getInt();
// }
//
// public static byte[] leastSignificantBytes(long l, int numBytes) {
// byte[] all8Bytes = Util.longToBytes(l);
// return trailingBytes(all8Bytes, numBytes);
// }
//
// public static byte[] trailingBytes(byte[] bs, int numBytes) {
// return Arrays.copyOfRange(bs, bs.length-numBytes, bs.length);
// }
//
// /**
// * A utility to allow hashing of a portion of an array without having to copy it.
// * @param array
// * @param startInclusive
// * @param endExclusive
// * @return hash byte
// */
// public static byte hashByteArray(byte[] array, int startInclusive, int endExclusive) {
// if (array == null) {
// return 0;
// }
//
// int range = endExclusive - startInclusive;
// if (range < 0) {
// throw new IllegalArgumentException(startInclusive + " > " + endExclusive);
// }
//
// int result = 1;
// for (int i=startInclusive; i<endExclusive; i++){
// result = 31 * result + array[i];
// }
//
// return (byte)result;
// }
//
// /**
// * Only use this for testing/debugging. Inefficient.
// */
// public static long countRows(Configuration conf, byte[] tableName) throws IOException {
// HTable hTable = null;
// ResultScanner rs = null;
// long count = 0;
// try {
// hTable = new HTable(conf, tableName);
// rs = hTable.getScanner(new Scan());
// for(@SuppressWarnings("unused") Result r: rs) {
// count++;
// }
// return count;
// } finally {
// if(hTable != null) {
// hTable.close();
// }
// if(rs != null) {
// rs.close();
// }
// }
// }
// }
// Path: src/main/java/com/urbanairship/datacube/ops/DoubleOp.java
import com.urbanairship.datacube.Util;
import com.urbanairship.datacube.Deserializer;
import com.urbanairship.datacube.Op;
}
@Override
public int hashCode() {
long temp = val != +0.0d ? Double.doubleToLongBits(val) : 0L;
return (int) (temp ^ (temp >>> 32));
}
/**
* Eclipse auto-generated
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DoubleOp other = (DoubleOp) obj;
if (val != other.val)
return false;
return true;
}
@Override
public byte[] serialize() {
return Util.longToBytes(Double.doubleToRawLongBits(val));
}
| public static class DoubleOpDeserializer implements Deserializer<DoubleOp> { |
urbanairship/datacube | src/main/java/com/urbanairship/datacube/bucketers/HourDayMonthBucketer.java | // Path: src/main/java/com/urbanairship/datacube/BucketType.java
// public class BucketType {
// public static final BucketType IDENTITY = new BucketType("nobucket", new byte[]{});
// public static final BucketType WILDCARD = new BucketType("wildcard", new byte[]{});
//
// private final String nameInErrMsgs;
// private final byte[] uniqueId;
//
// public BucketType(String nameInErrMsgs, byte[] uniqueId) {
// this.nameInErrMsgs = nameInErrMsgs;
// this.uniqueId = uniqueId;
// }
//
// public byte[] getUniqueId() {
// return uniqueId;
// }
//
// public String getNameInErrMsgs() {
// return nameInErrMsgs;
// }
//
// public String toString() {
// return nameInErrMsgs;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof BucketType)) return false;
// BucketType that = (BucketType) o;
// return Objects.equals(nameInErrMsgs, that.nameInErrMsgs) &&
// Arrays.equals(uniqueId, that.uniqueId);
// }
//
// @Override
// public int hashCode() {
//
// int result = Objects.hash(nameInErrMsgs);
// result = 31 * result + Arrays.hashCode(uniqueId);
// return result;
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/Bucketer.java
// public interface Bucketer<F> {
// /**
// * When writing to the cube at some address, the address will have one coordinate for each
// * dimension in the cube, for example (time: 348524388, location: portland). For each
// * dimension, for each bucket type within that dimension, the bucketer must transform the
// * input data into the bucket that should be used to store the data.
// */
// SetMultimap<BucketType, CSerializable> bucketForWrite(F coordinate);
//
// /**
// * When reading from the cube, the reader specifies some coordinates from which to read.
// * The bucketer can choose which cube coordinates to read from based on these input
// * coordinates. For example, if the reader asks for hourly counts (the Hourly BucketType) and
// * passes a timestamp, the bucketer could return the timestamp rounded down to the hour floor.
// */
// CSerializable bucketForRead(Object coordinate, BucketType bucketType);
//
// /**
// * Return all bucket types that exist in this dimension.
// */
// List<BucketType> getBucketTypes();
//
//
// /**
// * This identity/no-op bucketer class is implicitly used for dimensions that don't choose a
// * bucketer.
// */
// class IdentityBucketer implements Bucketer<CSerializable> {
// private final List<BucketType> bucketTypes = ImmutableList.of(BucketType.IDENTITY);
//
// @Override
// public SetMultimap<BucketType, CSerializable> bucketForWrite(CSerializable coordinate) {
// return ImmutableSetMultimap.of(BucketType.IDENTITY, coordinate);
// }
//
// @Override
// public CSerializable bucketForRead(Object coordinateField, BucketType bucketType) {
// return (CSerializable) coordinateField;
// }
//
// @Override
// public List<BucketType> getBucketTypes() {
// return bucketTypes;
// }
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
| import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.SetMultimap;
import com.urbanairship.datacube.BucketType;
import com.urbanairship.datacube.Bucketer;
import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.serializables.LongSerializable;
import org.joda.time.DateTime;
import java.util.List;
import java.util.Set; | /*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.bucketers;
public class HourDayMonthBucketer implements Bucketer<DateTime> {
public static final BucketType hours = new BucketType("hour", new byte[]{1});
public static final BucketType days = new BucketType("day", new byte[]{2});
public static final BucketType months = new BucketType("month", new byte[]{3});
public static final BucketType years = new BucketType("year", new byte[]{4});
public static final BucketType weeks = new BucketType("weeks", new byte[]{5});
static final Set<BucketType> ALL_BUCKET_TYPES = ImmutableSet.<BucketType>builder().
add(hours).add(days).add(months).add(years).add(weeks).build();
private final List<BucketType> bucketTypes;
// TODO move this class to TimeBucker and have HourDayMonthBucketer be a subclass that
// just calls super(ImmutableList.of(hours, days, months))
public HourDayMonthBucketer() {
this(ImmutableList.of(hours, days, months));
}
public HourDayMonthBucketer(List<BucketType> bucketTypes) {
this.bucketTypes = ImmutableList.copyOf(bucketTypes); // defensive copy
for (BucketType bucketType : bucketTypes) {
if (!ALL_BUCKET_TYPES.contains(bucketType)) {
throw new IllegalArgumentException("Invalid bucket type " + bucketType +
", expected one of " + ALL_BUCKET_TYPES);
}
}
}
@Override | // Path: src/main/java/com/urbanairship/datacube/BucketType.java
// public class BucketType {
// public static final BucketType IDENTITY = new BucketType("nobucket", new byte[]{});
// public static final BucketType WILDCARD = new BucketType("wildcard", new byte[]{});
//
// private final String nameInErrMsgs;
// private final byte[] uniqueId;
//
// public BucketType(String nameInErrMsgs, byte[] uniqueId) {
// this.nameInErrMsgs = nameInErrMsgs;
// this.uniqueId = uniqueId;
// }
//
// public byte[] getUniqueId() {
// return uniqueId;
// }
//
// public String getNameInErrMsgs() {
// return nameInErrMsgs;
// }
//
// public String toString() {
// return nameInErrMsgs;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof BucketType)) return false;
// BucketType that = (BucketType) o;
// return Objects.equals(nameInErrMsgs, that.nameInErrMsgs) &&
// Arrays.equals(uniqueId, that.uniqueId);
// }
//
// @Override
// public int hashCode() {
//
// int result = Objects.hash(nameInErrMsgs);
// result = 31 * result + Arrays.hashCode(uniqueId);
// return result;
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/Bucketer.java
// public interface Bucketer<F> {
// /**
// * When writing to the cube at some address, the address will have one coordinate for each
// * dimension in the cube, for example (time: 348524388, location: portland). For each
// * dimension, for each bucket type within that dimension, the bucketer must transform the
// * input data into the bucket that should be used to store the data.
// */
// SetMultimap<BucketType, CSerializable> bucketForWrite(F coordinate);
//
// /**
// * When reading from the cube, the reader specifies some coordinates from which to read.
// * The bucketer can choose which cube coordinates to read from based on these input
// * coordinates. For example, if the reader asks for hourly counts (the Hourly BucketType) and
// * passes a timestamp, the bucketer could return the timestamp rounded down to the hour floor.
// */
// CSerializable bucketForRead(Object coordinate, BucketType bucketType);
//
// /**
// * Return all bucket types that exist in this dimension.
// */
// List<BucketType> getBucketTypes();
//
//
// /**
// * This identity/no-op bucketer class is implicitly used for dimensions that don't choose a
// * bucketer.
// */
// class IdentityBucketer implements Bucketer<CSerializable> {
// private final List<BucketType> bucketTypes = ImmutableList.of(BucketType.IDENTITY);
//
// @Override
// public SetMultimap<BucketType, CSerializable> bucketForWrite(CSerializable coordinate) {
// return ImmutableSetMultimap.of(BucketType.IDENTITY, coordinate);
// }
//
// @Override
// public CSerializable bucketForRead(Object coordinateField, BucketType bucketType) {
// return (CSerializable) coordinateField;
// }
//
// @Override
// public List<BucketType> getBucketTypes() {
// return bucketTypes;
// }
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
// Path: src/main/java/com/urbanairship/datacube/bucketers/HourDayMonthBucketer.java
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.SetMultimap;
import com.urbanairship.datacube.BucketType;
import com.urbanairship.datacube.Bucketer;
import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.serializables.LongSerializable;
import org.joda.time.DateTime;
import java.util.List;
import java.util.Set;
/*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.bucketers;
public class HourDayMonthBucketer implements Bucketer<DateTime> {
public static final BucketType hours = new BucketType("hour", new byte[]{1});
public static final BucketType days = new BucketType("day", new byte[]{2});
public static final BucketType months = new BucketType("month", new byte[]{3});
public static final BucketType years = new BucketType("year", new byte[]{4});
public static final BucketType weeks = new BucketType("weeks", new byte[]{5});
static final Set<BucketType> ALL_BUCKET_TYPES = ImmutableSet.<BucketType>builder().
add(hours).add(days).add(months).add(years).add(weeks).build();
private final List<BucketType> bucketTypes;
// TODO move this class to TimeBucker and have HourDayMonthBucketer be a subclass that
// just calls super(ImmutableList.of(hours, days, months))
public HourDayMonthBucketer() {
this(ImmutableList.of(hours, days, months));
}
public HourDayMonthBucketer(List<BucketType> bucketTypes) {
this.bucketTypes = ImmutableList.copyOf(bucketTypes); // defensive copy
for (BucketType bucketType : bucketTypes) {
if (!ALL_BUCKET_TYPES.contains(bucketType)) {
throw new IllegalArgumentException("Invalid bucket type " + bucketType +
", expected one of " + ALL_BUCKET_TYPES);
}
}
}
@Override | public SetMultimap<BucketType, CSerializable> bucketForWrite( |
urbanairship/datacube | src/main/java/com/urbanairship/datacube/dbharnesses/HbaseDbHarnessConfiguration.java | // Path: src/main/java/com/urbanairship/datacube/DbHarness.java
// public interface DbHarness<T extends Op> {
// /**
// * Apply some ops to the database, combining them with ops that might already be stored there.
// * The passed batch will be modified by runBatch() to remove all ops that were successfully
// * stored, so the batch will be empty when this function returns if there was no IOException.
// * If this function throws IOException, the batch will contain one or more ops that were not
// * successfully applied to the DB.
// *
// * This is asynchronous, meaning that the given batch will probably be executed soon, but not
// * necessarily by the time this function returns.
// *
// * @throws AsyncException if the DbHarness is in a bad state as a result of an earlier
// * RuntimeException and will not accept any more batches. See {@link AsyncException} for
// * more info.
// * @throws FullQueueException if the queue of pending batches to be flushed is full, and no more
// * batches can be accepted right now. The caller can retry soon.
// */
// Future<?> runBatchAsync(Batch<T> batch, AfterExecute<T> afterExecute) throws FullQueueException;
//
// /**
// * @return absent if the bucket doesn't exist, or the bucket if it does.
// *
// * @throws InterruptedException
// */
// Optional<T> get(Address c) throws IOException, InterruptedException;
//
// /**
// * Overwrite value.
// *
// * @throws IOException
// * @throws InterruptedException
// */
// void set(Address c, T op) throws IOException, InterruptedException;
//
// List<Optional<T>> multiGet(List<Address> addresses) throws IOException, InterruptedException;
//
// /**
// * A hook for shutting down any internal threads during orderly shutdown. The default implementation simply calls
// * {@link #flush}
// *
// * @throws Exception
// */
// default void shutdown() throws IOException, InterruptedException {
// flush();
// }
//
// /**
// * When it's time to write a batch to the database, there are a couple of ways it can
// * be done.
// *
// * READ_COMBINE_CAS: read the existing cell value from the database, deserialize
// * it into an Op, combine it with the Op to be written, and write the combined Op back
// * to the database using a compare-and-swap operation to make sure it hasn't changed
// * since we read it. If the CAS fails because the cell value was concurrently modifed by
// * someone else, start over at the beginning and re-read the value.
// *
// * INCREMENT: for numeric values like counters, if the database supports server side
// * incrementing, the serialized Op will be passed as the amount to be incremented. This
// * means that no reads or combines will be done in the client (the harness code).
// *
// * OVERWRITE: without reading from the database, overwrite the cell value with the value
// * from the batch in memory. This will wipe out the existing count, so don't use this
// * unless you're sure you know what you're doing.
// */
// enum CommitType {
// READ_COMBINE_CAS,
// INCREMENT,
// OVERWRITE
// }
//
// /**
// * Wait until all currently outstanding writes have been written to the DB. or failed.
// */
// void flush() throws InterruptedException;
// }
| import com.google.common.base.Preconditions;
import com.urbanairship.datacube.DbHarness; | package com.urbanairship.datacube.dbharnesses;
public class HbaseDbHarnessConfiguration {
/**
* Your unique cube name, gets appended to the front of the key.
*/
public final byte[] uniqueCubeName;
/**
* The hbase table name that stores the cube
*/
public final byte[] tableName;
/**
* The hbase column family in which counts are stored
*/
public final byte[] cf;
| // Path: src/main/java/com/urbanairship/datacube/DbHarness.java
// public interface DbHarness<T extends Op> {
// /**
// * Apply some ops to the database, combining them with ops that might already be stored there.
// * The passed batch will be modified by runBatch() to remove all ops that were successfully
// * stored, so the batch will be empty when this function returns if there was no IOException.
// * If this function throws IOException, the batch will contain one or more ops that were not
// * successfully applied to the DB.
// *
// * This is asynchronous, meaning that the given batch will probably be executed soon, but not
// * necessarily by the time this function returns.
// *
// * @throws AsyncException if the DbHarness is in a bad state as a result of an earlier
// * RuntimeException and will not accept any more batches. See {@link AsyncException} for
// * more info.
// * @throws FullQueueException if the queue of pending batches to be flushed is full, and no more
// * batches can be accepted right now. The caller can retry soon.
// */
// Future<?> runBatchAsync(Batch<T> batch, AfterExecute<T> afterExecute) throws FullQueueException;
//
// /**
// * @return absent if the bucket doesn't exist, or the bucket if it does.
// *
// * @throws InterruptedException
// */
// Optional<T> get(Address c) throws IOException, InterruptedException;
//
// /**
// * Overwrite value.
// *
// * @throws IOException
// * @throws InterruptedException
// */
// void set(Address c, T op) throws IOException, InterruptedException;
//
// List<Optional<T>> multiGet(List<Address> addresses) throws IOException, InterruptedException;
//
// /**
// * A hook for shutting down any internal threads during orderly shutdown. The default implementation simply calls
// * {@link #flush}
// *
// * @throws Exception
// */
// default void shutdown() throws IOException, InterruptedException {
// flush();
// }
//
// /**
// * When it's time to write a batch to the database, there are a couple of ways it can
// * be done.
// *
// * READ_COMBINE_CAS: read the existing cell value from the database, deserialize
// * it into an Op, combine it with the Op to be written, and write the combined Op back
// * to the database using a compare-and-swap operation to make sure it hasn't changed
// * since we read it. If the CAS fails because the cell value was concurrently modifed by
// * someone else, start over at the beginning and re-read the value.
// *
// * INCREMENT: for numeric values like counters, if the database supports server side
// * incrementing, the serialized Op will be passed as the amount to be incremented. This
// * means that no reads or combines will be done in the client (the harness code).
// *
// * OVERWRITE: without reading from the database, overwrite the cell value with the value
// * from the batch in memory. This will wipe out the existing count, so don't use this
// * unless you're sure you know what you're doing.
// */
// enum CommitType {
// READ_COMBINE_CAS,
// INCREMENT,
// OVERWRITE
// }
//
// /**
// * Wait until all currently outstanding writes have been written to the DB. or failed.
// */
// void flush() throws InterruptedException;
// }
// Path: src/main/java/com/urbanairship/datacube/dbharnesses/HbaseDbHarnessConfiguration.java
import com.google.common.base.Preconditions;
import com.urbanairship.datacube.DbHarness;
package com.urbanairship.datacube.dbharnesses;
public class HbaseDbHarnessConfiguration {
/**
* Your unique cube name, gets appended to the front of the key.
*/
public final byte[] uniqueCubeName;
/**
* The hbase table name that stores the cube
*/
public final byte[] tableName;
/**
* The hbase column family in which counts are stored
*/
public final byte[] cf;
| public final DbHarness.CommitType commitType; |
urbanairship/datacube | src/main/java/com/urbanairship/datacube/bucketers/BigEndianIntBucketer.java | // Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
| import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.serializables.IntSerializable; | /*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.bucketers;
/**
* You can use this when one of your dimension coordinate types is a straightforward Integer.
*/
public class BigEndianIntBucketer extends AbstractIdentityBucketer<Integer> {
@Override | // Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
// Path: src/main/java/com/urbanairship/datacube/bucketers/BigEndianIntBucketer.java
import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.serializables.IntSerializable;
/*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.bucketers;
/**
* You can use this when one of your dimension coordinate types is a straightforward Integer.
*/
public class BigEndianIntBucketer extends AbstractIdentityBucketer<Integer> {
@Override | public CSerializable makeSerializable(Integer coord) { |
urbanairship/datacube | src/main/java/com/urbanairship/datacube/bucketers/BooleanBucketer.java | // Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
//
// Path: src/main/java/com/urbanairship/datacube/serializables/BooleanSerializable.java
// public class BooleanSerializable implements CSerializable {
// private final boolean bool;
// private static final byte[] FALSE_SERIAL = new byte[]{0};
// private static final byte[] TRUE_SERIAL = new byte[]{1};
//
// public BooleanSerializable(boolean bool) {
// this.bool = bool;
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(bool);
// }
//
// public static byte[] staticSerialize(boolean b) {
// if (b) {
// return TRUE_SERIAL;
// } else {
// return FALSE_SERIAL;
// }
// }
// }
| import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.serializables.BooleanSerializable; | /*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.bucketers;
/**
* BooleanBucketer
* You can use this bucketer for cases where:
* - You have a cube coordinate that is boolean
* - You want to store that boolean as a byte[0] for false or a byte[1] for true.
*/
public class BooleanBucketer extends AbstractIdentityBucketer<Boolean> {
private static final BooleanBucketer instance = new BooleanBucketer();
@Override | // Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
//
// Path: src/main/java/com/urbanairship/datacube/serializables/BooleanSerializable.java
// public class BooleanSerializable implements CSerializable {
// private final boolean bool;
// private static final byte[] FALSE_SERIAL = new byte[]{0};
// private static final byte[] TRUE_SERIAL = new byte[]{1};
//
// public BooleanSerializable(boolean bool) {
// this.bool = bool;
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(bool);
// }
//
// public static byte[] staticSerialize(boolean b) {
// if (b) {
// return TRUE_SERIAL;
// } else {
// return FALSE_SERIAL;
// }
// }
// }
// Path: src/main/java/com/urbanairship/datacube/bucketers/BooleanBucketer.java
import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.serializables.BooleanSerializable;
/*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.bucketers;
/**
* BooleanBucketer
* You can use this bucketer for cases where:
* - You have a cube coordinate that is boolean
* - You want to store that boolean as a byte[0] for false or a byte[1] for true.
*/
public class BooleanBucketer extends AbstractIdentityBucketer<Boolean> {
private static final BooleanBucketer instance = new BooleanBucketer();
@Override | public CSerializable makeSerializable(Boolean coordinateField) { |
urbanairship/datacube | src/main/java/com/urbanairship/datacube/bucketers/BooleanBucketer.java | // Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
//
// Path: src/main/java/com/urbanairship/datacube/serializables/BooleanSerializable.java
// public class BooleanSerializable implements CSerializable {
// private final boolean bool;
// private static final byte[] FALSE_SERIAL = new byte[]{0};
// private static final byte[] TRUE_SERIAL = new byte[]{1};
//
// public BooleanSerializable(boolean bool) {
// this.bool = bool;
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(bool);
// }
//
// public static byte[] staticSerialize(boolean b) {
// if (b) {
// return TRUE_SERIAL;
// } else {
// return FALSE_SERIAL;
// }
// }
// }
| import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.serializables.BooleanSerializable; | /*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.bucketers;
/**
* BooleanBucketer
* You can use this bucketer for cases where:
* - You have a cube coordinate that is boolean
* - You want to store that boolean as a byte[0] for false or a byte[1] for true.
*/
public class BooleanBucketer extends AbstractIdentityBucketer<Boolean> {
private static final BooleanBucketer instance = new BooleanBucketer();
@Override
public CSerializable makeSerializable(Boolean coordinateField) { | // Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
//
// Path: src/main/java/com/urbanairship/datacube/serializables/BooleanSerializable.java
// public class BooleanSerializable implements CSerializable {
// private final boolean bool;
// private static final byte[] FALSE_SERIAL = new byte[]{0};
// private static final byte[] TRUE_SERIAL = new byte[]{1};
//
// public BooleanSerializable(boolean bool) {
// this.bool = bool;
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(bool);
// }
//
// public static byte[] staticSerialize(boolean b) {
// if (b) {
// return TRUE_SERIAL;
// } else {
// return FALSE_SERIAL;
// }
// }
// }
// Path: src/main/java/com/urbanairship/datacube/bucketers/BooleanBucketer.java
import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.serializables.BooleanSerializable;
/*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.bucketers;
/**
* BooleanBucketer
* You can use this bucketer for cases where:
* - You have a cube coordinate that is boolean
* - You want to store that boolean as a byte[0] for false or a byte[1] for true.
*/
public class BooleanBucketer extends AbstractIdentityBucketer<Boolean> {
private static final BooleanBucketer instance = new BooleanBucketer();
@Override
public CSerializable makeSerializable(Boolean coordinateField) { | return new BooleanSerializable(coordinateField); |
urbanairship/datacube | src/main/java/com/urbanairship/datacube/bucketers/TagsBucketer.java | // Path: src/main/java/com/urbanairship/datacube/BucketType.java
// public class BucketType {
// public static final BucketType IDENTITY = new BucketType("nobucket", new byte[]{});
// public static final BucketType WILDCARD = new BucketType("wildcard", new byte[]{});
//
// private final String nameInErrMsgs;
// private final byte[] uniqueId;
//
// public BucketType(String nameInErrMsgs, byte[] uniqueId) {
// this.nameInErrMsgs = nameInErrMsgs;
// this.uniqueId = uniqueId;
// }
//
// public byte[] getUniqueId() {
// return uniqueId;
// }
//
// public String getNameInErrMsgs() {
// return nameInErrMsgs;
// }
//
// public String toString() {
// return nameInErrMsgs;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof BucketType)) return false;
// BucketType that = (BucketType) o;
// return Objects.equals(nameInErrMsgs, that.nameInErrMsgs) &&
// Arrays.equals(uniqueId, that.uniqueId);
// }
//
// @Override
// public int hashCode() {
//
// int result = Objects.hash(nameInErrMsgs);
// result = 31 * result + Arrays.hashCode(uniqueId);
// return result;
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/Bucketer.java
// public interface Bucketer<F> {
// /**
// * When writing to the cube at some address, the address will have one coordinate for each
// * dimension in the cube, for example (time: 348524388, location: portland). For each
// * dimension, for each bucket type within that dimension, the bucketer must transform the
// * input data into the bucket that should be used to store the data.
// */
// SetMultimap<BucketType, CSerializable> bucketForWrite(F coordinate);
//
// /**
// * When reading from the cube, the reader specifies some coordinates from which to read.
// * The bucketer can choose which cube coordinates to read from based on these input
// * coordinates. For example, if the reader asks for hourly counts (the Hourly BucketType) and
// * passes a timestamp, the bucketer could return the timestamp rounded down to the hour floor.
// */
// CSerializable bucketForRead(Object coordinate, BucketType bucketType);
//
// /**
// * Return all bucket types that exist in this dimension.
// */
// List<BucketType> getBucketTypes();
//
//
// /**
// * This identity/no-op bucketer class is implicitly used for dimensions that don't choose a
// * bucketer.
// */
// class IdentityBucketer implements Bucketer<CSerializable> {
// private final List<BucketType> bucketTypes = ImmutableList.of(BucketType.IDENTITY);
//
// @Override
// public SetMultimap<BucketType, CSerializable> bucketForWrite(CSerializable coordinate) {
// return ImmutableSetMultimap.of(BucketType.IDENTITY, coordinate);
// }
//
// @Override
// public CSerializable bucketForRead(Object coordinateField, BucketType bucketType) {
// return (CSerializable) coordinateField;
// }
//
// @Override
// public List<BucketType> getBucketTypes() {
// return bucketTypes;
// }
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
//
// Path: src/main/java/com/urbanairship/datacube/serializables/StringSerializable.java
// public class StringSerializable implements CSerializable {
// private final String s;
//
// public StringSerializable(String s) {
// this.s = s;
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(s);
// }
//
// public static byte[] staticSerialize(String s) {
// try {
// return s.getBytes("UTF8");
// } catch (UnsupportedEncodingException e) {
// // No reasonable JVM will lack UTF8
// throw new RuntimeException(e);
// }
// }
// }
| import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.SetMultimap;
import com.urbanairship.datacube.BucketType;
import com.urbanairship.datacube.Bucketer;
import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.serializables.StringSerializable;
import java.util.Collection;
import java.util.List; | package com.urbanairship.datacube.bucketers;
/**
* A Bucketer that accepts a list of strings and returns each one as a bucket. For example, this is useful when an
* input type has an arbitrary number of tags associated with it (there would be a single "tags" dimension").
*/
public class TagsBucketer implements Bucketer<Collection<String>> {
@Override | // Path: src/main/java/com/urbanairship/datacube/BucketType.java
// public class BucketType {
// public static final BucketType IDENTITY = new BucketType("nobucket", new byte[]{});
// public static final BucketType WILDCARD = new BucketType("wildcard", new byte[]{});
//
// private final String nameInErrMsgs;
// private final byte[] uniqueId;
//
// public BucketType(String nameInErrMsgs, byte[] uniqueId) {
// this.nameInErrMsgs = nameInErrMsgs;
// this.uniqueId = uniqueId;
// }
//
// public byte[] getUniqueId() {
// return uniqueId;
// }
//
// public String getNameInErrMsgs() {
// return nameInErrMsgs;
// }
//
// public String toString() {
// return nameInErrMsgs;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof BucketType)) return false;
// BucketType that = (BucketType) o;
// return Objects.equals(nameInErrMsgs, that.nameInErrMsgs) &&
// Arrays.equals(uniqueId, that.uniqueId);
// }
//
// @Override
// public int hashCode() {
//
// int result = Objects.hash(nameInErrMsgs);
// result = 31 * result + Arrays.hashCode(uniqueId);
// return result;
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/Bucketer.java
// public interface Bucketer<F> {
// /**
// * When writing to the cube at some address, the address will have one coordinate for each
// * dimension in the cube, for example (time: 348524388, location: portland). For each
// * dimension, for each bucket type within that dimension, the bucketer must transform the
// * input data into the bucket that should be used to store the data.
// */
// SetMultimap<BucketType, CSerializable> bucketForWrite(F coordinate);
//
// /**
// * When reading from the cube, the reader specifies some coordinates from which to read.
// * The bucketer can choose which cube coordinates to read from based on these input
// * coordinates. For example, if the reader asks for hourly counts (the Hourly BucketType) and
// * passes a timestamp, the bucketer could return the timestamp rounded down to the hour floor.
// */
// CSerializable bucketForRead(Object coordinate, BucketType bucketType);
//
// /**
// * Return all bucket types that exist in this dimension.
// */
// List<BucketType> getBucketTypes();
//
//
// /**
// * This identity/no-op bucketer class is implicitly used for dimensions that don't choose a
// * bucketer.
// */
// class IdentityBucketer implements Bucketer<CSerializable> {
// private final List<BucketType> bucketTypes = ImmutableList.of(BucketType.IDENTITY);
//
// @Override
// public SetMultimap<BucketType, CSerializable> bucketForWrite(CSerializable coordinate) {
// return ImmutableSetMultimap.of(BucketType.IDENTITY, coordinate);
// }
//
// @Override
// public CSerializable bucketForRead(Object coordinateField, BucketType bucketType) {
// return (CSerializable) coordinateField;
// }
//
// @Override
// public List<BucketType> getBucketTypes() {
// return bucketTypes;
// }
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
//
// Path: src/main/java/com/urbanairship/datacube/serializables/StringSerializable.java
// public class StringSerializable implements CSerializable {
// private final String s;
//
// public StringSerializable(String s) {
// this.s = s;
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(s);
// }
//
// public static byte[] staticSerialize(String s) {
// try {
// return s.getBytes("UTF8");
// } catch (UnsupportedEncodingException e) {
// // No reasonable JVM will lack UTF8
// throw new RuntimeException(e);
// }
// }
// }
// Path: src/main/java/com/urbanairship/datacube/bucketers/TagsBucketer.java
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.SetMultimap;
import com.urbanairship.datacube.BucketType;
import com.urbanairship.datacube.Bucketer;
import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.serializables.StringSerializable;
import java.util.Collection;
import java.util.List;
package com.urbanairship.datacube.bucketers;
/**
* A Bucketer that accepts a list of strings and returns each one as a bucket. For example, this is useful when an
* input type has an arbitrary number of tags associated with it (there would be a single "tags" dimension").
*/
public class TagsBucketer implements Bucketer<Collection<String>> {
@Override | public SetMultimap<BucketType, CSerializable> bucketForWrite( |
urbanairship/datacube | src/main/java/com/urbanairship/datacube/bucketers/TagsBucketer.java | // Path: src/main/java/com/urbanairship/datacube/BucketType.java
// public class BucketType {
// public static final BucketType IDENTITY = new BucketType("nobucket", new byte[]{});
// public static final BucketType WILDCARD = new BucketType("wildcard", new byte[]{});
//
// private final String nameInErrMsgs;
// private final byte[] uniqueId;
//
// public BucketType(String nameInErrMsgs, byte[] uniqueId) {
// this.nameInErrMsgs = nameInErrMsgs;
// this.uniqueId = uniqueId;
// }
//
// public byte[] getUniqueId() {
// return uniqueId;
// }
//
// public String getNameInErrMsgs() {
// return nameInErrMsgs;
// }
//
// public String toString() {
// return nameInErrMsgs;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof BucketType)) return false;
// BucketType that = (BucketType) o;
// return Objects.equals(nameInErrMsgs, that.nameInErrMsgs) &&
// Arrays.equals(uniqueId, that.uniqueId);
// }
//
// @Override
// public int hashCode() {
//
// int result = Objects.hash(nameInErrMsgs);
// result = 31 * result + Arrays.hashCode(uniqueId);
// return result;
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/Bucketer.java
// public interface Bucketer<F> {
// /**
// * When writing to the cube at some address, the address will have one coordinate for each
// * dimension in the cube, for example (time: 348524388, location: portland). For each
// * dimension, for each bucket type within that dimension, the bucketer must transform the
// * input data into the bucket that should be used to store the data.
// */
// SetMultimap<BucketType, CSerializable> bucketForWrite(F coordinate);
//
// /**
// * When reading from the cube, the reader specifies some coordinates from which to read.
// * The bucketer can choose which cube coordinates to read from based on these input
// * coordinates. For example, if the reader asks for hourly counts (the Hourly BucketType) and
// * passes a timestamp, the bucketer could return the timestamp rounded down to the hour floor.
// */
// CSerializable bucketForRead(Object coordinate, BucketType bucketType);
//
// /**
// * Return all bucket types that exist in this dimension.
// */
// List<BucketType> getBucketTypes();
//
//
// /**
// * This identity/no-op bucketer class is implicitly used for dimensions that don't choose a
// * bucketer.
// */
// class IdentityBucketer implements Bucketer<CSerializable> {
// private final List<BucketType> bucketTypes = ImmutableList.of(BucketType.IDENTITY);
//
// @Override
// public SetMultimap<BucketType, CSerializable> bucketForWrite(CSerializable coordinate) {
// return ImmutableSetMultimap.of(BucketType.IDENTITY, coordinate);
// }
//
// @Override
// public CSerializable bucketForRead(Object coordinateField, BucketType bucketType) {
// return (CSerializable) coordinateField;
// }
//
// @Override
// public List<BucketType> getBucketTypes() {
// return bucketTypes;
// }
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
//
// Path: src/main/java/com/urbanairship/datacube/serializables/StringSerializable.java
// public class StringSerializable implements CSerializable {
// private final String s;
//
// public StringSerializable(String s) {
// this.s = s;
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(s);
// }
//
// public static byte[] staticSerialize(String s) {
// try {
// return s.getBytes("UTF8");
// } catch (UnsupportedEncodingException e) {
// // No reasonable JVM will lack UTF8
// throw new RuntimeException(e);
// }
// }
// }
| import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.SetMultimap;
import com.urbanairship.datacube.BucketType;
import com.urbanairship.datacube.Bucketer;
import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.serializables.StringSerializable;
import java.util.Collection;
import java.util.List; | package com.urbanairship.datacube.bucketers;
/**
* A Bucketer that accepts a list of strings and returns each one as a bucket. For example, this is useful when an
* input type has an arbitrary number of tags associated with it (there would be a single "tags" dimension").
*/
public class TagsBucketer implements Bucketer<Collection<String>> {
@Override | // Path: src/main/java/com/urbanairship/datacube/BucketType.java
// public class BucketType {
// public static final BucketType IDENTITY = new BucketType("nobucket", new byte[]{});
// public static final BucketType WILDCARD = new BucketType("wildcard", new byte[]{});
//
// private final String nameInErrMsgs;
// private final byte[] uniqueId;
//
// public BucketType(String nameInErrMsgs, byte[] uniqueId) {
// this.nameInErrMsgs = nameInErrMsgs;
// this.uniqueId = uniqueId;
// }
//
// public byte[] getUniqueId() {
// return uniqueId;
// }
//
// public String getNameInErrMsgs() {
// return nameInErrMsgs;
// }
//
// public String toString() {
// return nameInErrMsgs;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof BucketType)) return false;
// BucketType that = (BucketType) o;
// return Objects.equals(nameInErrMsgs, that.nameInErrMsgs) &&
// Arrays.equals(uniqueId, that.uniqueId);
// }
//
// @Override
// public int hashCode() {
//
// int result = Objects.hash(nameInErrMsgs);
// result = 31 * result + Arrays.hashCode(uniqueId);
// return result;
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/Bucketer.java
// public interface Bucketer<F> {
// /**
// * When writing to the cube at some address, the address will have one coordinate for each
// * dimension in the cube, for example (time: 348524388, location: portland). For each
// * dimension, for each bucket type within that dimension, the bucketer must transform the
// * input data into the bucket that should be used to store the data.
// */
// SetMultimap<BucketType, CSerializable> bucketForWrite(F coordinate);
//
// /**
// * When reading from the cube, the reader specifies some coordinates from which to read.
// * The bucketer can choose which cube coordinates to read from based on these input
// * coordinates. For example, if the reader asks for hourly counts (the Hourly BucketType) and
// * passes a timestamp, the bucketer could return the timestamp rounded down to the hour floor.
// */
// CSerializable bucketForRead(Object coordinate, BucketType bucketType);
//
// /**
// * Return all bucket types that exist in this dimension.
// */
// List<BucketType> getBucketTypes();
//
//
// /**
// * This identity/no-op bucketer class is implicitly used for dimensions that don't choose a
// * bucketer.
// */
// class IdentityBucketer implements Bucketer<CSerializable> {
// private final List<BucketType> bucketTypes = ImmutableList.of(BucketType.IDENTITY);
//
// @Override
// public SetMultimap<BucketType, CSerializable> bucketForWrite(CSerializable coordinate) {
// return ImmutableSetMultimap.of(BucketType.IDENTITY, coordinate);
// }
//
// @Override
// public CSerializable bucketForRead(Object coordinateField, BucketType bucketType) {
// return (CSerializable) coordinateField;
// }
//
// @Override
// public List<BucketType> getBucketTypes() {
// return bucketTypes;
// }
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
//
// Path: src/main/java/com/urbanairship/datacube/serializables/StringSerializable.java
// public class StringSerializable implements CSerializable {
// private final String s;
//
// public StringSerializable(String s) {
// this.s = s;
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(s);
// }
//
// public static byte[] staticSerialize(String s) {
// try {
// return s.getBytes("UTF8");
// } catch (UnsupportedEncodingException e) {
// // No reasonable JVM will lack UTF8
// throw new RuntimeException(e);
// }
// }
// }
// Path: src/main/java/com/urbanairship/datacube/bucketers/TagsBucketer.java
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.SetMultimap;
import com.urbanairship.datacube.BucketType;
import com.urbanairship.datacube.Bucketer;
import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.serializables.StringSerializable;
import java.util.Collection;
import java.util.List;
package com.urbanairship.datacube.bucketers;
/**
* A Bucketer that accepts a list of strings and returns each one as a bucket. For example, this is useful when an
* input type has an arbitrary number of tags associated with it (there would be a single "tags" dimension").
*/
public class TagsBucketer implements Bucketer<Collection<String>> {
@Override | public SetMultimap<BucketType, CSerializable> bucketForWrite( |
urbanairship/datacube | src/main/java/com/urbanairship/datacube/bucketers/TagsBucketer.java | // Path: src/main/java/com/urbanairship/datacube/BucketType.java
// public class BucketType {
// public static final BucketType IDENTITY = new BucketType("nobucket", new byte[]{});
// public static final BucketType WILDCARD = new BucketType("wildcard", new byte[]{});
//
// private final String nameInErrMsgs;
// private final byte[] uniqueId;
//
// public BucketType(String nameInErrMsgs, byte[] uniqueId) {
// this.nameInErrMsgs = nameInErrMsgs;
// this.uniqueId = uniqueId;
// }
//
// public byte[] getUniqueId() {
// return uniqueId;
// }
//
// public String getNameInErrMsgs() {
// return nameInErrMsgs;
// }
//
// public String toString() {
// return nameInErrMsgs;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof BucketType)) return false;
// BucketType that = (BucketType) o;
// return Objects.equals(nameInErrMsgs, that.nameInErrMsgs) &&
// Arrays.equals(uniqueId, that.uniqueId);
// }
//
// @Override
// public int hashCode() {
//
// int result = Objects.hash(nameInErrMsgs);
// result = 31 * result + Arrays.hashCode(uniqueId);
// return result;
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/Bucketer.java
// public interface Bucketer<F> {
// /**
// * When writing to the cube at some address, the address will have one coordinate for each
// * dimension in the cube, for example (time: 348524388, location: portland). For each
// * dimension, for each bucket type within that dimension, the bucketer must transform the
// * input data into the bucket that should be used to store the data.
// */
// SetMultimap<BucketType, CSerializable> bucketForWrite(F coordinate);
//
// /**
// * When reading from the cube, the reader specifies some coordinates from which to read.
// * The bucketer can choose which cube coordinates to read from based on these input
// * coordinates. For example, if the reader asks for hourly counts (the Hourly BucketType) and
// * passes a timestamp, the bucketer could return the timestamp rounded down to the hour floor.
// */
// CSerializable bucketForRead(Object coordinate, BucketType bucketType);
//
// /**
// * Return all bucket types that exist in this dimension.
// */
// List<BucketType> getBucketTypes();
//
//
// /**
// * This identity/no-op bucketer class is implicitly used for dimensions that don't choose a
// * bucketer.
// */
// class IdentityBucketer implements Bucketer<CSerializable> {
// private final List<BucketType> bucketTypes = ImmutableList.of(BucketType.IDENTITY);
//
// @Override
// public SetMultimap<BucketType, CSerializable> bucketForWrite(CSerializable coordinate) {
// return ImmutableSetMultimap.of(BucketType.IDENTITY, coordinate);
// }
//
// @Override
// public CSerializable bucketForRead(Object coordinateField, BucketType bucketType) {
// return (CSerializable) coordinateField;
// }
//
// @Override
// public List<BucketType> getBucketTypes() {
// return bucketTypes;
// }
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
//
// Path: src/main/java/com/urbanairship/datacube/serializables/StringSerializable.java
// public class StringSerializable implements CSerializable {
// private final String s;
//
// public StringSerializable(String s) {
// this.s = s;
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(s);
// }
//
// public static byte[] staticSerialize(String s) {
// try {
// return s.getBytes("UTF8");
// } catch (UnsupportedEncodingException e) {
// // No reasonable JVM will lack UTF8
// throw new RuntimeException(e);
// }
// }
// }
| import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.SetMultimap;
import com.urbanairship.datacube.BucketType;
import com.urbanairship.datacube.Bucketer;
import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.serializables.StringSerializable;
import java.util.Collection;
import java.util.List; | package com.urbanairship.datacube.bucketers;
/**
* A Bucketer that accepts a list of strings and returns each one as a bucket. For example, this is useful when an
* input type has an arbitrary number of tags associated with it (there would be a single "tags" dimension").
*/
public class TagsBucketer implements Bucketer<Collection<String>> {
@Override
public SetMultimap<BucketType, CSerializable> bucketForWrite(
Collection<String> tags) {
ImmutableSetMultimap.Builder<BucketType, CSerializable> builder =
ImmutableSetMultimap.builder();
for (String tag : tags) { | // Path: src/main/java/com/urbanairship/datacube/BucketType.java
// public class BucketType {
// public static final BucketType IDENTITY = new BucketType("nobucket", new byte[]{});
// public static final BucketType WILDCARD = new BucketType("wildcard", new byte[]{});
//
// private final String nameInErrMsgs;
// private final byte[] uniqueId;
//
// public BucketType(String nameInErrMsgs, byte[] uniqueId) {
// this.nameInErrMsgs = nameInErrMsgs;
// this.uniqueId = uniqueId;
// }
//
// public byte[] getUniqueId() {
// return uniqueId;
// }
//
// public String getNameInErrMsgs() {
// return nameInErrMsgs;
// }
//
// public String toString() {
// return nameInErrMsgs;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof BucketType)) return false;
// BucketType that = (BucketType) o;
// return Objects.equals(nameInErrMsgs, that.nameInErrMsgs) &&
// Arrays.equals(uniqueId, that.uniqueId);
// }
//
// @Override
// public int hashCode() {
//
// int result = Objects.hash(nameInErrMsgs);
// result = 31 * result + Arrays.hashCode(uniqueId);
// return result;
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/Bucketer.java
// public interface Bucketer<F> {
// /**
// * When writing to the cube at some address, the address will have one coordinate for each
// * dimension in the cube, for example (time: 348524388, location: portland). For each
// * dimension, for each bucket type within that dimension, the bucketer must transform the
// * input data into the bucket that should be used to store the data.
// */
// SetMultimap<BucketType, CSerializable> bucketForWrite(F coordinate);
//
// /**
// * When reading from the cube, the reader specifies some coordinates from which to read.
// * The bucketer can choose which cube coordinates to read from based on these input
// * coordinates. For example, if the reader asks for hourly counts (the Hourly BucketType) and
// * passes a timestamp, the bucketer could return the timestamp rounded down to the hour floor.
// */
// CSerializable bucketForRead(Object coordinate, BucketType bucketType);
//
// /**
// * Return all bucket types that exist in this dimension.
// */
// List<BucketType> getBucketTypes();
//
//
// /**
// * This identity/no-op bucketer class is implicitly used for dimensions that don't choose a
// * bucketer.
// */
// class IdentityBucketer implements Bucketer<CSerializable> {
// private final List<BucketType> bucketTypes = ImmutableList.of(BucketType.IDENTITY);
//
// @Override
// public SetMultimap<BucketType, CSerializable> bucketForWrite(CSerializable coordinate) {
// return ImmutableSetMultimap.of(BucketType.IDENTITY, coordinate);
// }
//
// @Override
// public CSerializable bucketForRead(Object coordinateField, BucketType bucketType) {
// return (CSerializable) coordinateField;
// }
//
// @Override
// public List<BucketType> getBucketTypes() {
// return bucketTypes;
// }
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
//
// Path: src/main/java/com/urbanairship/datacube/serializables/StringSerializable.java
// public class StringSerializable implements CSerializable {
// private final String s;
//
// public StringSerializable(String s) {
// this.s = s;
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(s);
// }
//
// public static byte[] staticSerialize(String s) {
// try {
// return s.getBytes("UTF8");
// } catch (UnsupportedEncodingException e) {
// // No reasonable JVM will lack UTF8
// throw new RuntimeException(e);
// }
// }
// }
// Path: src/main/java/com/urbanairship/datacube/bucketers/TagsBucketer.java
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.SetMultimap;
import com.urbanairship.datacube.BucketType;
import com.urbanairship.datacube.Bucketer;
import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.serializables.StringSerializable;
import java.util.Collection;
import java.util.List;
package com.urbanairship.datacube.bucketers;
/**
* A Bucketer that accepts a list of strings and returns each one as a bucket. For example, this is useful when an
* input type has an arbitrary number of tags associated with it (there would be a single "tags" dimension").
*/
public class TagsBucketer implements Bucketer<Collection<String>> {
@Override
public SetMultimap<BucketType, CSerializable> bucketForWrite(
Collection<String> tags) {
ImmutableSetMultimap.Builder<BucketType, CSerializable> builder =
ImmutableSetMultimap.builder();
for (String tag : tags) { | builder.put(BucketType.IDENTITY, new StringSerializable(tag)); |
urbanairship/datacube | src/main/java/com/urbanairship/datacube/bucketers/BigEndianLongBucketer.java | // Path: src/main/java/com/urbanairship/datacube/BucketType.java
// public class BucketType {
// public static final BucketType IDENTITY = new BucketType("nobucket", new byte[]{});
// public static final BucketType WILDCARD = new BucketType("wildcard", new byte[]{});
//
// private final String nameInErrMsgs;
// private final byte[] uniqueId;
//
// public BucketType(String nameInErrMsgs, byte[] uniqueId) {
// this.nameInErrMsgs = nameInErrMsgs;
// this.uniqueId = uniqueId;
// }
//
// public byte[] getUniqueId() {
// return uniqueId;
// }
//
// public String getNameInErrMsgs() {
// return nameInErrMsgs;
// }
//
// public String toString() {
// return nameInErrMsgs;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof BucketType)) return false;
// BucketType that = (BucketType) o;
// return Objects.equals(nameInErrMsgs, that.nameInErrMsgs) &&
// Arrays.equals(uniqueId, that.uniqueId);
// }
//
// @Override
// public int hashCode() {
//
// int result = Objects.hash(nameInErrMsgs);
// result = 31 * result + Arrays.hashCode(uniqueId);
// return result;
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/Bucketer.java
// public interface Bucketer<F> {
// /**
// * When writing to the cube at some address, the address will have one coordinate for each
// * dimension in the cube, for example (time: 348524388, location: portland). For each
// * dimension, for each bucket type within that dimension, the bucketer must transform the
// * input data into the bucket that should be used to store the data.
// */
// SetMultimap<BucketType, CSerializable> bucketForWrite(F coordinate);
//
// /**
// * When reading from the cube, the reader specifies some coordinates from which to read.
// * The bucketer can choose which cube coordinates to read from based on these input
// * coordinates. For example, if the reader asks for hourly counts (the Hourly BucketType) and
// * passes a timestamp, the bucketer could return the timestamp rounded down to the hour floor.
// */
// CSerializable bucketForRead(Object coordinate, BucketType bucketType);
//
// /**
// * Return all bucket types that exist in this dimension.
// */
// List<BucketType> getBucketTypes();
//
//
// /**
// * This identity/no-op bucketer class is implicitly used for dimensions that don't choose a
// * bucketer.
// */
// class IdentityBucketer implements Bucketer<CSerializable> {
// private final List<BucketType> bucketTypes = ImmutableList.of(BucketType.IDENTITY);
//
// @Override
// public SetMultimap<BucketType, CSerializable> bucketForWrite(CSerializable coordinate) {
// return ImmutableSetMultimap.of(BucketType.IDENTITY, coordinate);
// }
//
// @Override
// public CSerializable bucketForRead(Object coordinateField, BucketType bucketType) {
// return (CSerializable) coordinateField;
// }
//
// @Override
// public List<BucketType> getBucketTypes() {
// return bucketTypes;
// }
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
//
// Path: src/main/java/com/urbanairship/datacube/ops/LongOp.java
// public class LongOp implements Op {
// private final long val;
// public static final LongOpDeserializer DESERIALIZER = new LongOpDeserializer();
//
// public LongOp(long val) {
// this.val = val;
// }
//
// @Override
// public Op add(Op otherOp) {
// if (!(otherOp instanceof LongOp)) {
// throw new RuntimeException();
// }
// return new LongOp(val + ((LongOp) otherOp).val);
// }
//
// @Override
// public Op subtract(Op otherOp) {
// return new LongOp(this.val - ((LongOp) otherOp).val);
// }
//
// /**
// * Eclipse auto-generated
// */
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + (int) (val ^ (val >>> 32));
// return result;
// }
//
// /**
// * Eclipse auto-generated
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// LongOp other = (LongOp) obj;
// if (val != other.val)
// return false;
// return true;
// }
//
// @Override
// public byte[] serialize() {
// return Util.longToBytes(val);
// }
//
// public static class LongOpDeserializer implements Deserializer<LongOp> {
// @Override
// public LongOp fromBytes(byte[] bytes) {
// return new LongOp(Util.bytesToLong(bytes));
// }
// }
//
// public String toString() {
// return Long.toString(val);
// }
//
// public long getLong() {
// return val;
// }
// }
| import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.SetMultimap;
import com.urbanairship.datacube.BucketType;
import com.urbanairship.datacube.Bucketer;
import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.ops.LongOp;
import com.urbanairship.datacube.serializables.LongSerializable;
import java.util.List; | /*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.bucketers;
/**
* You can use this when one of your dimension coordinate types is a straightforward Long.
*/
public class BigEndianLongBucketer implements Bucketer<Long> {
private final static List<BucketType> bucketTypes = ImmutableList.of(BucketType.IDENTITY);
@Override | // Path: src/main/java/com/urbanairship/datacube/BucketType.java
// public class BucketType {
// public static final BucketType IDENTITY = new BucketType("nobucket", new byte[]{});
// public static final BucketType WILDCARD = new BucketType("wildcard", new byte[]{});
//
// private final String nameInErrMsgs;
// private final byte[] uniqueId;
//
// public BucketType(String nameInErrMsgs, byte[] uniqueId) {
// this.nameInErrMsgs = nameInErrMsgs;
// this.uniqueId = uniqueId;
// }
//
// public byte[] getUniqueId() {
// return uniqueId;
// }
//
// public String getNameInErrMsgs() {
// return nameInErrMsgs;
// }
//
// public String toString() {
// return nameInErrMsgs;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof BucketType)) return false;
// BucketType that = (BucketType) o;
// return Objects.equals(nameInErrMsgs, that.nameInErrMsgs) &&
// Arrays.equals(uniqueId, that.uniqueId);
// }
//
// @Override
// public int hashCode() {
//
// int result = Objects.hash(nameInErrMsgs);
// result = 31 * result + Arrays.hashCode(uniqueId);
// return result;
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/Bucketer.java
// public interface Bucketer<F> {
// /**
// * When writing to the cube at some address, the address will have one coordinate for each
// * dimension in the cube, for example (time: 348524388, location: portland). For each
// * dimension, for each bucket type within that dimension, the bucketer must transform the
// * input data into the bucket that should be used to store the data.
// */
// SetMultimap<BucketType, CSerializable> bucketForWrite(F coordinate);
//
// /**
// * When reading from the cube, the reader specifies some coordinates from which to read.
// * The bucketer can choose which cube coordinates to read from based on these input
// * coordinates. For example, if the reader asks for hourly counts (the Hourly BucketType) and
// * passes a timestamp, the bucketer could return the timestamp rounded down to the hour floor.
// */
// CSerializable bucketForRead(Object coordinate, BucketType bucketType);
//
// /**
// * Return all bucket types that exist in this dimension.
// */
// List<BucketType> getBucketTypes();
//
//
// /**
// * This identity/no-op bucketer class is implicitly used for dimensions that don't choose a
// * bucketer.
// */
// class IdentityBucketer implements Bucketer<CSerializable> {
// private final List<BucketType> bucketTypes = ImmutableList.of(BucketType.IDENTITY);
//
// @Override
// public SetMultimap<BucketType, CSerializable> bucketForWrite(CSerializable coordinate) {
// return ImmutableSetMultimap.of(BucketType.IDENTITY, coordinate);
// }
//
// @Override
// public CSerializable bucketForRead(Object coordinateField, BucketType bucketType) {
// return (CSerializable) coordinateField;
// }
//
// @Override
// public List<BucketType> getBucketTypes() {
// return bucketTypes;
// }
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
//
// Path: src/main/java/com/urbanairship/datacube/ops/LongOp.java
// public class LongOp implements Op {
// private final long val;
// public static final LongOpDeserializer DESERIALIZER = new LongOpDeserializer();
//
// public LongOp(long val) {
// this.val = val;
// }
//
// @Override
// public Op add(Op otherOp) {
// if (!(otherOp instanceof LongOp)) {
// throw new RuntimeException();
// }
// return new LongOp(val + ((LongOp) otherOp).val);
// }
//
// @Override
// public Op subtract(Op otherOp) {
// return new LongOp(this.val - ((LongOp) otherOp).val);
// }
//
// /**
// * Eclipse auto-generated
// */
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + (int) (val ^ (val >>> 32));
// return result;
// }
//
// /**
// * Eclipse auto-generated
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// LongOp other = (LongOp) obj;
// if (val != other.val)
// return false;
// return true;
// }
//
// @Override
// public byte[] serialize() {
// return Util.longToBytes(val);
// }
//
// public static class LongOpDeserializer implements Deserializer<LongOp> {
// @Override
// public LongOp fromBytes(byte[] bytes) {
// return new LongOp(Util.bytesToLong(bytes));
// }
// }
//
// public String toString() {
// return Long.toString(val);
// }
//
// public long getLong() {
// return val;
// }
// }
// Path: src/main/java/com/urbanairship/datacube/bucketers/BigEndianLongBucketer.java
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.SetMultimap;
import com.urbanairship.datacube.BucketType;
import com.urbanairship.datacube.Bucketer;
import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.ops.LongOp;
import com.urbanairship.datacube.serializables.LongSerializable;
import java.util.List;
/*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.bucketers;
/**
* You can use this when one of your dimension coordinate types is a straightforward Long.
*/
public class BigEndianLongBucketer implements Bucketer<Long> {
private final static List<BucketType> bucketTypes = ImmutableList.of(BucketType.IDENTITY);
@Override | public SetMultimap<BucketType, CSerializable> bucketForWrite(Long coordinate) { |
urbanairship/datacube | src/main/java/com/urbanairship/datacube/bucketers/BigEndianLongBucketer.java | // Path: src/main/java/com/urbanairship/datacube/BucketType.java
// public class BucketType {
// public static final BucketType IDENTITY = new BucketType("nobucket", new byte[]{});
// public static final BucketType WILDCARD = new BucketType("wildcard", new byte[]{});
//
// private final String nameInErrMsgs;
// private final byte[] uniqueId;
//
// public BucketType(String nameInErrMsgs, byte[] uniqueId) {
// this.nameInErrMsgs = nameInErrMsgs;
// this.uniqueId = uniqueId;
// }
//
// public byte[] getUniqueId() {
// return uniqueId;
// }
//
// public String getNameInErrMsgs() {
// return nameInErrMsgs;
// }
//
// public String toString() {
// return nameInErrMsgs;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof BucketType)) return false;
// BucketType that = (BucketType) o;
// return Objects.equals(nameInErrMsgs, that.nameInErrMsgs) &&
// Arrays.equals(uniqueId, that.uniqueId);
// }
//
// @Override
// public int hashCode() {
//
// int result = Objects.hash(nameInErrMsgs);
// result = 31 * result + Arrays.hashCode(uniqueId);
// return result;
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/Bucketer.java
// public interface Bucketer<F> {
// /**
// * When writing to the cube at some address, the address will have one coordinate for each
// * dimension in the cube, for example (time: 348524388, location: portland). For each
// * dimension, for each bucket type within that dimension, the bucketer must transform the
// * input data into the bucket that should be used to store the data.
// */
// SetMultimap<BucketType, CSerializable> bucketForWrite(F coordinate);
//
// /**
// * When reading from the cube, the reader specifies some coordinates from which to read.
// * The bucketer can choose which cube coordinates to read from based on these input
// * coordinates. For example, if the reader asks for hourly counts (the Hourly BucketType) and
// * passes a timestamp, the bucketer could return the timestamp rounded down to the hour floor.
// */
// CSerializable bucketForRead(Object coordinate, BucketType bucketType);
//
// /**
// * Return all bucket types that exist in this dimension.
// */
// List<BucketType> getBucketTypes();
//
//
// /**
// * This identity/no-op bucketer class is implicitly used for dimensions that don't choose a
// * bucketer.
// */
// class IdentityBucketer implements Bucketer<CSerializable> {
// private final List<BucketType> bucketTypes = ImmutableList.of(BucketType.IDENTITY);
//
// @Override
// public SetMultimap<BucketType, CSerializable> bucketForWrite(CSerializable coordinate) {
// return ImmutableSetMultimap.of(BucketType.IDENTITY, coordinate);
// }
//
// @Override
// public CSerializable bucketForRead(Object coordinateField, BucketType bucketType) {
// return (CSerializable) coordinateField;
// }
//
// @Override
// public List<BucketType> getBucketTypes() {
// return bucketTypes;
// }
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
//
// Path: src/main/java/com/urbanairship/datacube/ops/LongOp.java
// public class LongOp implements Op {
// private final long val;
// public static final LongOpDeserializer DESERIALIZER = new LongOpDeserializer();
//
// public LongOp(long val) {
// this.val = val;
// }
//
// @Override
// public Op add(Op otherOp) {
// if (!(otherOp instanceof LongOp)) {
// throw new RuntimeException();
// }
// return new LongOp(val + ((LongOp) otherOp).val);
// }
//
// @Override
// public Op subtract(Op otherOp) {
// return new LongOp(this.val - ((LongOp) otherOp).val);
// }
//
// /**
// * Eclipse auto-generated
// */
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + (int) (val ^ (val >>> 32));
// return result;
// }
//
// /**
// * Eclipse auto-generated
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// LongOp other = (LongOp) obj;
// if (val != other.val)
// return false;
// return true;
// }
//
// @Override
// public byte[] serialize() {
// return Util.longToBytes(val);
// }
//
// public static class LongOpDeserializer implements Deserializer<LongOp> {
// @Override
// public LongOp fromBytes(byte[] bytes) {
// return new LongOp(Util.bytesToLong(bytes));
// }
// }
//
// public String toString() {
// return Long.toString(val);
// }
//
// public long getLong() {
// return val;
// }
// }
| import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.SetMultimap;
import com.urbanairship.datacube.BucketType;
import com.urbanairship.datacube.Bucketer;
import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.ops.LongOp;
import com.urbanairship.datacube.serializables.LongSerializable;
import java.util.List; | /*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.bucketers;
/**
* You can use this when one of your dimension coordinate types is a straightforward Long.
*/
public class BigEndianLongBucketer implements Bucketer<Long> {
private final static List<BucketType> bucketTypes = ImmutableList.of(BucketType.IDENTITY);
@Override
public SetMultimap<BucketType, CSerializable> bucketForWrite(Long coordinate) {
return ImmutableSetMultimap.<BucketType, CSerializable>of( | // Path: src/main/java/com/urbanairship/datacube/BucketType.java
// public class BucketType {
// public static final BucketType IDENTITY = new BucketType("nobucket", new byte[]{});
// public static final BucketType WILDCARD = new BucketType("wildcard", new byte[]{});
//
// private final String nameInErrMsgs;
// private final byte[] uniqueId;
//
// public BucketType(String nameInErrMsgs, byte[] uniqueId) {
// this.nameInErrMsgs = nameInErrMsgs;
// this.uniqueId = uniqueId;
// }
//
// public byte[] getUniqueId() {
// return uniqueId;
// }
//
// public String getNameInErrMsgs() {
// return nameInErrMsgs;
// }
//
// public String toString() {
// return nameInErrMsgs;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof BucketType)) return false;
// BucketType that = (BucketType) o;
// return Objects.equals(nameInErrMsgs, that.nameInErrMsgs) &&
// Arrays.equals(uniqueId, that.uniqueId);
// }
//
// @Override
// public int hashCode() {
//
// int result = Objects.hash(nameInErrMsgs);
// result = 31 * result + Arrays.hashCode(uniqueId);
// return result;
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/Bucketer.java
// public interface Bucketer<F> {
// /**
// * When writing to the cube at some address, the address will have one coordinate for each
// * dimension in the cube, for example (time: 348524388, location: portland). For each
// * dimension, for each bucket type within that dimension, the bucketer must transform the
// * input data into the bucket that should be used to store the data.
// */
// SetMultimap<BucketType, CSerializable> bucketForWrite(F coordinate);
//
// /**
// * When reading from the cube, the reader specifies some coordinates from which to read.
// * The bucketer can choose which cube coordinates to read from based on these input
// * coordinates. For example, if the reader asks for hourly counts (the Hourly BucketType) and
// * passes a timestamp, the bucketer could return the timestamp rounded down to the hour floor.
// */
// CSerializable bucketForRead(Object coordinate, BucketType bucketType);
//
// /**
// * Return all bucket types that exist in this dimension.
// */
// List<BucketType> getBucketTypes();
//
//
// /**
// * This identity/no-op bucketer class is implicitly used for dimensions that don't choose a
// * bucketer.
// */
// class IdentityBucketer implements Bucketer<CSerializable> {
// private final List<BucketType> bucketTypes = ImmutableList.of(BucketType.IDENTITY);
//
// @Override
// public SetMultimap<BucketType, CSerializable> bucketForWrite(CSerializable coordinate) {
// return ImmutableSetMultimap.of(BucketType.IDENTITY, coordinate);
// }
//
// @Override
// public CSerializable bucketForRead(Object coordinateField, BucketType bucketType) {
// return (CSerializable) coordinateField;
// }
//
// @Override
// public List<BucketType> getBucketTypes() {
// return bucketTypes;
// }
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
//
// Path: src/main/java/com/urbanairship/datacube/ops/LongOp.java
// public class LongOp implements Op {
// private final long val;
// public static final LongOpDeserializer DESERIALIZER = new LongOpDeserializer();
//
// public LongOp(long val) {
// this.val = val;
// }
//
// @Override
// public Op add(Op otherOp) {
// if (!(otherOp instanceof LongOp)) {
// throw new RuntimeException();
// }
// return new LongOp(val + ((LongOp) otherOp).val);
// }
//
// @Override
// public Op subtract(Op otherOp) {
// return new LongOp(this.val - ((LongOp) otherOp).val);
// }
//
// /**
// * Eclipse auto-generated
// */
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + (int) (val ^ (val >>> 32));
// return result;
// }
//
// /**
// * Eclipse auto-generated
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// LongOp other = (LongOp) obj;
// if (val != other.val)
// return false;
// return true;
// }
//
// @Override
// public byte[] serialize() {
// return Util.longToBytes(val);
// }
//
// public static class LongOpDeserializer implements Deserializer<LongOp> {
// @Override
// public LongOp fromBytes(byte[] bytes) {
// return new LongOp(Util.bytesToLong(bytes));
// }
// }
//
// public String toString() {
// return Long.toString(val);
// }
//
// public long getLong() {
// return val;
// }
// }
// Path: src/main/java/com/urbanairship/datacube/bucketers/BigEndianLongBucketer.java
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.SetMultimap;
import com.urbanairship.datacube.BucketType;
import com.urbanairship.datacube.Bucketer;
import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.ops.LongOp;
import com.urbanairship.datacube.serializables.LongSerializable;
import java.util.List;
/*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.bucketers;
/**
* You can use this when one of your dimension coordinate types is a straightforward Long.
*/
public class BigEndianLongBucketer implements Bucketer<Long> {
private final static List<BucketType> bucketTypes = ImmutableList.of(BucketType.IDENTITY);
@Override
public SetMultimap<BucketType, CSerializable> bucketForWrite(Long coordinate) {
return ImmutableSetMultimap.<BucketType, CSerializable>of( | BucketType.IDENTITY, new LongOp(coordinate)); |
urbanairship/datacube | src/main/java/com/urbanairship/datacube/bucketers/EnumToOrdinalBucketer.java | // Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
//
// Path: src/main/java/com/urbanairship/datacube/Util.java
// public class Util {
// public static byte[] longToBytes(long l) {
// return ByteBuffer.allocate(8).putLong(l).array();
// }
//
// /**
// * Write a big-endian integer into the least significant bytes of a byte array.
// */
// public static byte[] intToBytesWithLen(int x, int len) {
// if(len <= 4) {
// return trailingBytes(intToBytes(x), len);
// } else {
// ByteBuffer bb = ByteBuffer.allocate(len);
// bb.position(len-4);
// bb.putInt(x);
// assert bb.remaining() == 0;
// return bb.array();
// }
// }
//
// public static long bytesToLong(byte[] bytes) {
// if(bytes.length < 8) {
// throw new IllegalArgumentException("Input array was too small: " +
// Arrays.toString(bytes));
// }
//
// return ByteBuffer.wrap(bytes).getLong();
// }
//
// /**
// * Call this if you have a byte array to convert to long, but your array might need
// * to be left-padded with zeros (if it is less than 8 bytes long).
// */
// public static long bytesToLongPad(byte[] bytes) {
// final int padZeros = Math.max(8-bytes.length, 0);
// ByteBuffer bb = ByteBuffer.allocate(8);
// for(int i=0; i<padZeros; i++) {
// bb.put((byte)0);
// }
// bb.put(bytes, 0, 8-padZeros);
// bb.flip();
// return bb.getLong();
// }
//
// public static byte[] intToBytes(int x) {
// ByteBuffer bb = ByteBuffer.allocate(4);
// bb.putInt(x);
// return bb.array();
// }
//
// public static int bytesToInt(byte[] bytes) {
// return ByteBuffer.wrap(bytes).getInt();
// }
//
// public static byte[] leastSignificantBytes(long l, int numBytes) {
// byte[] all8Bytes = Util.longToBytes(l);
// return trailingBytes(all8Bytes, numBytes);
// }
//
// public static byte[] trailingBytes(byte[] bs, int numBytes) {
// return Arrays.copyOfRange(bs, bs.length-numBytes, bs.length);
// }
//
// /**
// * A utility to allow hashing of a portion of an array without having to copy it.
// * @param array
// * @param startInclusive
// * @param endExclusive
// * @return hash byte
// */
// public static byte hashByteArray(byte[] array, int startInclusive, int endExclusive) {
// if (array == null) {
// return 0;
// }
//
// int range = endExclusive - startInclusive;
// if (range < 0) {
// throw new IllegalArgumentException(startInclusive + " > " + endExclusive);
// }
//
// int result = 1;
// for (int i=startInclusive; i<endExclusive; i++){
// result = 31 * result + array[i];
// }
//
// return (byte)result;
// }
//
// /**
// * Only use this for testing/debugging. Inefficient.
// */
// public static long countRows(Configuration conf, byte[] tableName) throws IOException {
// HTable hTable = null;
// ResultScanner rs = null;
// long count = 0;
// try {
// hTable = new HTable(conf, tableName);
// rs = hTable.getScanner(new Scan());
// for(@SuppressWarnings("unused") Result r: rs) {
// count++;
// }
// return count;
// } finally {
// if(hTable != null) {
// hTable.close();
// }
// if(rs != null) {
// rs.close();
// }
// }
// }
// }
| import com.urbanairship.datacube.serializables.BytesSerializable;
import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.Util; | /*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.bucketers;
public class EnumToOrdinalBucketer<T extends Enum<?>> extends AbstractIdentityBucketer<T> {
private final int numBytes;
public EnumToOrdinalBucketer(int numBytes) {
this.numBytes = numBytes;
}
@Override | // Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
//
// Path: src/main/java/com/urbanairship/datacube/Util.java
// public class Util {
// public static byte[] longToBytes(long l) {
// return ByteBuffer.allocate(8).putLong(l).array();
// }
//
// /**
// * Write a big-endian integer into the least significant bytes of a byte array.
// */
// public static byte[] intToBytesWithLen(int x, int len) {
// if(len <= 4) {
// return trailingBytes(intToBytes(x), len);
// } else {
// ByteBuffer bb = ByteBuffer.allocate(len);
// bb.position(len-4);
// bb.putInt(x);
// assert bb.remaining() == 0;
// return bb.array();
// }
// }
//
// public static long bytesToLong(byte[] bytes) {
// if(bytes.length < 8) {
// throw new IllegalArgumentException("Input array was too small: " +
// Arrays.toString(bytes));
// }
//
// return ByteBuffer.wrap(bytes).getLong();
// }
//
// /**
// * Call this if you have a byte array to convert to long, but your array might need
// * to be left-padded with zeros (if it is less than 8 bytes long).
// */
// public static long bytesToLongPad(byte[] bytes) {
// final int padZeros = Math.max(8-bytes.length, 0);
// ByteBuffer bb = ByteBuffer.allocate(8);
// for(int i=0; i<padZeros; i++) {
// bb.put((byte)0);
// }
// bb.put(bytes, 0, 8-padZeros);
// bb.flip();
// return bb.getLong();
// }
//
// public static byte[] intToBytes(int x) {
// ByteBuffer bb = ByteBuffer.allocate(4);
// bb.putInt(x);
// return bb.array();
// }
//
// public static int bytesToInt(byte[] bytes) {
// return ByteBuffer.wrap(bytes).getInt();
// }
//
// public static byte[] leastSignificantBytes(long l, int numBytes) {
// byte[] all8Bytes = Util.longToBytes(l);
// return trailingBytes(all8Bytes, numBytes);
// }
//
// public static byte[] trailingBytes(byte[] bs, int numBytes) {
// return Arrays.copyOfRange(bs, bs.length-numBytes, bs.length);
// }
//
// /**
// * A utility to allow hashing of a portion of an array without having to copy it.
// * @param array
// * @param startInclusive
// * @param endExclusive
// * @return hash byte
// */
// public static byte hashByteArray(byte[] array, int startInclusive, int endExclusive) {
// if (array == null) {
// return 0;
// }
//
// int range = endExclusive - startInclusive;
// if (range < 0) {
// throw new IllegalArgumentException(startInclusive + " > " + endExclusive);
// }
//
// int result = 1;
// for (int i=startInclusive; i<endExclusive; i++){
// result = 31 * result + array[i];
// }
//
// return (byte)result;
// }
//
// /**
// * Only use this for testing/debugging. Inefficient.
// */
// public static long countRows(Configuration conf, byte[] tableName) throws IOException {
// HTable hTable = null;
// ResultScanner rs = null;
// long count = 0;
// try {
// hTable = new HTable(conf, tableName);
// rs = hTable.getScanner(new Scan());
// for(@SuppressWarnings("unused") Result r: rs) {
// count++;
// }
// return count;
// } finally {
// if(hTable != null) {
// hTable.close();
// }
// if(rs != null) {
// rs.close();
// }
// }
// }
// }
// Path: src/main/java/com/urbanairship/datacube/bucketers/EnumToOrdinalBucketer.java
import com.urbanairship.datacube.serializables.BytesSerializable;
import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.Util;
/*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.bucketers;
public class EnumToOrdinalBucketer<T extends Enum<?>> extends AbstractIdentityBucketer<T> {
private final int numBytes;
public EnumToOrdinalBucketer(int numBytes) {
this.numBytes = numBytes;
}
@Override | public CSerializable makeSerializable(T coordinate) { |
urbanairship/datacube | src/main/java/com/urbanairship/datacube/bucketers/EnumToOrdinalBucketer.java | // Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
//
// Path: src/main/java/com/urbanairship/datacube/Util.java
// public class Util {
// public static byte[] longToBytes(long l) {
// return ByteBuffer.allocate(8).putLong(l).array();
// }
//
// /**
// * Write a big-endian integer into the least significant bytes of a byte array.
// */
// public static byte[] intToBytesWithLen(int x, int len) {
// if(len <= 4) {
// return trailingBytes(intToBytes(x), len);
// } else {
// ByteBuffer bb = ByteBuffer.allocate(len);
// bb.position(len-4);
// bb.putInt(x);
// assert bb.remaining() == 0;
// return bb.array();
// }
// }
//
// public static long bytesToLong(byte[] bytes) {
// if(bytes.length < 8) {
// throw new IllegalArgumentException("Input array was too small: " +
// Arrays.toString(bytes));
// }
//
// return ByteBuffer.wrap(bytes).getLong();
// }
//
// /**
// * Call this if you have a byte array to convert to long, but your array might need
// * to be left-padded with zeros (if it is less than 8 bytes long).
// */
// public static long bytesToLongPad(byte[] bytes) {
// final int padZeros = Math.max(8-bytes.length, 0);
// ByteBuffer bb = ByteBuffer.allocate(8);
// for(int i=0; i<padZeros; i++) {
// bb.put((byte)0);
// }
// bb.put(bytes, 0, 8-padZeros);
// bb.flip();
// return bb.getLong();
// }
//
// public static byte[] intToBytes(int x) {
// ByteBuffer bb = ByteBuffer.allocate(4);
// bb.putInt(x);
// return bb.array();
// }
//
// public static int bytesToInt(byte[] bytes) {
// return ByteBuffer.wrap(bytes).getInt();
// }
//
// public static byte[] leastSignificantBytes(long l, int numBytes) {
// byte[] all8Bytes = Util.longToBytes(l);
// return trailingBytes(all8Bytes, numBytes);
// }
//
// public static byte[] trailingBytes(byte[] bs, int numBytes) {
// return Arrays.copyOfRange(bs, bs.length-numBytes, bs.length);
// }
//
// /**
// * A utility to allow hashing of a portion of an array without having to copy it.
// * @param array
// * @param startInclusive
// * @param endExclusive
// * @return hash byte
// */
// public static byte hashByteArray(byte[] array, int startInclusive, int endExclusive) {
// if (array == null) {
// return 0;
// }
//
// int range = endExclusive - startInclusive;
// if (range < 0) {
// throw new IllegalArgumentException(startInclusive + " > " + endExclusive);
// }
//
// int result = 1;
// for (int i=startInclusive; i<endExclusive; i++){
// result = 31 * result + array[i];
// }
//
// return (byte)result;
// }
//
// /**
// * Only use this for testing/debugging. Inefficient.
// */
// public static long countRows(Configuration conf, byte[] tableName) throws IOException {
// HTable hTable = null;
// ResultScanner rs = null;
// long count = 0;
// try {
// hTable = new HTable(conf, tableName);
// rs = hTable.getScanner(new Scan());
// for(@SuppressWarnings("unused") Result r: rs) {
// count++;
// }
// return count;
// } finally {
// if(hTable != null) {
// hTable.close();
// }
// if(rs != null) {
// rs.close();
// }
// }
// }
// }
| import com.urbanairship.datacube.serializables.BytesSerializable;
import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.Util; | /*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.bucketers;
public class EnumToOrdinalBucketer<T extends Enum<?>> extends AbstractIdentityBucketer<T> {
private final int numBytes;
public EnumToOrdinalBucketer(int numBytes) {
this.numBytes = numBytes;
}
@Override
public CSerializable makeSerializable(T coordinate) {
int ordinal = coordinate.ordinal(); | // Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
//
// Path: src/main/java/com/urbanairship/datacube/Util.java
// public class Util {
// public static byte[] longToBytes(long l) {
// return ByteBuffer.allocate(8).putLong(l).array();
// }
//
// /**
// * Write a big-endian integer into the least significant bytes of a byte array.
// */
// public static byte[] intToBytesWithLen(int x, int len) {
// if(len <= 4) {
// return trailingBytes(intToBytes(x), len);
// } else {
// ByteBuffer bb = ByteBuffer.allocate(len);
// bb.position(len-4);
// bb.putInt(x);
// assert bb.remaining() == 0;
// return bb.array();
// }
// }
//
// public static long bytesToLong(byte[] bytes) {
// if(bytes.length < 8) {
// throw new IllegalArgumentException("Input array was too small: " +
// Arrays.toString(bytes));
// }
//
// return ByteBuffer.wrap(bytes).getLong();
// }
//
// /**
// * Call this if you have a byte array to convert to long, but your array might need
// * to be left-padded with zeros (if it is less than 8 bytes long).
// */
// public static long bytesToLongPad(byte[] bytes) {
// final int padZeros = Math.max(8-bytes.length, 0);
// ByteBuffer bb = ByteBuffer.allocate(8);
// for(int i=0; i<padZeros; i++) {
// bb.put((byte)0);
// }
// bb.put(bytes, 0, 8-padZeros);
// bb.flip();
// return bb.getLong();
// }
//
// public static byte[] intToBytes(int x) {
// ByteBuffer bb = ByteBuffer.allocate(4);
// bb.putInt(x);
// return bb.array();
// }
//
// public static int bytesToInt(byte[] bytes) {
// return ByteBuffer.wrap(bytes).getInt();
// }
//
// public static byte[] leastSignificantBytes(long l, int numBytes) {
// byte[] all8Bytes = Util.longToBytes(l);
// return trailingBytes(all8Bytes, numBytes);
// }
//
// public static byte[] trailingBytes(byte[] bs, int numBytes) {
// return Arrays.copyOfRange(bs, bs.length-numBytes, bs.length);
// }
//
// /**
// * A utility to allow hashing of a portion of an array without having to copy it.
// * @param array
// * @param startInclusive
// * @param endExclusive
// * @return hash byte
// */
// public static byte hashByteArray(byte[] array, int startInclusive, int endExclusive) {
// if (array == null) {
// return 0;
// }
//
// int range = endExclusive - startInclusive;
// if (range < 0) {
// throw new IllegalArgumentException(startInclusive + " > " + endExclusive);
// }
//
// int result = 1;
// for (int i=startInclusive; i<endExclusive; i++){
// result = 31 * result + array[i];
// }
//
// return (byte)result;
// }
//
// /**
// * Only use this for testing/debugging. Inefficient.
// */
// public static long countRows(Configuration conf, byte[] tableName) throws IOException {
// HTable hTable = null;
// ResultScanner rs = null;
// long count = 0;
// try {
// hTable = new HTable(conf, tableName);
// rs = hTable.getScanner(new Scan());
// for(@SuppressWarnings("unused") Result r: rs) {
// count++;
// }
// return count;
// } finally {
// if(hTable != null) {
// hTable.close();
// }
// if(rs != null) {
// rs.close();
// }
// }
// }
// }
// Path: src/main/java/com/urbanairship/datacube/bucketers/EnumToOrdinalBucketer.java
import com.urbanairship.datacube.serializables.BytesSerializable;
import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.Util;
/*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.bucketers;
public class EnumToOrdinalBucketer<T extends Enum<?>> extends AbstractIdentityBucketer<T> {
private final int numBytes;
public EnumToOrdinalBucketer(int numBytes) {
this.numBytes = numBytes;
}
@Override
public CSerializable makeSerializable(T coordinate) {
int ordinal = coordinate.ordinal(); | byte[] bytes = Util.trailingBytes(Util.intToBytes(ordinal), numBytes); |
urbanairship/datacube | src/main/java/com/urbanairship/datacube/backfill/HBaseBackfillMerger.java | // Path: src/main/java/com/urbanairship/datacube/Deserializer.java
// public interface Deserializer<O extends Op> {
// O fromBytes(byte[] bytes);
// }
//
// Path: src/main/java/com/urbanairship/datacube/collectioninputformat/CollectionInputFormat.java
// public class CollectionInputFormat extends InputFormat<Writable, NullWritable> {
// public static final String CONFKEY_COLLECTION = "collectioninputformat.collectionitems";
// public static final String CONFKEY_VALCLASS = "collectioninputformat.valueclass";
//
// /**
// * Stores the given collection as a configuration value. When getSplits() runs later,
// * it will be able to deserialize the collection and use it.
// */
// public static <T extends Writable> void setCollection(Job job, Class<T> valueClass,
// Collection<T> collection) throws IOException {
// setCollection(job.getConfiguration(), valueClass, collection);
// }
//
// public static <T extends Writable> void setCollection(Configuration conf, Class<T> valueClass,
// Collection<T> collection) throws IOException {
// conf.set(CONFKEY_COLLECTION, toBase64(valueClass, collection));
// conf.set(CONFKEY_VALCLASS, valueClass.getName());
// }
//
// public static <T extends Writable> String toBase64(Class<T> valueClass,
// Collection<? extends Writable> collection) throws IOException {
// DataOutputBuffer out = new DataOutputBuffer();
// new CollectionWritable(valueClass, collection).write(out);
// byte[] rawBytes = Arrays.copyOf(out.getData(), out.getLength());
// return new String(Base64.encodeBase64(rawBytes));
// }
//
// @SuppressWarnings("unchecked")
// public static <T extends Writable> Collection<T> fromBase64(Class<T> valueClass,
// String base64) throws IOException {
// byte[] rawBytes = Base64.decodeBase64(base64.getBytes());
// DataInputBuffer in = new DataInputBuffer();
// in.reset(rawBytes, rawBytes.length);
//
// CollectionWritable cw = new CollectionWritable();
// cw.readFields(in);
// return (Collection<T>) cw.getCollection();
// }
//
// @Override
// public RecordReader<Writable, NullWritable> createRecordReader(final InputSplit split, TaskAttemptContext arg1)
// throws IOException, InterruptedException {
// return new SingleItemRecordReader((SingleValueSplit) split);
//
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public List<InputSplit> getSplits(JobContext ctx) throws IOException, InterruptedException {
// String base64 = ctx.getConfiguration().get(CONFKEY_COLLECTION);
// String valueClassName = ctx.getConfiguration().get(CONFKEY_VALCLASS);
// Class<? extends Writable> valueClass;
// try {
// valueClass = (Class<? extends Writable>) Class.forName(valueClassName);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// Collection<? extends Writable> collection = fromBase64(valueClass, base64);
// List<InputSplit> splits = new ArrayList<InputSplit>(collection.size());
// for (Writable val : collection) {
// splits.add(new SingleValueSplit(valueClass, val));
// }
// return splits;
// }
// }
| import com.urbanairship.datacube.Deserializer;
import com.urbanairship.datacube.collectioninputformat.CollectionInputFormat;
import org.apache.commons.lang.ArrayUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List; | /*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.backfill;
/**
* Backfilling is a 3 step process:
* (1) snapshot the live cube data into a so-called snapshot table
* (2) do the application-level event processing into a cube that is stored in some non-visible table
* (3) Merge the snapshot, the backfill table, and the live cube, making changes to the live cube.
*
* This MR job does step 3.
*
* TODO InputSplit locality for mapreduce
*/
public class HBaseBackfillMerger implements Runnable {
private static final Logger log = LoggerFactory.getLogger(HBaseBackfillMerger.class);
static final String CONFKEY_COLUMN_FAMILY = "hbasebackfiller.cf";
static final String CONFKEY_LIVECUBE_TABLE_NAME = "hbasebackfiller.liveCubeTableName";
static final String CONFKEY_SNAPSHOT_TABLE_NAME = "hbasebackfiller.snapshotTableName";
static final String CONFKEY_BACKFILLED_TABLE_NAME = "hbasebackfiller.backfilledTableName";
static final String CONFKEY_DESERIALIZER = "hbasebackfiller.deserializerClassName";
private final Configuration conf;
private final byte[] cubeNameKeyPrefix;
private final byte[] liveCubeTableName;
private final byte[] snapshotTableName;
private final byte[] backfilledTableName;
private final byte[] cf; | // Path: src/main/java/com/urbanairship/datacube/Deserializer.java
// public interface Deserializer<O extends Op> {
// O fromBytes(byte[] bytes);
// }
//
// Path: src/main/java/com/urbanairship/datacube/collectioninputformat/CollectionInputFormat.java
// public class CollectionInputFormat extends InputFormat<Writable, NullWritable> {
// public static final String CONFKEY_COLLECTION = "collectioninputformat.collectionitems";
// public static final String CONFKEY_VALCLASS = "collectioninputformat.valueclass";
//
// /**
// * Stores the given collection as a configuration value. When getSplits() runs later,
// * it will be able to deserialize the collection and use it.
// */
// public static <T extends Writable> void setCollection(Job job, Class<T> valueClass,
// Collection<T> collection) throws IOException {
// setCollection(job.getConfiguration(), valueClass, collection);
// }
//
// public static <T extends Writable> void setCollection(Configuration conf, Class<T> valueClass,
// Collection<T> collection) throws IOException {
// conf.set(CONFKEY_COLLECTION, toBase64(valueClass, collection));
// conf.set(CONFKEY_VALCLASS, valueClass.getName());
// }
//
// public static <T extends Writable> String toBase64(Class<T> valueClass,
// Collection<? extends Writable> collection) throws IOException {
// DataOutputBuffer out = new DataOutputBuffer();
// new CollectionWritable(valueClass, collection).write(out);
// byte[] rawBytes = Arrays.copyOf(out.getData(), out.getLength());
// return new String(Base64.encodeBase64(rawBytes));
// }
//
// @SuppressWarnings("unchecked")
// public static <T extends Writable> Collection<T> fromBase64(Class<T> valueClass,
// String base64) throws IOException {
// byte[] rawBytes = Base64.decodeBase64(base64.getBytes());
// DataInputBuffer in = new DataInputBuffer();
// in.reset(rawBytes, rawBytes.length);
//
// CollectionWritable cw = new CollectionWritable();
// cw.readFields(in);
// return (Collection<T>) cw.getCollection();
// }
//
// @Override
// public RecordReader<Writable, NullWritable> createRecordReader(final InputSplit split, TaskAttemptContext arg1)
// throws IOException, InterruptedException {
// return new SingleItemRecordReader((SingleValueSplit) split);
//
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public List<InputSplit> getSplits(JobContext ctx) throws IOException, InterruptedException {
// String base64 = ctx.getConfiguration().get(CONFKEY_COLLECTION);
// String valueClassName = ctx.getConfiguration().get(CONFKEY_VALCLASS);
// Class<? extends Writable> valueClass;
// try {
// valueClass = (Class<? extends Writable>) Class.forName(valueClassName);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// Collection<? extends Writable> collection = fromBase64(valueClass, base64);
// List<InputSplit> splits = new ArrayList<InputSplit>(collection.size());
// for (Writable val : collection) {
// splits.add(new SingleValueSplit(valueClass, val));
// }
// return splits;
// }
// }
// Path: src/main/java/com/urbanairship/datacube/backfill/HBaseBackfillMerger.java
import com.urbanairship.datacube.Deserializer;
import com.urbanairship.datacube.collectioninputformat.CollectionInputFormat;
import org.apache.commons.lang.ArrayUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.backfill;
/**
* Backfilling is a 3 step process:
* (1) snapshot the live cube data into a so-called snapshot table
* (2) do the application-level event processing into a cube that is stored in some non-visible table
* (3) Merge the snapshot, the backfill table, and the live cube, making changes to the live cube.
*
* This MR job does step 3.
*
* TODO InputSplit locality for mapreduce
*/
public class HBaseBackfillMerger implements Runnable {
private static final Logger log = LoggerFactory.getLogger(HBaseBackfillMerger.class);
static final String CONFKEY_COLUMN_FAMILY = "hbasebackfiller.cf";
static final String CONFKEY_LIVECUBE_TABLE_NAME = "hbasebackfiller.liveCubeTableName";
static final String CONFKEY_SNAPSHOT_TABLE_NAME = "hbasebackfiller.snapshotTableName";
static final String CONFKEY_BACKFILLED_TABLE_NAME = "hbasebackfiller.backfilledTableName";
static final String CONFKEY_DESERIALIZER = "hbasebackfiller.deserializerClassName";
private final Configuration conf;
private final byte[] cubeNameKeyPrefix;
private final byte[] liveCubeTableName;
private final byte[] snapshotTableName;
private final byte[] backfilledTableName;
private final byte[] cf; | private final Class<? extends Deserializer<?>> opDeserializer; |
urbanairship/datacube | src/main/java/com/urbanairship/datacube/backfill/HBaseBackfillMerger.java | // Path: src/main/java/com/urbanairship/datacube/Deserializer.java
// public interface Deserializer<O extends Op> {
// O fromBytes(byte[] bytes);
// }
//
// Path: src/main/java/com/urbanairship/datacube/collectioninputformat/CollectionInputFormat.java
// public class CollectionInputFormat extends InputFormat<Writable, NullWritable> {
// public static final String CONFKEY_COLLECTION = "collectioninputformat.collectionitems";
// public static final String CONFKEY_VALCLASS = "collectioninputformat.valueclass";
//
// /**
// * Stores the given collection as a configuration value. When getSplits() runs later,
// * it will be able to deserialize the collection and use it.
// */
// public static <T extends Writable> void setCollection(Job job, Class<T> valueClass,
// Collection<T> collection) throws IOException {
// setCollection(job.getConfiguration(), valueClass, collection);
// }
//
// public static <T extends Writable> void setCollection(Configuration conf, Class<T> valueClass,
// Collection<T> collection) throws IOException {
// conf.set(CONFKEY_COLLECTION, toBase64(valueClass, collection));
// conf.set(CONFKEY_VALCLASS, valueClass.getName());
// }
//
// public static <T extends Writable> String toBase64(Class<T> valueClass,
// Collection<? extends Writable> collection) throws IOException {
// DataOutputBuffer out = new DataOutputBuffer();
// new CollectionWritable(valueClass, collection).write(out);
// byte[] rawBytes = Arrays.copyOf(out.getData(), out.getLength());
// return new String(Base64.encodeBase64(rawBytes));
// }
//
// @SuppressWarnings("unchecked")
// public static <T extends Writable> Collection<T> fromBase64(Class<T> valueClass,
// String base64) throws IOException {
// byte[] rawBytes = Base64.decodeBase64(base64.getBytes());
// DataInputBuffer in = new DataInputBuffer();
// in.reset(rawBytes, rawBytes.length);
//
// CollectionWritable cw = new CollectionWritable();
// cw.readFields(in);
// return (Collection<T>) cw.getCollection();
// }
//
// @Override
// public RecordReader<Writable, NullWritable> createRecordReader(final InputSplit split, TaskAttemptContext arg1)
// throws IOException, InterruptedException {
// return new SingleItemRecordReader((SingleValueSplit) split);
//
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public List<InputSplit> getSplits(JobContext ctx) throws IOException, InterruptedException {
// String base64 = ctx.getConfiguration().get(CONFKEY_COLLECTION);
// String valueClassName = ctx.getConfiguration().get(CONFKEY_VALCLASS);
// Class<? extends Writable> valueClass;
// try {
// valueClass = (Class<? extends Writable>) Class.forName(valueClassName);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// Collection<? extends Writable> collection = fromBase64(valueClass, base64);
// List<InputSplit> splits = new ArrayList<InputSplit>(collection.size());
// for (Writable val : collection) {
// splits.add(new SingleValueSplit(valueClass, val));
// }
// return splits;
// }
// }
| import com.urbanairship.datacube.Deserializer;
import com.urbanairship.datacube.collectioninputformat.CollectionInputFormat;
import org.apache.commons.lang.ArrayUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List; | HTable liveCubeHTable = null;
ResultScanner liveCubeScanner = null;
try {
// If the live table is empty, we just efficiently copy the backfill in
liveCubeHTable = new HTable(conf, liveCubeTableName);
liveCubeScanner = liveCubeHTable.getScanner(cf);
boolean liveCubeIsEmpty = !liveCubeScanner.iterator().hasNext();
liveCubeScanner.close();
if (liveCubeIsEmpty) {
log.info("Live cube is empty, running a straight copy from the backfill table");
HBaseSnapshotter hbaseSnapshotter = new HBaseSnapshotter(conf, backfilledTableName,
cf, liveCubeTableName, new Path("/tmp/backfill_snapshot_hfiles"), true,
cubeNameKeyPrefix, Bytes.add(cubeNameKeyPrefix, fiftyBytesFF));
return hbaseSnapshotter.runWithCheckedExceptions();
} else {
Job job = new Job(conf);
backfilledHTable = new HTable(conf, backfilledTableName);
Pair<byte[][], byte[][]> allRegionsStartAndEndKeys = backfilledHTable.getStartEndKeys();
byte[][] internalSplitKeys = BackfillUtil.getSplitKeys(allRegionsStartAndEndKeys);
Collection<Scan> scans = scansThisCubeOnly(cubeNameKeyPrefix, internalSplitKeys);
// Get the scans that will cover this table, and store them in the job configuration to be used
// as input splits.
if (log.isDebugEnabled()) {
log.debug("Scans: " + scans);
} | // Path: src/main/java/com/urbanairship/datacube/Deserializer.java
// public interface Deserializer<O extends Op> {
// O fromBytes(byte[] bytes);
// }
//
// Path: src/main/java/com/urbanairship/datacube/collectioninputformat/CollectionInputFormat.java
// public class CollectionInputFormat extends InputFormat<Writable, NullWritable> {
// public static final String CONFKEY_COLLECTION = "collectioninputformat.collectionitems";
// public static final String CONFKEY_VALCLASS = "collectioninputformat.valueclass";
//
// /**
// * Stores the given collection as a configuration value. When getSplits() runs later,
// * it will be able to deserialize the collection and use it.
// */
// public static <T extends Writable> void setCollection(Job job, Class<T> valueClass,
// Collection<T> collection) throws IOException {
// setCollection(job.getConfiguration(), valueClass, collection);
// }
//
// public static <T extends Writable> void setCollection(Configuration conf, Class<T> valueClass,
// Collection<T> collection) throws IOException {
// conf.set(CONFKEY_COLLECTION, toBase64(valueClass, collection));
// conf.set(CONFKEY_VALCLASS, valueClass.getName());
// }
//
// public static <T extends Writable> String toBase64(Class<T> valueClass,
// Collection<? extends Writable> collection) throws IOException {
// DataOutputBuffer out = new DataOutputBuffer();
// new CollectionWritable(valueClass, collection).write(out);
// byte[] rawBytes = Arrays.copyOf(out.getData(), out.getLength());
// return new String(Base64.encodeBase64(rawBytes));
// }
//
// @SuppressWarnings("unchecked")
// public static <T extends Writable> Collection<T> fromBase64(Class<T> valueClass,
// String base64) throws IOException {
// byte[] rawBytes = Base64.decodeBase64(base64.getBytes());
// DataInputBuffer in = new DataInputBuffer();
// in.reset(rawBytes, rawBytes.length);
//
// CollectionWritable cw = new CollectionWritable();
// cw.readFields(in);
// return (Collection<T>) cw.getCollection();
// }
//
// @Override
// public RecordReader<Writable, NullWritable> createRecordReader(final InputSplit split, TaskAttemptContext arg1)
// throws IOException, InterruptedException {
// return new SingleItemRecordReader((SingleValueSplit) split);
//
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public List<InputSplit> getSplits(JobContext ctx) throws IOException, InterruptedException {
// String base64 = ctx.getConfiguration().get(CONFKEY_COLLECTION);
// String valueClassName = ctx.getConfiguration().get(CONFKEY_VALCLASS);
// Class<? extends Writable> valueClass;
// try {
// valueClass = (Class<? extends Writable>) Class.forName(valueClassName);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// Collection<? extends Writable> collection = fromBase64(valueClass, base64);
// List<InputSplit> splits = new ArrayList<InputSplit>(collection.size());
// for (Writable val : collection) {
// splits.add(new SingleValueSplit(valueClass, val));
// }
// return splits;
// }
// }
// Path: src/main/java/com/urbanairship/datacube/backfill/HBaseBackfillMerger.java
import com.urbanairship.datacube.Deserializer;
import com.urbanairship.datacube.collectioninputformat.CollectionInputFormat;
import org.apache.commons.lang.ArrayUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
HTable liveCubeHTable = null;
ResultScanner liveCubeScanner = null;
try {
// If the live table is empty, we just efficiently copy the backfill in
liveCubeHTable = new HTable(conf, liveCubeTableName);
liveCubeScanner = liveCubeHTable.getScanner(cf);
boolean liveCubeIsEmpty = !liveCubeScanner.iterator().hasNext();
liveCubeScanner.close();
if (liveCubeIsEmpty) {
log.info("Live cube is empty, running a straight copy from the backfill table");
HBaseSnapshotter hbaseSnapshotter = new HBaseSnapshotter(conf, backfilledTableName,
cf, liveCubeTableName, new Path("/tmp/backfill_snapshot_hfiles"), true,
cubeNameKeyPrefix, Bytes.add(cubeNameKeyPrefix, fiftyBytesFF));
return hbaseSnapshotter.runWithCheckedExceptions();
} else {
Job job = new Job(conf);
backfilledHTable = new HTable(conf, backfilledTableName);
Pair<byte[][], byte[][]> allRegionsStartAndEndKeys = backfilledHTable.getStartEndKeys();
byte[][] internalSplitKeys = BackfillUtil.getSplitKeys(allRegionsStartAndEndKeys);
Collection<Scan> scans = scansThisCubeOnly(cubeNameKeyPrefix, internalSplitKeys);
// Get the scans that will cover this table, and store them in the job configuration to be used
// as input splits.
if (log.isDebugEnabled()) {
log.debug("Scans: " + scans);
} | CollectionInputFormat.setCollection(job, Scan.class, scans); |
urbanairship/datacube | src/main/java/com/urbanairship/datacube/serializables/EnumSerializable.java | // Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
//
// Path: src/main/java/com/urbanairship/datacube/Util.java
// public class Util {
// public static byte[] longToBytes(long l) {
// return ByteBuffer.allocate(8).putLong(l).array();
// }
//
// /**
// * Write a big-endian integer into the least significant bytes of a byte array.
// */
// public static byte[] intToBytesWithLen(int x, int len) {
// if(len <= 4) {
// return trailingBytes(intToBytes(x), len);
// } else {
// ByteBuffer bb = ByteBuffer.allocate(len);
// bb.position(len-4);
// bb.putInt(x);
// assert bb.remaining() == 0;
// return bb.array();
// }
// }
//
// public static long bytesToLong(byte[] bytes) {
// if(bytes.length < 8) {
// throw new IllegalArgumentException("Input array was too small: " +
// Arrays.toString(bytes));
// }
//
// return ByteBuffer.wrap(bytes).getLong();
// }
//
// /**
// * Call this if you have a byte array to convert to long, but your array might need
// * to be left-padded with zeros (if it is less than 8 bytes long).
// */
// public static long bytesToLongPad(byte[] bytes) {
// final int padZeros = Math.max(8-bytes.length, 0);
// ByteBuffer bb = ByteBuffer.allocate(8);
// for(int i=0; i<padZeros; i++) {
// bb.put((byte)0);
// }
// bb.put(bytes, 0, 8-padZeros);
// bb.flip();
// return bb.getLong();
// }
//
// public static byte[] intToBytes(int x) {
// ByteBuffer bb = ByteBuffer.allocate(4);
// bb.putInt(x);
// return bb.array();
// }
//
// public static int bytesToInt(byte[] bytes) {
// return ByteBuffer.wrap(bytes).getInt();
// }
//
// public static byte[] leastSignificantBytes(long l, int numBytes) {
// byte[] all8Bytes = Util.longToBytes(l);
// return trailingBytes(all8Bytes, numBytes);
// }
//
// public static byte[] trailingBytes(byte[] bs, int numBytes) {
// return Arrays.copyOfRange(bs, bs.length-numBytes, bs.length);
// }
//
// /**
// * A utility to allow hashing of a portion of an array without having to copy it.
// * @param array
// * @param startInclusive
// * @param endExclusive
// * @return hash byte
// */
// public static byte hashByteArray(byte[] array, int startInclusive, int endExclusive) {
// if (array == null) {
// return 0;
// }
//
// int range = endExclusive - startInclusive;
// if (range < 0) {
// throw new IllegalArgumentException(startInclusive + " > " + endExclusive);
// }
//
// int result = 1;
// for (int i=startInclusive; i<endExclusive; i++){
// result = 31 * result + array[i];
// }
//
// return (byte)result;
// }
//
// /**
// * Only use this for testing/debugging. Inefficient.
// */
// public static long countRows(Configuration conf, byte[] tableName) throws IOException {
// HTable hTable = null;
// ResultScanner rs = null;
// long count = 0;
// try {
// hTable = new HTable(conf, tableName);
// rs = hTable.getScanner(new Scan());
// for(@SuppressWarnings("unused") Result r: rs) {
// count++;
// }
// return count;
// } finally {
// if(hTable != null) {
// hTable.close();
// }
// if(rs != null) {
// rs.close();
// }
// }
// }
// }
| import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.Util; | /*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.serializables;
/**
* When using an enum as a dimension bucket type, this wrapper eliminates the boilerplate
* of serializing it to an ordinal. Use this in your bucketer.
*/
public class EnumSerializable implements CSerializable {
private final int ordinal;
private final int numFieldBytes;
/**
* @param numFieldBytes the number of bytes to produce for serialized version of this
* enum
*/
public EnumSerializable(Enum<?> enumInstance, int numFieldBytes) {
this.ordinal = enumInstance.ordinal();
this.numFieldBytes = numFieldBytes;
if (numFieldBytes < 1 || numFieldBytes > 4) {
throw new IllegalArgumentException("numFieldBytes must be in [1..4]");
}
}
@Override
public byte[] serialize() {
return staticSerialize(ordinal, numFieldBytes);
}
public static byte[] staticSerialize(Enum<?> enumInstance, int numFieldBytes) {
return staticSerialize(enumInstance.ordinal(), numFieldBytes);
}
public static byte[] staticSerialize(int ordinal, int numFieldBytes) { | // Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
//
// Path: src/main/java/com/urbanairship/datacube/Util.java
// public class Util {
// public static byte[] longToBytes(long l) {
// return ByteBuffer.allocate(8).putLong(l).array();
// }
//
// /**
// * Write a big-endian integer into the least significant bytes of a byte array.
// */
// public static byte[] intToBytesWithLen(int x, int len) {
// if(len <= 4) {
// return trailingBytes(intToBytes(x), len);
// } else {
// ByteBuffer bb = ByteBuffer.allocate(len);
// bb.position(len-4);
// bb.putInt(x);
// assert bb.remaining() == 0;
// return bb.array();
// }
// }
//
// public static long bytesToLong(byte[] bytes) {
// if(bytes.length < 8) {
// throw new IllegalArgumentException("Input array was too small: " +
// Arrays.toString(bytes));
// }
//
// return ByteBuffer.wrap(bytes).getLong();
// }
//
// /**
// * Call this if you have a byte array to convert to long, but your array might need
// * to be left-padded with zeros (if it is less than 8 bytes long).
// */
// public static long bytesToLongPad(byte[] bytes) {
// final int padZeros = Math.max(8-bytes.length, 0);
// ByteBuffer bb = ByteBuffer.allocate(8);
// for(int i=0; i<padZeros; i++) {
// bb.put((byte)0);
// }
// bb.put(bytes, 0, 8-padZeros);
// bb.flip();
// return bb.getLong();
// }
//
// public static byte[] intToBytes(int x) {
// ByteBuffer bb = ByteBuffer.allocate(4);
// bb.putInt(x);
// return bb.array();
// }
//
// public static int bytesToInt(byte[] bytes) {
// return ByteBuffer.wrap(bytes).getInt();
// }
//
// public static byte[] leastSignificantBytes(long l, int numBytes) {
// byte[] all8Bytes = Util.longToBytes(l);
// return trailingBytes(all8Bytes, numBytes);
// }
//
// public static byte[] trailingBytes(byte[] bs, int numBytes) {
// return Arrays.copyOfRange(bs, bs.length-numBytes, bs.length);
// }
//
// /**
// * A utility to allow hashing of a portion of an array without having to copy it.
// * @param array
// * @param startInclusive
// * @param endExclusive
// * @return hash byte
// */
// public static byte hashByteArray(byte[] array, int startInclusive, int endExclusive) {
// if (array == null) {
// return 0;
// }
//
// int range = endExclusive - startInclusive;
// if (range < 0) {
// throw new IllegalArgumentException(startInclusive + " > " + endExclusive);
// }
//
// int result = 1;
// for (int i=startInclusive; i<endExclusive; i++){
// result = 31 * result + array[i];
// }
//
// return (byte)result;
// }
//
// /**
// * Only use this for testing/debugging. Inefficient.
// */
// public static long countRows(Configuration conf, byte[] tableName) throws IOException {
// HTable hTable = null;
// ResultScanner rs = null;
// long count = 0;
// try {
// hTable = new HTable(conf, tableName);
// rs = hTable.getScanner(new Scan());
// for(@SuppressWarnings("unused") Result r: rs) {
// count++;
// }
// return count;
// } finally {
// if(hTable != null) {
// hTable.close();
// }
// if(rs != null) {
// rs.close();
// }
// }
// }
// }
// Path: src/main/java/com/urbanairship/datacube/serializables/EnumSerializable.java
import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.Util;
/*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.serializables;
/**
* When using an enum as a dimension bucket type, this wrapper eliminates the boilerplate
* of serializing it to an ordinal. Use this in your bucketer.
*/
public class EnumSerializable implements CSerializable {
private final int ordinal;
private final int numFieldBytes;
/**
* @param numFieldBytes the number of bytes to produce for serialized version of this
* enum
*/
public EnumSerializable(Enum<?> enumInstance, int numFieldBytes) {
this.ordinal = enumInstance.ordinal();
this.numFieldBytes = numFieldBytes;
if (numFieldBytes < 1 || numFieldBytes > 4) {
throw new IllegalArgumentException("numFieldBytes must be in [1..4]");
}
}
@Override
public byte[] serialize() {
return staticSerialize(ordinal, numFieldBytes);
}
public static byte[] staticSerialize(Enum<?> enumInstance, int numFieldBytes) {
return staticSerialize(enumInstance.ordinal(), numFieldBytes);
}
public static byte[] staticSerialize(int ordinal, int numFieldBytes) { | return Util.intToBytesWithLen(ordinal, numFieldBytes); |
urbanairship/datacube | src/main/java/com/urbanairship/datacube/bucketers/StringToBytesBucketer.java | // Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
//
// Path: src/main/java/com/urbanairship/datacube/serializables/StringSerializable.java
// public class StringSerializable implements CSerializable {
// private final String s;
//
// public StringSerializable(String s) {
// this.s = s;
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(s);
// }
//
// public static byte[] staticSerialize(String s) {
// try {
// return s.getBytes("UTF8");
// } catch (UnsupportedEncodingException e) {
// // No reasonable JVM will lack UTF8
// throw new RuntimeException(e);
// }
// }
// }
| import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.serializables.StringSerializable; | /*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.bucketers;
/**
* You can use this bucketer to avoid writing your own, in the case where:
* - You have a cube coordinate that's a String
* - You want the bucketer to pass through the String unchanged as the bucket
*/
public class StringToBytesBucketer extends AbstractIdentityBucketer<String> {
private static final StringToBytesBucketer instance = new StringToBytesBucketer();
public static final StringToBytesBucketer getInstance() {
return instance;
}
@Override | // Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
//
// Path: src/main/java/com/urbanairship/datacube/serializables/StringSerializable.java
// public class StringSerializable implements CSerializable {
// private final String s;
//
// public StringSerializable(String s) {
// this.s = s;
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(s);
// }
//
// public static byte[] staticSerialize(String s) {
// try {
// return s.getBytes("UTF8");
// } catch (UnsupportedEncodingException e) {
// // No reasonable JVM will lack UTF8
// throw new RuntimeException(e);
// }
// }
// }
// Path: src/main/java/com/urbanairship/datacube/bucketers/StringToBytesBucketer.java
import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.serializables.StringSerializable;
/*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.bucketers;
/**
* You can use this bucketer to avoid writing your own, in the case where:
* - You have a cube coordinate that's a String
* - You want the bucketer to pass through the String unchanged as the bucket
*/
public class StringToBytesBucketer extends AbstractIdentityBucketer<String> {
private static final StringToBytesBucketer instance = new StringToBytesBucketer();
public static final StringToBytesBucketer getInstance() {
return instance;
}
@Override | public CSerializable makeSerializable(String coord) { |
urbanairship/datacube | src/main/java/com/urbanairship/datacube/bucketers/StringToBytesBucketer.java | // Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
//
// Path: src/main/java/com/urbanairship/datacube/serializables/StringSerializable.java
// public class StringSerializable implements CSerializable {
// private final String s;
//
// public StringSerializable(String s) {
// this.s = s;
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(s);
// }
//
// public static byte[] staticSerialize(String s) {
// try {
// return s.getBytes("UTF8");
// } catch (UnsupportedEncodingException e) {
// // No reasonable JVM will lack UTF8
// throw new RuntimeException(e);
// }
// }
// }
| import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.serializables.StringSerializable; | /*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.bucketers;
/**
* You can use this bucketer to avoid writing your own, in the case where:
* - You have a cube coordinate that's a String
* - You want the bucketer to pass through the String unchanged as the bucket
*/
public class StringToBytesBucketer extends AbstractIdentityBucketer<String> {
private static final StringToBytesBucketer instance = new StringToBytesBucketer();
public static final StringToBytesBucketer getInstance() {
return instance;
}
@Override
public CSerializable makeSerializable(String coord) { | // Path: src/main/java/com/urbanairship/datacube/CSerializable.java
// public interface CSerializable {
// byte[] serialize();
// }
//
// Path: src/main/java/com/urbanairship/datacube/serializables/StringSerializable.java
// public class StringSerializable implements CSerializable {
// private final String s;
//
// public StringSerializable(String s) {
// this.s = s;
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(s);
// }
//
// public static byte[] staticSerialize(String s) {
// try {
// return s.getBytes("UTF8");
// } catch (UnsupportedEncodingException e) {
// // No reasonable JVM will lack UTF8
// throw new RuntimeException(e);
// }
// }
// }
// Path: src/main/java/com/urbanairship/datacube/bucketers/StringToBytesBucketer.java
import com.urbanairship.datacube.CSerializable;
import com.urbanairship.datacube.serializables.StringSerializable;
/*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube.bucketers;
/**
* You can use this bucketer to avoid writing your own, in the case where:
* - You have a cube coordinate that's a String
* - You want the bucketer to pass through the String unchanged as the bucket
*/
public class StringToBytesBucketer extends AbstractIdentityBucketer<String> {
private static final StringToBytesBucketer instance = new StringToBytesBucketer();
public static final StringToBytesBucketer getInstance() {
return instance;
}
@Override
public CSerializable makeSerializable(String coord) { | return new StringSerializable(coord); |
urbanairship/datacube | src/test/java/com/urbanairship/datacube/SerializerTests.java | // Path: src/main/java/com/urbanairship/datacube/serializables/BooleanSerializable.java
// public class BooleanSerializable implements CSerializable {
// private final boolean bool;
// private static final byte[] FALSE_SERIAL = new byte[]{0};
// private static final byte[] TRUE_SERIAL = new byte[]{1};
//
// public BooleanSerializable(boolean bool) {
// this.bool = bool;
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(bool);
// }
//
// public static byte[] staticSerialize(boolean b) {
// if (b) {
// return TRUE_SERIAL;
// } else {
// return FALSE_SERIAL;
// }
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/serializables/EnumSerializable.java
// public class EnumSerializable implements CSerializable {
// private final int ordinal;
// private final int numFieldBytes;
//
// /**
// * @param numFieldBytes the number of bytes to produce for serialized version of this
// * enum
// */
// public EnumSerializable(Enum<?> enumInstance, int numFieldBytes) {
// this.ordinal = enumInstance.ordinal();
// this.numFieldBytes = numFieldBytes;
//
// if (numFieldBytes < 1 || numFieldBytes > 4) {
// throw new IllegalArgumentException("numFieldBytes must be in [1..4]");
// }
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(ordinal, numFieldBytes);
// }
//
// public static byte[] staticSerialize(Enum<?> enumInstance, int numFieldBytes) {
// return staticSerialize(enumInstance.ordinal(), numFieldBytes);
// }
//
// public static byte[] staticSerialize(int ordinal, int numFieldBytes) {
// return Util.intToBytesWithLen(ordinal, numFieldBytes);
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/serializables/StringSerializable.java
// public class StringSerializable implements CSerializable {
// private final String s;
//
// public StringSerializable(String s) {
// this.s = s;
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(s);
// }
//
// public static byte[] staticSerialize(String s) {
// try {
// return s.getBytes("UTF8");
// } catch (UnsupportedEncodingException e) {
// // No reasonable JVM will lack UTF8
// throw new RuntimeException(e);
// }
// }
// }
| import com.urbanairship.datacube.serializables.BooleanSerializable;
import com.urbanairship.datacube.serializables.BytesSerializable;
import com.urbanairship.datacube.serializables.EnumSerializable;
import com.urbanairship.datacube.serializables.IntSerializable;
import com.urbanairship.datacube.serializables.LongSerializable;
import com.urbanairship.datacube.serializables.StringSerializable;
import org.junit.Assert;
import org.junit.Test;
import java.nio.ByteBuffer; | /*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube;
/**
* Test to make sure the serializers do what we expect them to do.
*/
public class SerializerTests {
public static final byte[] FALSE_CASE = new byte[]{0};
public static final byte[] TRUE_CASE = new byte[]{1};
public static final long TEST_LONG = 5L;
public static final String TEST_STRING = "test";
@Test
public void testBooleanSerializable() throws Exception { | // Path: src/main/java/com/urbanairship/datacube/serializables/BooleanSerializable.java
// public class BooleanSerializable implements CSerializable {
// private final boolean bool;
// private static final byte[] FALSE_SERIAL = new byte[]{0};
// private static final byte[] TRUE_SERIAL = new byte[]{1};
//
// public BooleanSerializable(boolean bool) {
// this.bool = bool;
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(bool);
// }
//
// public static byte[] staticSerialize(boolean b) {
// if (b) {
// return TRUE_SERIAL;
// } else {
// return FALSE_SERIAL;
// }
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/serializables/EnumSerializable.java
// public class EnumSerializable implements CSerializable {
// private final int ordinal;
// private final int numFieldBytes;
//
// /**
// * @param numFieldBytes the number of bytes to produce for serialized version of this
// * enum
// */
// public EnumSerializable(Enum<?> enumInstance, int numFieldBytes) {
// this.ordinal = enumInstance.ordinal();
// this.numFieldBytes = numFieldBytes;
//
// if (numFieldBytes < 1 || numFieldBytes > 4) {
// throw new IllegalArgumentException("numFieldBytes must be in [1..4]");
// }
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(ordinal, numFieldBytes);
// }
//
// public static byte[] staticSerialize(Enum<?> enumInstance, int numFieldBytes) {
// return staticSerialize(enumInstance.ordinal(), numFieldBytes);
// }
//
// public static byte[] staticSerialize(int ordinal, int numFieldBytes) {
// return Util.intToBytesWithLen(ordinal, numFieldBytes);
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/serializables/StringSerializable.java
// public class StringSerializable implements CSerializable {
// private final String s;
//
// public StringSerializable(String s) {
// this.s = s;
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(s);
// }
//
// public static byte[] staticSerialize(String s) {
// try {
// return s.getBytes("UTF8");
// } catch (UnsupportedEncodingException e) {
// // No reasonable JVM will lack UTF8
// throw new RuntimeException(e);
// }
// }
// }
// Path: src/test/java/com/urbanairship/datacube/SerializerTests.java
import com.urbanairship.datacube.serializables.BooleanSerializable;
import com.urbanairship.datacube.serializables.BytesSerializable;
import com.urbanairship.datacube.serializables.EnumSerializable;
import com.urbanairship.datacube.serializables.IntSerializable;
import com.urbanairship.datacube.serializables.LongSerializable;
import com.urbanairship.datacube.serializables.StringSerializable;
import org.junit.Assert;
import org.junit.Test;
import java.nio.ByteBuffer;
/*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube;
/**
* Test to make sure the serializers do what we expect them to do.
*/
public class SerializerTests {
public static final byte[] FALSE_CASE = new byte[]{0};
public static final byte[] TRUE_CASE = new byte[]{1};
public static final long TEST_LONG = 5L;
public static final String TEST_STRING = "test";
@Test
public void testBooleanSerializable() throws Exception { | Assert.assertArrayEquals(new BooleanSerializable(true).serialize(), TRUE_CASE); |
urbanairship/datacube | src/test/java/com/urbanairship/datacube/SerializerTests.java | // Path: src/main/java/com/urbanairship/datacube/serializables/BooleanSerializable.java
// public class BooleanSerializable implements CSerializable {
// private final boolean bool;
// private static final byte[] FALSE_SERIAL = new byte[]{0};
// private static final byte[] TRUE_SERIAL = new byte[]{1};
//
// public BooleanSerializable(boolean bool) {
// this.bool = bool;
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(bool);
// }
//
// public static byte[] staticSerialize(boolean b) {
// if (b) {
// return TRUE_SERIAL;
// } else {
// return FALSE_SERIAL;
// }
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/serializables/EnumSerializable.java
// public class EnumSerializable implements CSerializable {
// private final int ordinal;
// private final int numFieldBytes;
//
// /**
// * @param numFieldBytes the number of bytes to produce for serialized version of this
// * enum
// */
// public EnumSerializable(Enum<?> enumInstance, int numFieldBytes) {
// this.ordinal = enumInstance.ordinal();
// this.numFieldBytes = numFieldBytes;
//
// if (numFieldBytes < 1 || numFieldBytes > 4) {
// throw new IllegalArgumentException("numFieldBytes must be in [1..4]");
// }
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(ordinal, numFieldBytes);
// }
//
// public static byte[] staticSerialize(Enum<?> enumInstance, int numFieldBytes) {
// return staticSerialize(enumInstance.ordinal(), numFieldBytes);
// }
//
// public static byte[] staticSerialize(int ordinal, int numFieldBytes) {
// return Util.intToBytesWithLen(ordinal, numFieldBytes);
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/serializables/StringSerializable.java
// public class StringSerializable implements CSerializable {
// private final String s;
//
// public StringSerializable(String s) {
// this.s = s;
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(s);
// }
//
// public static byte[] staticSerialize(String s) {
// try {
// return s.getBytes("UTF8");
// } catch (UnsupportedEncodingException e) {
// // No reasonable JVM will lack UTF8
// throw new RuntimeException(e);
// }
// }
// }
| import com.urbanairship.datacube.serializables.BooleanSerializable;
import com.urbanairship.datacube.serializables.BytesSerializable;
import com.urbanairship.datacube.serializables.EnumSerializable;
import com.urbanairship.datacube.serializables.IntSerializable;
import com.urbanairship.datacube.serializables.LongSerializable;
import com.urbanairship.datacube.serializables.StringSerializable;
import org.junit.Assert;
import org.junit.Test;
import java.nio.ByteBuffer; | /*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube;
/**
* Test to make sure the serializers do what we expect them to do.
*/
public class SerializerTests {
public static final byte[] FALSE_CASE = new byte[]{0};
public static final byte[] TRUE_CASE = new byte[]{1};
public static final long TEST_LONG = 5L;
public static final String TEST_STRING = "test";
@Test
public void testBooleanSerializable() throws Exception {
Assert.assertArrayEquals(new BooleanSerializable(true).serialize(), TRUE_CASE);
Assert.assertArrayEquals(new BooleanSerializable(false).serialize(), FALSE_CASE);
}
@Test
public void testBytesSerializable() throws Exception {
Assert.assertArrayEquals(
new BytesSerializable(new byte[]{1}).serialize(), TRUE_CASE);
Assert.assertArrayEquals(
new BytesSerializable(new byte[]{0}).serialize(), FALSE_CASE);
}
@Test
public void testStringSerializable() throws Exception { | // Path: src/main/java/com/urbanairship/datacube/serializables/BooleanSerializable.java
// public class BooleanSerializable implements CSerializable {
// private final boolean bool;
// private static final byte[] FALSE_SERIAL = new byte[]{0};
// private static final byte[] TRUE_SERIAL = new byte[]{1};
//
// public BooleanSerializable(boolean bool) {
// this.bool = bool;
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(bool);
// }
//
// public static byte[] staticSerialize(boolean b) {
// if (b) {
// return TRUE_SERIAL;
// } else {
// return FALSE_SERIAL;
// }
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/serializables/EnumSerializable.java
// public class EnumSerializable implements CSerializable {
// private final int ordinal;
// private final int numFieldBytes;
//
// /**
// * @param numFieldBytes the number of bytes to produce for serialized version of this
// * enum
// */
// public EnumSerializable(Enum<?> enumInstance, int numFieldBytes) {
// this.ordinal = enumInstance.ordinal();
// this.numFieldBytes = numFieldBytes;
//
// if (numFieldBytes < 1 || numFieldBytes > 4) {
// throw new IllegalArgumentException("numFieldBytes must be in [1..4]");
// }
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(ordinal, numFieldBytes);
// }
//
// public static byte[] staticSerialize(Enum<?> enumInstance, int numFieldBytes) {
// return staticSerialize(enumInstance.ordinal(), numFieldBytes);
// }
//
// public static byte[] staticSerialize(int ordinal, int numFieldBytes) {
// return Util.intToBytesWithLen(ordinal, numFieldBytes);
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/serializables/StringSerializable.java
// public class StringSerializable implements CSerializable {
// private final String s;
//
// public StringSerializable(String s) {
// this.s = s;
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(s);
// }
//
// public static byte[] staticSerialize(String s) {
// try {
// return s.getBytes("UTF8");
// } catch (UnsupportedEncodingException e) {
// // No reasonable JVM will lack UTF8
// throw new RuntimeException(e);
// }
// }
// }
// Path: src/test/java/com/urbanairship/datacube/SerializerTests.java
import com.urbanairship.datacube.serializables.BooleanSerializable;
import com.urbanairship.datacube.serializables.BytesSerializable;
import com.urbanairship.datacube.serializables.EnumSerializable;
import com.urbanairship.datacube.serializables.IntSerializable;
import com.urbanairship.datacube.serializables.LongSerializable;
import com.urbanairship.datacube.serializables.StringSerializable;
import org.junit.Assert;
import org.junit.Test;
import java.nio.ByteBuffer;
/*
Copyright 2012 Urban Airship and Contributors
*/
package com.urbanairship.datacube;
/**
* Test to make sure the serializers do what we expect them to do.
*/
public class SerializerTests {
public static final byte[] FALSE_CASE = new byte[]{0};
public static final byte[] TRUE_CASE = new byte[]{1};
public static final long TEST_LONG = 5L;
public static final String TEST_STRING = "test";
@Test
public void testBooleanSerializable() throws Exception {
Assert.assertArrayEquals(new BooleanSerializable(true).serialize(), TRUE_CASE);
Assert.assertArrayEquals(new BooleanSerializable(false).serialize(), FALSE_CASE);
}
@Test
public void testBytesSerializable() throws Exception {
Assert.assertArrayEquals(
new BytesSerializable(new byte[]{1}).serialize(), TRUE_CASE);
Assert.assertArrayEquals(
new BytesSerializable(new byte[]{0}).serialize(), FALSE_CASE);
}
@Test
public void testStringSerializable() throws Exception { | Assert.assertArrayEquals(new StringSerializable(TEST_STRING).serialize(), |
urbanairship/datacube | src/test/java/com/urbanairship/datacube/SerializerTests.java | // Path: src/main/java/com/urbanairship/datacube/serializables/BooleanSerializable.java
// public class BooleanSerializable implements CSerializable {
// private final boolean bool;
// private static final byte[] FALSE_SERIAL = new byte[]{0};
// private static final byte[] TRUE_SERIAL = new byte[]{1};
//
// public BooleanSerializable(boolean bool) {
// this.bool = bool;
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(bool);
// }
//
// public static byte[] staticSerialize(boolean b) {
// if (b) {
// return TRUE_SERIAL;
// } else {
// return FALSE_SERIAL;
// }
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/serializables/EnumSerializable.java
// public class EnumSerializable implements CSerializable {
// private final int ordinal;
// private final int numFieldBytes;
//
// /**
// * @param numFieldBytes the number of bytes to produce for serialized version of this
// * enum
// */
// public EnumSerializable(Enum<?> enumInstance, int numFieldBytes) {
// this.ordinal = enumInstance.ordinal();
// this.numFieldBytes = numFieldBytes;
//
// if (numFieldBytes < 1 || numFieldBytes > 4) {
// throw new IllegalArgumentException("numFieldBytes must be in [1..4]");
// }
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(ordinal, numFieldBytes);
// }
//
// public static byte[] staticSerialize(Enum<?> enumInstance, int numFieldBytes) {
// return staticSerialize(enumInstance.ordinal(), numFieldBytes);
// }
//
// public static byte[] staticSerialize(int ordinal, int numFieldBytes) {
// return Util.intToBytesWithLen(ordinal, numFieldBytes);
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/serializables/StringSerializable.java
// public class StringSerializable implements CSerializable {
// private final String s;
//
// public StringSerializable(String s) {
// this.s = s;
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(s);
// }
//
// public static byte[] staticSerialize(String s) {
// try {
// return s.getBytes("UTF8");
// } catch (UnsupportedEncodingException e) {
// // No reasonable JVM will lack UTF8
// throw new RuntimeException(e);
// }
// }
// }
| import com.urbanairship.datacube.serializables.BooleanSerializable;
import com.urbanairship.datacube.serializables.BytesSerializable;
import com.urbanairship.datacube.serializables.EnumSerializable;
import com.urbanairship.datacube.serializables.IntSerializable;
import com.urbanairship.datacube.serializables.LongSerializable;
import com.urbanairship.datacube.serializables.StringSerializable;
import org.junit.Assert;
import org.junit.Test;
import java.nio.ByteBuffer; | public void testBooleanSerializable() throws Exception {
Assert.assertArrayEquals(new BooleanSerializable(true).serialize(), TRUE_CASE);
Assert.assertArrayEquals(new BooleanSerializable(false).serialize(), FALSE_CASE);
}
@Test
public void testBytesSerializable() throws Exception {
Assert.assertArrayEquals(
new BytesSerializable(new byte[]{1}).serialize(), TRUE_CASE);
Assert.assertArrayEquals(
new BytesSerializable(new byte[]{0}).serialize(), FALSE_CASE);
}
@Test
public void testStringSerializable() throws Exception {
Assert.assertArrayEquals(new StringSerializable(TEST_STRING).serialize(),
TEST_STRING.getBytes());
}
@Test
public void testLongSerializable() throws Exception {
Assert.assertArrayEquals(new LongSerializable(TEST_LONG).serialize(),
ByteBuffer.allocate(8).putLong(TEST_LONG).array());
}
private enum TestEnum {ZEROTH, FIRST, SECOND}
@Test
public void testEnumSerializable() throws Exception {
Assert.assertArrayEquals(Util.intToBytes(0), | // Path: src/main/java/com/urbanairship/datacube/serializables/BooleanSerializable.java
// public class BooleanSerializable implements CSerializable {
// private final boolean bool;
// private static final byte[] FALSE_SERIAL = new byte[]{0};
// private static final byte[] TRUE_SERIAL = new byte[]{1};
//
// public BooleanSerializable(boolean bool) {
// this.bool = bool;
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(bool);
// }
//
// public static byte[] staticSerialize(boolean b) {
// if (b) {
// return TRUE_SERIAL;
// } else {
// return FALSE_SERIAL;
// }
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/serializables/EnumSerializable.java
// public class EnumSerializable implements CSerializable {
// private final int ordinal;
// private final int numFieldBytes;
//
// /**
// * @param numFieldBytes the number of bytes to produce for serialized version of this
// * enum
// */
// public EnumSerializable(Enum<?> enumInstance, int numFieldBytes) {
// this.ordinal = enumInstance.ordinal();
// this.numFieldBytes = numFieldBytes;
//
// if (numFieldBytes < 1 || numFieldBytes > 4) {
// throw new IllegalArgumentException("numFieldBytes must be in [1..4]");
// }
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(ordinal, numFieldBytes);
// }
//
// public static byte[] staticSerialize(Enum<?> enumInstance, int numFieldBytes) {
// return staticSerialize(enumInstance.ordinal(), numFieldBytes);
// }
//
// public static byte[] staticSerialize(int ordinal, int numFieldBytes) {
// return Util.intToBytesWithLen(ordinal, numFieldBytes);
// }
// }
//
// Path: src/main/java/com/urbanairship/datacube/serializables/StringSerializable.java
// public class StringSerializable implements CSerializable {
// private final String s;
//
// public StringSerializable(String s) {
// this.s = s;
// }
//
// @Override
// public byte[] serialize() {
// return staticSerialize(s);
// }
//
// public static byte[] staticSerialize(String s) {
// try {
// return s.getBytes("UTF8");
// } catch (UnsupportedEncodingException e) {
// // No reasonable JVM will lack UTF8
// throw new RuntimeException(e);
// }
// }
// }
// Path: src/test/java/com/urbanairship/datacube/SerializerTests.java
import com.urbanairship.datacube.serializables.BooleanSerializable;
import com.urbanairship.datacube.serializables.BytesSerializable;
import com.urbanairship.datacube.serializables.EnumSerializable;
import com.urbanairship.datacube.serializables.IntSerializable;
import com.urbanairship.datacube.serializables.LongSerializable;
import com.urbanairship.datacube.serializables.StringSerializable;
import org.junit.Assert;
import org.junit.Test;
import java.nio.ByteBuffer;
public void testBooleanSerializable() throws Exception {
Assert.assertArrayEquals(new BooleanSerializable(true).serialize(), TRUE_CASE);
Assert.assertArrayEquals(new BooleanSerializable(false).serialize(), FALSE_CASE);
}
@Test
public void testBytesSerializable() throws Exception {
Assert.assertArrayEquals(
new BytesSerializable(new byte[]{1}).serialize(), TRUE_CASE);
Assert.assertArrayEquals(
new BytesSerializable(new byte[]{0}).serialize(), FALSE_CASE);
}
@Test
public void testStringSerializable() throws Exception {
Assert.assertArrayEquals(new StringSerializable(TEST_STRING).serialize(),
TEST_STRING.getBytes());
}
@Test
public void testLongSerializable() throws Exception {
Assert.assertArrayEquals(new LongSerializable(TEST_LONG).serialize(),
ByteBuffer.allocate(8).putLong(TEST_LONG).array());
}
private enum TestEnum {ZEROTH, FIRST, SECOND}
@Test
public void testEnumSerializable() throws Exception {
Assert.assertArrayEquals(Util.intToBytes(0), | EnumSerializable.staticSerialize(TestEnum.ZEROTH, 4)); |
flyver/Flyver-SDK | IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/SocketIOIOConnection.java | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIOConnection.java
// public interface IOIOConnection {
// void waitForConnect() throws ConnectionLostException;
//
// void disconnect();
//
// InputStream getInputStream() throws ConnectionLostException;
//
// OutputStream getOutputStream() throws ConnectionLostException;
//
// /**
// * Can this connection be closed. Normally the answer would be "true", but
// * some weird connections cannot be closed and need the higher layer to do
// * a "soft close" instead.
// *
// * @return true This connection can be closed.
// */
// boolean canClose();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/Log.java
// public class Log {
// public static int println(int priority, String tag, String msg) {
// return android.util.Log.println(priority, tag, msg);
// }
//
// public static void e(String tag, String message) {
// android.util.Log.e(tag, message);
// }
//
// public static void e(String tag, String message, Throwable tr) {
// android.util.Log.e(tag, message, tr);
// }
//
// public static void w(String tag, String message) {
// android.util.Log.w(tag, message);
// }
//
// public static void w(String tag, String message, Throwable tr) {
// android.util.Log.w(tag, message);
// }
//
// public static void i(String tag, String message) {
// android.util.Log.i(tag, message);
// }
//
// public static void d(String tag, String message) {
// android.util.Log.d(tag, message);
// }
//
// public static void v(String tag, String message) {
// android.util.Log.v(tag, message);
// }
// }
| import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import ioio.lib.api.IOIOConnection;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.spi.Log;
import java.io.BufferedOutputStream;
import java.io.IOException; | /*
* Copyright 2011 Ytai Ben-Tsvi. All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARSHAN POURSOHI OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied.
*/
package ioio.lib.impl;
public class SocketIOIOConnection implements IOIOConnection {
private static final String TAG = "SocketIOIOConnection";
private final int port_;
private ServerSocket server_ = null;
private Socket socket_ = null;
private boolean disconnect_ = false;
private boolean server_owned_by_connect_ = true;
private boolean socket_owned_by_connect_ = true;
private InputStream inputStream_;
private OutputStream outputStream_;
public SocketIOIOConnection(int port) {
port_ = port;
}
@Override
public void waitForConnect() throws ConnectionLostException {
try {
synchronized (this) {
if (disconnect_) {
throw new ConnectionLostException();
} | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIOConnection.java
// public interface IOIOConnection {
// void waitForConnect() throws ConnectionLostException;
//
// void disconnect();
//
// InputStream getInputStream() throws ConnectionLostException;
//
// OutputStream getOutputStream() throws ConnectionLostException;
//
// /**
// * Can this connection be closed. Normally the answer would be "true", but
// * some weird connections cannot be closed and need the higher layer to do
// * a "soft close" instead.
// *
// * @return true This connection can be closed.
// */
// boolean canClose();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/Log.java
// public class Log {
// public static int println(int priority, String tag, String msg) {
// return android.util.Log.println(priority, tag, msg);
// }
//
// public static void e(String tag, String message) {
// android.util.Log.e(tag, message);
// }
//
// public static void e(String tag, String message, Throwable tr) {
// android.util.Log.e(tag, message, tr);
// }
//
// public static void w(String tag, String message) {
// android.util.Log.w(tag, message);
// }
//
// public static void w(String tag, String message, Throwable tr) {
// android.util.Log.w(tag, message);
// }
//
// public static void i(String tag, String message) {
// android.util.Log.i(tag, message);
// }
//
// public static void d(String tag, String message) {
// android.util.Log.d(tag, message);
// }
//
// public static void v(String tag, String message) {
// android.util.Log.v(tag, message);
// }
// }
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/SocketIOIOConnection.java
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import ioio.lib.api.IOIOConnection;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.spi.Log;
import java.io.BufferedOutputStream;
import java.io.IOException;
/*
* Copyright 2011 Ytai Ben-Tsvi. All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARSHAN POURSOHI OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied.
*/
package ioio.lib.impl;
public class SocketIOIOConnection implements IOIOConnection {
private static final String TAG = "SocketIOIOConnection";
private final int port_;
private ServerSocket server_ = null;
private Socket socket_ = null;
private boolean disconnect_ = false;
private boolean server_owned_by_connect_ = true;
private boolean socket_owned_by_connect_ = true;
private InputStream inputStream_;
private OutputStream outputStream_;
public SocketIOIOConnection(int port) {
port_ = port;
}
@Override
public void waitForConnect() throws ConnectionLostException {
try {
synchronized (this) {
if (disconnect_) {
throw new ConnectionLostException();
} | Log.v(TAG, "Creating server socket"); |
flyver/Flyver-SDK | IOIO/iOIOLibAccessory/src/main/java/ioio/lib/android/accessory/AccessoryConnectionBootstrap.java | // Path: IOIO/iOIOLibAccessory/src/main/java/ioio/lib/android/accessory/Adapter.java
// static interface UsbAccessoryInterface {
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIOConnection.java
// public interface IOIOConnection {
// void waitForConnect() throws ConnectionLostException;
//
// void disconnect();
//
// InputStream getInputStream() throws ConnectionLostException;
//
// OutputStream getOutputStream() throws ConnectionLostException;
//
// /**
// * Can this connection be closed. Normally the answer would be "true", but
// * some weird connections cannot be closed and need the higher layer to do
// * a "soft close" instead.
// *
// * @return true This connection can be closed.
// */
// boolean canClose();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/FixedReadBufferedInputStream.java
// public class FixedReadBufferedInputStream extends InputStream {
// private int bufferIndex_ = 0;
// private int validData_ = 0;
// private final byte[] buffer_;
// private final InputStream source_;
//
// public FixedReadBufferedInputStream(InputStream source, int size) {
// buffer_ = new byte[size];
// source_ = source;
// }
//
// @Override
// public int available() throws IOException {
// return validData_ - bufferIndex_;
// }
//
// @Override
// public void close() throws IOException {
// source_.close();
// }
//
// @Override
// public int read(byte[] buffer, int offset, int length) throws IOException {
// fillIfEmpty();
// if (validData_ == -1) {
// return -1;
// }
// length = Math.min(length, validData_ - bufferIndex_);
// System.arraycopy(buffer_, bufferIndex_, buffer, offset, length);
// bufferIndex_ += length;
// return length;
// }
//
// @Override
// public int read(byte[] buffer) throws IOException {
// return read(buffer, 0, buffer.length);
// }
//
// @Override
// public int read() throws IOException {
// fillIfEmpty();
// if (validData_ == -1) {
// return -1;
// }
// return buffer_[bufferIndex_++] & 0xFF;
// }
//
// @Override
// public long skip(long byteCount) throws IOException {
// long skipped = 0;
// while (byteCount > 0) {
// fillIfEmpty();
// if (validData_ == -1) {
// return skipped;
// }
// int count = (int) Math.min(available(), byteCount);
// byteCount -= count;
// bufferIndex_ += count;
// skipped += count;
// }
// return skipped;
// }
//
// private void fillIfEmpty() throws IOException {
// while (available() == 0 && validData_ != -1) {
// fill();
// }
// }
//
// private void fill() throws IOException {
// bufferIndex_ = 0;
// validData_ = source_.read(buffer_);
// }
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionBootstrap.java
// public interface IOIOConnectionBootstrap {
// public void getFactories(Collection<IOIOConnectionFactory> result);
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionFactory.java
// public interface IOIOConnectionFactory {
// /**
// * A unique name of the connection type. Typically a fully-qualified
// * name of the connection class.
// */
// public String getType();
//
// /**
// * Extra information on the connection. This is specific to the
// * connection type. For example, for a Bluetooth connection, this is an
// * array containing the name and the Bluetooth address of the remote
// * IOIO.
// */
// public Object getExtra();
//
// public IOIOConnection createConnection();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/util/android/ContextWrapperDependent.java
// public interface ContextWrapperDependent {
// public void onCreate(ContextWrapper wrapper);
//
// public void onDestroy();
//
// public void open();
//
// public void reopen();
//
// public void close();
// }
| import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import ioio.lib.android.accessory.Adapter.UsbAccessoryInterface;
import ioio.lib.api.IOIOConnection;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.impl.FixedReadBufferedInputStream;
import ioio.lib.spi.IOIOConnectionBootstrap;
import ioio.lib.spi.IOIOConnectionFactory;
import ioio.lib.spi.NoRuntimeSupportException;
import ioio.lib.util.android.ContextWrapperDependent; | if (accessory_ != null) {
if (usbManager_.hasPermission(accessory_)) {
openStreams();
} else {
pendingIntent_ = PendingIntent.getBroadcast(activity_, 0, new Intent(
ACTION_USB_PERMISSION), 0);
usbManager_.requestPermission(accessory_, pendingIntent_);
setState(State.WAIT_PERMISSION);
}
} else {
Log.d(TAG, "No accessory found.");
}
}
@Override
public void reopen() {
open();
}
@Override
public synchronized void close() {
if (state_ == State.OPEN) {
closeStreams();
} else if (state_ == State.WAIT_PERMISSION) {
pendingIntent_.cancel();
}
setState(State.CLOSED);
}
@Override | // Path: IOIO/iOIOLibAccessory/src/main/java/ioio/lib/android/accessory/Adapter.java
// static interface UsbAccessoryInterface {
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIOConnection.java
// public interface IOIOConnection {
// void waitForConnect() throws ConnectionLostException;
//
// void disconnect();
//
// InputStream getInputStream() throws ConnectionLostException;
//
// OutputStream getOutputStream() throws ConnectionLostException;
//
// /**
// * Can this connection be closed. Normally the answer would be "true", but
// * some weird connections cannot be closed and need the higher layer to do
// * a "soft close" instead.
// *
// * @return true This connection can be closed.
// */
// boolean canClose();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/FixedReadBufferedInputStream.java
// public class FixedReadBufferedInputStream extends InputStream {
// private int bufferIndex_ = 0;
// private int validData_ = 0;
// private final byte[] buffer_;
// private final InputStream source_;
//
// public FixedReadBufferedInputStream(InputStream source, int size) {
// buffer_ = new byte[size];
// source_ = source;
// }
//
// @Override
// public int available() throws IOException {
// return validData_ - bufferIndex_;
// }
//
// @Override
// public void close() throws IOException {
// source_.close();
// }
//
// @Override
// public int read(byte[] buffer, int offset, int length) throws IOException {
// fillIfEmpty();
// if (validData_ == -1) {
// return -1;
// }
// length = Math.min(length, validData_ - bufferIndex_);
// System.arraycopy(buffer_, bufferIndex_, buffer, offset, length);
// bufferIndex_ += length;
// return length;
// }
//
// @Override
// public int read(byte[] buffer) throws IOException {
// return read(buffer, 0, buffer.length);
// }
//
// @Override
// public int read() throws IOException {
// fillIfEmpty();
// if (validData_ == -1) {
// return -1;
// }
// return buffer_[bufferIndex_++] & 0xFF;
// }
//
// @Override
// public long skip(long byteCount) throws IOException {
// long skipped = 0;
// while (byteCount > 0) {
// fillIfEmpty();
// if (validData_ == -1) {
// return skipped;
// }
// int count = (int) Math.min(available(), byteCount);
// byteCount -= count;
// bufferIndex_ += count;
// skipped += count;
// }
// return skipped;
// }
//
// private void fillIfEmpty() throws IOException {
// while (available() == 0 && validData_ != -1) {
// fill();
// }
// }
//
// private void fill() throws IOException {
// bufferIndex_ = 0;
// validData_ = source_.read(buffer_);
// }
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionBootstrap.java
// public interface IOIOConnectionBootstrap {
// public void getFactories(Collection<IOIOConnectionFactory> result);
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionFactory.java
// public interface IOIOConnectionFactory {
// /**
// * A unique name of the connection type. Typically a fully-qualified
// * name of the connection class.
// */
// public String getType();
//
// /**
// * Extra information on the connection. This is specific to the
// * connection type. For example, for a Bluetooth connection, this is an
// * array containing the name and the Bluetooth address of the remote
// * IOIO.
// */
// public Object getExtra();
//
// public IOIOConnection createConnection();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/util/android/ContextWrapperDependent.java
// public interface ContextWrapperDependent {
// public void onCreate(ContextWrapper wrapper);
//
// public void onDestroy();
//
// public void open();
//
// public void reopen();
//
// public void close();
// }
// Path: IOIO/iOIOLibAccessory/src/main/java/ioio/lib/android/accessory/AccessoryConnectionBootstrap.java
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import ioio.lib.android.accessory.Adapter.UsbAccessoryInterface;
import ioio.lib.api.IOIOConnection;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.impl.FixedReadBufferedInputStream;
import ioio.lib.spi.IOIOConnectionBootstrap;
import ioio.lib.spi.IOIOConnectionFactory;
import ioio.lib.spi.NoRuntimeSupportException;
import ioio.lib.util.android.ContextWrapperDependent;
if (accessory_ != null) {
if (usbManager_.hasPermission(accessory_)) {
openStreams();
} else {
pendingIntent_ = PendingIntent.getBroadcast(activity_, 0, new Intent(
ACTION_USB_PERMISSION), 0);
usbManager_.requestPermission(accessory_, pendingIntent_);
setState(State.WAIT_PERMISSION);
}
} else {
Log.d(TAG, "No accessory found.");
}
}
@Override
public void reopen() {
open();
}
@Override
public synchronized void close() {
if (state_ == State.OPEN) {
closeStreams();
} else if (state_ == State.WAIT_PERMISSION) {
pendingIntent_.cancel();
}
setState(State.CLOSED);
}
@Override | public IOIOConnection createConnection() { |
flyver/Flyver-SDK | IOIO/iOIOLibAccessory/src/main/java/ioio/lib/android/accessory/AccessoryConnectionBootstrap.java | // Path: IOIO/iOIOLibAccessory/src/main/java/ioio/lib/android/accessory/Adapter.java
// static interface UsbAccessoryInterface {
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIOConnection.java
// public interface IOIOConnection {
// void waitForConnect() throws ConnectionLostException;
//
// void disconnect();
//
// InputStream getInputStream() throws ConnectionLostException;
//
// OutputStream getOutputStream() throws ConnectionLostException;
//
// /**
// * Can this connection be closed. Normally the answer would be "true", but
// * some weird connections cannot be closed and need the higher layer to do
// * a "soft close" instead.
// *
// * @return true This connection can be closed.
// */
// boolean canClose();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/FixedReadBufferedInputStream.java
// public class FixedReadBufferedInputStream extends InputStream {
// private int bufferIndex_ = 0;
// private int validData_ = 0;
// private final byte[] buffer_;
// private final InputStream source_;
//
// public FixedReadBufferedInputStream(InputStream source, int size) {
// buffer_ = new byte[size];
// source_ = source;
// }
//
// @Override
// public int available() throws IOException {
// return validData_ - bufferIndex_;
// }
//
// @Override
// public void close() throws IOException {
// source_.close();
// }
//
// @Override
// public int read(byte[] buffer, int offset, int length) throws IOException {
// fillIfEmpty();
// if (validData_ == -1) {
// return -1;
// }
// length = Math.min(length, validData_ - bufferIndex_);
// System.arraycopy(buffer_, bufferIndex_, buffer, offset, length);
// bufferIndex_ += length;
// return length;
// }
//
// @Override
// public int read(byte[] buffer) throws IOException {
// return read(buffer, 0, buffer.length);
// }
//
// @Override
// public int read() throws IOException {
// fillIfEmpty();
// if (validData_ == -1) {
// return -1;
// }
// return buffer_[bufferIndex_++] & 0xFF;
// }
//
// @Override
// public long skip(long byteCount) throws IOException {
// long skipped = 0;
// while (byteCount > 0) {
// fillIfEmpty();
// if (validData_ == -1) {
// return skipped;
// }
// int count = (int) Math.min(available(), byteCount);
// byteCount -= count;
// bufferIndex_ += count;
// skipped += count;
// }
// return skipped;
// }
//
// private void fillIfEmpty() throws IOException {
// while (available() == 0 && validData_ != -1) {
// fill();
// }
// }
//
// private void fill() throws IOException {
// bufferIndex_ = 0;
// validData_ = source_.read(buffer_);
// }
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionBootstrap.java
// public interface IOIOConnectionBootstrap {
// public void getFactories(Collection<IOIOConnectionFactory> result);
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionFactory.java
// public interface IOIOConnectionFactory {
// /**
// * A unique name of the connection type. Typically a fully-qualified
// * name of the connection class.
// */
// public String getType();
//
// /**
// * Extra information on the connection. This is specific to the
// * connection type. For example, for a Bluetooth connection, this is an
// * array containing the name and the Bluetooth address of the remote
// * IOIO.
// */
// public Object getExtra();
//
// public IOIOConnection createConnection();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/util/android/ContextWrapperDependent.java
// public interface ContextWrapperDependent {
// public void onCreate(ContextWrapper wrapper);
//
// public void onDestroy();
//
// public void open();
//
// public void reopen();
//
// public void close();
// }
| import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import ioio.lib.android.accessory.Adapter.UsbAccessoryInterface;
import ioio.lib.api.IOIOConnection;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.impl.FixedReadBufferedInputStream;
import ioio.lib.spi.IOIOConnectionBootstrap;
import ioio.lib.spi.IOIOConnectionFactory;
import ioio.lib.spi.NoRuntimeSupportException;
import ioio.lib.util.android.ContextWrapperDependent; | return localInputStream_;
}
@Override
public OutputStream getOutputStream() throws ConnectionLostException {
return localOutputStream_;
}
@Override
public boolean canClose() {
return false;
}
@Override
public void waitForConnect() throws ConnectionLostException {
synchronized (AccessoryConnectionBootstrap.this) {
if (instanceState_ != InstanceState.INIT) {
throw new IllegalStateException("waitForConnect() may only be called once");
}
while (instanceState_ != InstanceState.DEAD && state_ != State.OPEN) {
try {
AccessoryConnectionBootstrap.this.wait();
} catch (InterruptedException e) {
}
}
if (instanceState_ == InstanceState.DEAD) {
throw new ConnectionLostException();
}
// Apparently, some Android devices (e.g. Nexus 5) only support read operations of
// multiples of the endpoint buffer size. So there you have it! | // Path: IOIO/iOIOLibAccessory/src/main/java/ioio/lib/android/accessory/Adapter.java
// static interface UsbAccessoryInterface {
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIOConnection.java
// public interface IOIOConnection {
// void waitForConnect() throws ConnectionLostException;
//
// void disconnect();
//
// InputStream getInputStream() throws ConnectionLostException;
//
// OutputStream getOutputStream() throws ConnectionLostException;
//
// /**
// * Can this connection be closed. Normally the answer would be "true", but
// * some weird connections cannot be closed and need the higher layer to do
// * a "soft close" instead.
// *
// * @return true This connection can be closed.
// */
// boolean canClose();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/FixedReadBufferedInputStream.java
// public class FixedReadBufferedInputStream extends InputStream {
// private int bufferIndex_ = 0;
// private int validData_ = 0;
// private final byte[] buffer_;
// private final InputStream source_;
//
// public FixedReadBufferedInputStream(InputStream source, int size) {
// buffer_ = new byte[size];
// source_ = source;
// }
//
// @Override
// public int available() throws IOException {
// return validData_ - bufferIndex_;
// }
//
// @Override
// public void close() throws IOException {
// source_.close();
// }
//
// @Override
// public int read(byte[] buffer, int offset, int length) throws IOException {
// fillIfEmpty();
// if (validData_ == -1) {
// return -1;
// }
// length = Math.min(length, validData_ - bufferIndex_);
// System.arraycopy(buffer_, bufferIndex_, buffer, offset, length);
// bufferIndex_ += length;
// return length;
// }
//
// @Override
// public int read(byte[] buffer) throws IOException {
// return read(buffer, 0, buffer.length);
// }
//
// @Override
// public int read() throws IOException {
// fillIfEmpty();
// if (validData_ == -1) {
// return -1;
// }
// return buffer_[bufferIndex_++] & 0xFF;
// }
//
// @Override
// public long skip(long byteCount) throws IOException {
// long skipped = 0;
// while (byteCount > 0) {
// fillIfEmpty();
// if (validData_ == -1) {
// return skipped;
// }
// int count = (int) Math.min(available(), byteCount);
// byteCount -= count;
// bufferIndex_ += count;
// skipped += count;
// }
// return skipped;
// }
//
// private void fillIfEmpty() throws IOException {
// while (available() == 0 && validData_ != -1) {
// fill();
// }
// }
//
// private void fill() throws IOException {
// bufferIndex_ = 0;
// validData_ = source_.read(buffer_);
// }
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionBootstrap.java
// public interface IOIOConnectionBootstrap {
// public void getFactories(Collection<IOIOConnectionFactory> result);
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionFactory.java
// public interface IOIOConnectionFactory {
// /**
// * A unique name of the connection type. Typically a fully-qualified
// * name of the connection class.
// */
// public String getType();
//
// /**
// * Extra information on the connection. This is specific to the
// * connection type. For example, for a Bluetooth connection, this is an
// * array containing the name and the Bluetooth address of the remote
// * IOIO.
// */
// public Object getExtra();
//
// public IOIOConnection createConnection();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/util/android/ContextWrapperDependent.java
// public interface ContextWrapperDependent {
// public void onCreate(ContextWrapper wrapper);
//
// public void onDestroy();
//
// public void open();
//
// public void reopen();
//
// public void close();
// }
// Path: IOIO/iOIOLibAccessory/src/main/java/ioio/lib/android/accessory/AccessoryConnectionBootstrap.java
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import ioio.lib.android.accessory.Adapter.UsbAccessoryInterface;
import ioio.lib.api.IOIOConnection;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.impl.FixedReadBufferedInputStream;
import ioio.lib.spi.IOIOConnectionBootstrap;
import ioio.lib.spi.IOIOConnectionFactory;
import ioio.lib.spi.NoRuntimeSupportException;
import ioio.lib.util.android.ContextWrapperDependent;
return localInputStream_;
}
@Override
public OutputStream getOutputStream() throws ConnectionLostException {
return localOutputStream_;
}
@Override
public boolean canClose() {
return false;
}
@Override
public void waitForConnect() throws ConnectionLostException {
synchronized (AccessoryConnectionBootstrap.this) {
if (instanceState_ != InstanceState.INIT) {
throw new IllegalStateException("waitForConnect() may only be called once");
}
while (instanceState_ != InstanceState.DEAD && state_ != State.OPEN) {
try {
AccessoryConnectionBootstrap.this.wait();
} catch (InterruptedException e) {
}
}
if (instanceState_ == InstanceState.DEAD) {
throw new ConnectionLostException();
}
// Apparently, some Android devices (e.g. Nexus 5) only support read operations of
// multiples of the endpoint buffer size. So there you have it! | localInputStream_ = new FixedReadBufferedInputStream(inputStream_, 1024); |
flyver/Flyver-SDK | IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/IncomingState.java | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/IOIOProtocol.java
// public interface IncomingHandler {
// public void handleEstablishConnection(byte[] hardwareId, byte[] bootloaderId,
// byte[] firmwareId);
//
// public void handleConnectionLost();
//
// public void handleSoftReset();
//
// public void handleCheckInterfaceResponse(boolean supported);
//
// public void handleSetChangeNotify(int pin, boolean changeNotify);
//
// public void handleReportDigitalInStatus(int pin, boolean level);
//
// public void handleRegisterPeriodicDigitalSampling(int pin, int freqScale);
//
// public void handleReportPeriodicDigitalInStatus(int frameNum, boolean values[]);
//
// public void handleAnalogPinStatus(int pin, boolean open);
//
// public void handleReportAnalogInStatus(List<Integer> pins, List<Integer> values);
//
// public void handleUartOpen(int uartNum);
//
// public void handleUartClose(int uartNum);
//
// public void handleUartData(int uartNum, int numBytes, byte data[]);
//
// public void handleUartReportTxStatus(int uartNum, int bytesRemaining);
//
// public void handleSpiOpen(int spiNum);
//
// public void handleSpiClose(int spiNum);
//
// public void handleSpiData(int spiNum, int ssPin, byte data[], int dataBytes);
//
// public void handleSpiReportTxStatus(int spiNum, int bytesRemaining);
//
// public void handleI2cOpen(int i2cNum);
//
// public void handleI2cClose(int i2cNum);
//
// public void handleI2cResult(int i2cNum, int size, byte[] data);
//
// public void handleI2cReportTxStatus(int spiNum, int bytesRemaining);
//
// void handleIcspOpen();
//
// void handleIcspClose();
//
// void handleIcspReportRxStatus(int bytesRemaining);
//
// void handleIcspResult(int size, byte[] data);
//
// public void handleIncapReport(int incapNum, int size, byte[] data);
//
// public void handleIncapClose(int incapNum);
//
// public void handleIncapOpen(int incapNum);
//
// public void handleCapSenseReport(int pinNum, int value);
//
// public void handleSetCapSenseSampling(int pinNum, boolean enable);
//
// public void handleSequencerEvent(SequencerEvent event, int arg);
//
// public void handleSync();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/IOIOProtocol.java
// enum SequencerEvent {
// PAUSED, STALLED, OPENED, NEXT_CUE, STOPPED, CLOSED
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/Log.java
// public class Log {
// public static int println(int priority, String tag, String msg) {
// return android.util.Log.println(priority, tag, msg);
// }
//
// public static void e(String tag, String message) {
// android.util.Log.e(tag, message);
// }
//
// public static void e(String tag, String message, Throwable tr) {
// android.util.Log.e(tag, message, tr);
// }
//
// public static void w(String tag, String message) {
// android.util.Log.w(tag, message);
// }
//
// public static void w(String tag, String message, Throwable tr) {
// android.util.Log.w(tag, message);
// }
//
// public static void i(String tag, String message) {
// android.util.Log.i(tag, message);
// }
//
// public static void d(String tag, String message) {
// android.util.Log.d(tag, message);
// }
//
// public static void v(String tag, String message) {
// android.util.Log.v(tag, message);
// }
// }
| import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.impl.Board.Hardware;
import ioio.lib.impl.IOIOProtocol.IncomingHandler;
import ioio.lib.impl.IOIOProtocol.SequencerEvent;
import ioio.lib.spi.Log;
import java.util.HashSet;
import java.util.List; | public void handleI2cOpen(int i2cNum) {
// logMethod("handleI2cOpen", i2cNum);
twiStates_[i2cNum].openNextListener();
}
@Override
public void handleI2cClose(int i2cNum) {
// logMethod("handleI2cClose", i2cNum);
twiStates_[i2cNum].closeCurrentListener();
}
@Override
public void handleIcspOpen() {
// logMethod("handleIcspOpen");
icspState_.openNextListener();
}
@Override
public void handleIcspClose() {
// logMethod("handleIcspClose");
icspState_.closeCurrentListener();
}
@Override
public void handleEstablishConnection(byte[] hardwareId,
byte[] bootloaderId, byte[] firmwareId) {
hardwareId_ = new String(hardwareId);
bootloaderId_ = new String(bootloaderId);
firmwareId_ = new String(firmwareId);
| // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/IOIOProtocol.java
// public interface IncomingHandler {
// public void handleEstablishConnection(byte[] hardwareId, byte[] bootloaderId,
// byte[] firmwareId);
//
// public void handleConnectionLost();
//
// public void handleSoftReset();
//
// public void handleCheckInterfaceResponse(boolean supported);
//
// public void handleSetChangeNotify(int pin, boolean changeNotify);
//
// public void handleReportDigitalInStatus(int pin, boolean level);
//
// public void handleRegisterPeriodicDigitalSampling(int pin, int freqScale);
//
// public void handleReportPeriodicDigitalInStatus(int frameNum, boolean values[]);
//
// public void handleAnalogPinStatus(int pin, boolean open);
//
// public void handleReportAnalogInStatus(List<Integer> pins, List<Integer> values);
//
// public void handleUartOpen(int uartNum);
//
// public void handleUartClose(int uartNum);
//
// public void handleUartData(int uartNum, int numBytes, byte data[]);
//
// public void handleUartReportTxStatus(int uartNum, int bytesRemaining);
//
// public void handleSpiOpen(int spiNum);
//
// public void handleSpiClose(int spiNum);
//
// public void handleSpiData(int spiNum, int ssPin, byte data[], int dataBytes);
//
// public void handleSpiReportTxStatus(int spiNum, int bytesRemaining);
//
// public void handleI2cOpen(int i2cNum);
//
// public void handleI2cClose(int i2cNum);
//
// public void handleI2cResult(int i2cNum, int size, byte[] data);
//
// public void handleI2cReportTxStatus(int spiNum, int bytesRemaining);
//
// void handleIcspOpen();
//
// void handleIcspClose();
//
// void handleIcspReportRxStatus(int bytesRemaining);
//
// void handleIcspResult(int size, byte[] data);
//
// public void handleIncapReport(int incapNum, int size, byte[] data);
//
// public void handleIncapClose(int incapNum);
//
// public void handleIncapOpen(int incapNum);
//
// public void handleCapSenseReport(int pinNum, int value);
//
// public void handleSetCapSenseSampling(int pinNum, boolean enable);
//
// public void handleSequencerEvent(SequencerEvent event, int arg);
//
// public void handleSync();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/IOIOProtocol.java
// enum SequencerEvent {
// PAUSED, STALLED, OPENED, NEXT_CUE, STOPPED, CLOSED
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/Log.java
// public class Log {
// public static int println(int priority, String tag, String msg) {
// return android.util.Log.println(priority, tag, msg);
// }
//
// public static void e(String tag, String message) {
// android.util.Log.e(tag, message);
// }
//
// public static void e(String tag, String message, Throwable tr) {
// android.util.Log.e(tag, message, tr);
// }
//
// public static void w(String tag, String message) {
// android.util.Log.w(tag, message);
// }
//
// public static void w(String tag, String message, Throwable tr) {
// android.util.Log.w(tag, message);
// }
//
// public static void i(String tag, String message) {
// android.util.Log.i(tag, message);
// }
//
// public static void d(String tag, String message) {
// android.util.Log.d(tag, message);
// }
//
// public static void v(String tag, String message) {
// android.util.Log.v(tag, message);
// }
// }
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/IncomingState.java
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.impl.Board.Hardware;
import ioio.lib.impl.IOIOProtocol.IncomingHandler;
import ioio.lib.impl.IOIOProtocol.SequencerEvent;
import ioio.lib.spi.Log;
import java.util.HashSet;
import java.util.List;
public void handleI2cOpen(int i2cNum) {
// logMethod("handleI2cOpen", i2cNum);
twiStates_[i2cNum].openNextListener();
}
@Override
public void handleI2cClose(int i2cNum) {
// logMethod("handleI2cClose", i2cNum);
twiStates_[i2cNum].closeCurrentListener();
}
@Override
public void handleIcspOpen() {
// logMethod("handleIcspOpen");
icspState_.openNextListener();
}
@Override
public void handleIcspClose() {
// logMethod("handleIcspClose");
icspState_.closeCurrentListener();
}
@Override
public void handleEstablishConnection(byte[] hardwareId,
byte[] bootloaderId, byte[] firmwareId) {
hardwareId_ = new String(hardwareId);
bootloaderId_ = new String(bootloaderId);
firmwareId_ = new String(firmwareId);
| Log.i(TAG, "IOIO Connection established. Hardware ID: " + hardwareId_ |
flyver/Flyver-SDK | IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/IncomingState.java | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/IOIOProtocol.java
// public interface IncomingHandler {
// public void handleEstablishConnection(byte[] hardwareId, byte[] bootloaderId,
// byte[] firmwareId);
//
// public void handleConnectionLost();
//
// public void handleSoftReset();
//
// public void handleCheckInterfaceResponse(boolean supported);
//
// public void handleSetChangeNotify(int pin, boolean changeNotify);
//
// public void handleReportDigitalInStatus(int pin, boolean level);
//
// public void handleRegisterPeriodicDigitalSampling(int pin, int freqScale);
//
// public void handleReportPeriodicDigitalInStatus(int frameNum, boolean values[]);
//
// public void handleAnalogPinStatus(int pin, boolean open);
//
// public void handleReportAnalogInStatus(List<Integer> pins, List<Integer> values);
//
// public void handleUartOpen(int uartNum);
//
// public void handleUartClose(int uartNum);
//
// public void handleUartData(int uartNum, int numBytes, byte data[]);
//
// public void handleUartReportTxStatus(int uartNum, int bytesRemaining);
//
// public void handleSpiOpen(int spiNum);
//
// public void handleSpiClose(int spiNum);
//
// public void handleSpiData(int spiNum, int ssPin, byte data[], int dataBytes);
//
// public void handleSpiReportTxStatus(int spiNum, int bytesRemaining);
//
// public void handleI2cOpen(int i2cNum);
//
// public void handleI2cClose(int i2cNum);
//
// public void handleI2cResult(int i2cNum, int size, byte[] data);
//
// public void handleI2cReportTxStatus(int spiNum, int bytesRemaining);
//
// void handleIcspOpen();
//
// void handleIcspClose();
//
// void handleIcspReportRxStatus(int bytesRemaining);
//
// void handleIcspResult(int size, byte[] data);
//
// public void handleIncapReport(int incapNum, int size, byte[] data);
//
// public void handleIncapClose(int incapNum);
//
// public void handleIncapOpen(int incapNum);
//
// public void handleCapSenseReport(int pinNum, int value);
//
// public void handleSetCapSenseSampling(int pinNum, boolean enable);
//
// public void handleSequencerEvent(SequencerEvent event, int arg);
//
// public void handleSync();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/IOIOProtocol.java
// enum SequencerEvent {
// PAUSED, STALLED, OPENED, NEXT_CUE, STOPPED, CLOSED
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/Log.java
// public class Log {
// public static int println(int priority, String tag, String msg) {
// return android.util.Log.println(priority, tag, msg);
// }
//
// public static void e(String tag, String message) {
// android.util.Log.e(tag, message);
// }
//
// public static void e(String tag, String message, Throwable tr) {
// android.util.Log.e(tag, message, tr);
// }
//
// public static void w(String tag, String message) {
// android.util.Log.w(tag, message);
// }
//
// public static void w(String tag, String message, Throwable tr) {
// android.util.Log.w(tag, message);
// }
//
// public static void i(String tag, String message) {
// android.util.Log.i(tag, message);
// }
//
// public static void d(String tag, String message) {
// android.util.Log.d(tag, message);
// }
//
// public static void v(String tag, String message) {
// android.util.Log.v(tag, message);
// }
// }
| import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.impl.Board.Hardware;
import ioio.lib.impl.IOIOProtocol.IncomingHandler;
import ioio.lib.impl.IOIOProtocol.SequencerEvent;
import ioio.lib.spi.Log;
import java.util.HashSet;
import java.util.List; |
@Override
public void handleIncapOpen(int incapNum) {
// logMethod("handleIncapOpen", incapNum);
incapStates_[incapNum].openNextListener();
}
@Override
public void handleIcspResult(int size, byte[] data) {
// logMethod("handleIcspResult", size, data);
icspState_.dataReceived(data, size);
}
@Override
public void handleCapSenseReport(int pinNum, int value) {
// logMethod("handleCapSenseReport", pinNum, value);
intputPinStates_[pinNum].setValue(value);
}
@Override
public void handleSetCapSenseSampling(int pinNum, boolean enable) {
// logMethod("handleSetCapSenseSampling", pinNum, enable);
if (enable) {
intputPinStates_[pinNum].openNextListener();
} else {
intputPinStates_[pinNum].closeCurrentListener();
}
}
@Override | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/IOIOProtocol.java
// public interface IncomingHandler {
// public void handleEstablishConnection(byte[] hardwareId, byte[] bootloaderId,
// byte[] firmwareId);
//
// public void handleConnectionLost();
//
// public void handleSoftReset();
//
// public void handleCheckInterfaceResponse(boolean supported);
//
// public void handleSetChangeNotify(int pin, boolean changeNotify);
//
// public void handleReportDigitalInStatus(int pin, boolean level);
//
// public void handleRegisterPeriodicDigitalSampling(int pin, int freqScale);
//
// public void handleReportPeriodicDigitalInStatus(int frameNum, boolean values[]);
//
// public void handleAnalogPinStatus(int pin, boolean open);
//
// public void handleReportAnalogInStatus(List<Integer> pins, List<Integer> values);
//
// public void handleUartOpen(int uartNum);
//
// public void handleUartClose(int uartNum);
//
// public void handleUartData(int uartNum, int numBytes, byte data[]);
//
// public void handleUartReportTxStatus(int uartNum, int bytesRemaining);
//
// public void handleSpiOpen(int spiNum);
//
// public void handleSpiClose(int spiNum);
//
// public void handleSpiData(int spiNum, int ssPin, byte data[], int dataBytes);
//
// public void handleSpiReportTxStatus(int spiNum, int bytesRemaining);
//
// public void handleI2cOpen(int i2cNum);
//
// public void handleI2cClose(int i2cNum);
//
// public void handleI2cResult(int i2cNum, int size, byte[] data);
//
// public void handleI2cReportTxStatus(int spiNum, int bytesRemaining);
//
// void handleIcspOpen();
//
// void handleIcspClose();
//
// void handleIcspReportRxStatus(int bytesRemaining);
//
// void handleIcspResult(int size, byte[] data);
//
// public void handleIncapReport(int incapNum, int size, byte[] data);
//
// public void handleIncapClose(int incapNum);
//
// public void handleIncapOpen(int incapNum);
//
// public void handleCapSenseReport(int pinNum, int value);
//
// public void handleSetCapSenseSampling(int pinNum, boolean enable);
//
// public void handleSequencerEvent(SequencerEvent event, int arg);
//
// public void handleSync();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/IOIOProtocol.java
// enum SequencerEvent {
// PAUSED, STALLED, OPENED, NEXT_CUE, STOPPED, CLOSED
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/Log.java
// public class Log {
// public static int println(int priority, String tag, String msg) {
// return android.util.Log.println(priority, tag, msg);
// }
//
// public static void e(String tag, String message) {
// android.util.Log.e(tag, message);
// }
//
// public static void e(String tag, String message, Throwable tr) {
// android.util.Log.e(tag, message, tr);
// }
//
// public static void w(String tag, String message) {
// android.util.Log.w(tag, message);
// }
//
// public static void w(String tag, String message, Throwable tr) {
// android.util.Log.w(tag, message);
// }
//
// public static void i(String tag, String message) {
// android.util.Log.i(tag, message);
// }
//
// public static void d(String tag, String message) {
// android.util.Log.d(tag, message);
// }
//
// public static void v(String tag, String message) {
// android.util.Log.v(tag, message);
// }
// }
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/IncomingState.java
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.impl.Board.Hardware;
import ioio.lib.impl.IOIOProtocol.IncomingHandler;
import ioio.lib.impl.IOIOProtocol.SequencerEvent;
import ioio.lib.spi.Log;
import java.util.HashSet;
import java.util.List;
@Override
public void handleIncapOpen(int incapNum) {
// logMethod("handleIncapOpen", incapNum);
incapStates_[incapNum].openNextListener();
}
@Override
public void handleIcspResult(int size, byte[] data) {
// logMethod("handleIcspResult", size, data);
icspState_.dataReceived(data, size);
}
@Override
public void handleCapSenseReport(int pinNum, int value) {
// logMethod("handleCapSenseReport", pinNum, value);
intputPinStates_[pinNum].setValue(value);
}
@Override
public void handleSetCapSenseSampling(int pinNum, boolean enable) {
// logMethod("handleSetCapSenseSampling", pinNum, enable);
if (enable) {
intputPinStates_[pinNum].openNextListener();
} else {
intputPinStates_[pinNum].closeCurrentListener();
}
}
@Override | public void handleSequencerEvent(SequencerEvent event, int arg) { |
flyver/Flyver-SDK | IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/SocketIOIOConnectionBootstrap.java | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIOConnection.java
// public interface IOIOConnection {
// void waitForConnect() throws ConnectionLostException;
//
// void disconnect();
//
// InputStream getInputStream() throws ConnectionLostException;
//
// OutputStream getOutputStream() throws ConnectionLostException;
//
// /**
// * Can this connection be closed. Normally the answer would be "true", but
// * some weird connections cannot be closed and need the higher layer to do
// * a "soft close" instead.
// *
// * @return true This connection can be closed.
// */
// boolean canClose();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionBootstrap.java
// public interface IOIOConnectionBootstrap {
// public void getFactories(Collection<IOIOConnectionFactory> result);
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionFactory.java
// public interface IOIOConnectionFactory {
// /**
// * A unique name of the connection type. Typically a fully-qualified
// * name of the connection class.
// */
// public String getType();
//
// /**
// * Extra information on the connection. This is specific to the
// * connection type. For example, for a Bluetooth connection, this is an
// * array containing the name and the Bluetooth address of the remote
// * IOIO.
// */
// public Object getExtra();
//
// public IOIOConnection createConnection();
// }
| import ioio.lib.api.IOIOConnection;
import ioio.lib.spi.IOIOConnectionBootstrap;
import ioio.lib.spi.IOIOConnectionFactory;
import java.util.Collection; | /*
* Copyright 2011 Ytai Ben-Tsvi. All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARSHAN POURSOHI OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied.
*/
package ioio.lib.impl;
public class SocketIOIOConnectionBootstrap implements IOIOConnectionBootstrap {
/**
* The TCP port used for communicating with the IOIO board.
*/
public static final int IOIO_PORT = 4545;
@Override | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIOConnection.java
// public interface IOIOConnection {
// void waitForConnect() throws ConnectionLostException;
//
// void disconnect();
//
// InputStream getInputStream() throws ConnectionLostException;
//
// OutputStream getOutputStream() throws ConnectionLostException;
//
// /**
// * Can this connection be closed. Normally the answer would be "true", but
// * some weird connections cannot be closed and need the higher layer to do
// * a "soft close" instead.
// *
// * @return true This connection can be closed.
// */
// boolean canClose();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionBootstrap.java
// public interface IOIOConnectionBootstrap {
// public void getFactories(Collection<IOIOConnectionFactory> result);
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionFactory.java
// public interface IOIOConnectionFactory {
// /**
// * A unique name of the connection type. Typically a fully-qualified
// * name of the connection class.
// */
// public String getType();
//
// /**
// * Extra information on the connection. This is specific to the
// * connection type. For example, for a Bluetooth connection, this is an
// * array containing the name and the Bluetooth address of the remote
// * IOIO.
// */
// public Object getExtra();
//
// public IOIOConnection createConnection();
// }
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/SocketIOIOConnectionBootstrap.java
import ioio.lib.api.IOIOConnection;
import ioio.lib.spi.IOIOConnectionBootstrap;
import ioio.lib.spi.IOIOConnectionFactory;
import java.util.Collection;
/*
* Copyright 2011 Ytai Ben-Tsvi. All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARSHAN POURSOHI OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied.
*/
package ioio.lib.impl;
public class SocketIOIOConnectionBootstrap implements IOIOConnectionBootstrap {
/**
* The TCP port used for communicating with the IOIO board.
*/
public static final int IOIO_PORT = 4545;
@Override | public void getFactories(Collection<IOIOConnectionFactory> result) { |
flyver/Flyver-SDK | IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/SocketIOIOConnectionBootstrap.java | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIOConnection.java
// public interface IOIOConnection {
// void waitForConnect() throws ConnectionLostException;
//
// void disconnect();
//
// InputStream getInputStream() throws ConnectionLostException;
//
// OutputStream getOutputStream() throws ConnectionLostException;
//
// /**
// * Can this connection be closed. Normally the answer would be "true", but
// * some weird connections cannot be closed and need the higher layer to do
// * a "soft close" instead.
// *
// * @return true This connection can be closed.
// */
// boolean canClose();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionBootstrap.java
// public interface IOIOConnectionBootstrap {
// public void getFactories(Collection<IOIOConnectionFactory> result);
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionFactory.java
// public interface IOIOConnectionFactory {
// /**
// * A unique name of the connection type. Typically a fully-qualified
// * name of the connection class.
// */
// public String getType();
//
// /**
// * Extra information on the connection. This is specific to the
// * connection type. For example, for a Bluetooth connection, this is an
// * array containing the name and the Bluetooth address of the remote
// * IOIO.
// */
// public Object getExtra();
//
// public IOIOConnection createConnection();
// }
| import ioio.lib.api.IOIOConnection;
import ioio.lib.spi.IOIOConnectionBootstrap;
import ioio.lib.spi.IOIOConnectionFactory;
import java.util.Collection; | /*
* Copyright 2011 Ytai Ben-Tsvi. All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARSHAN POURSOHI OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied.
*/
package ioio.lib.impl;
public class SocketIOIOConnectionBootstrap implements IOIOConnectionBootstrap {
/**
* The TCP port used for communicating with the IOIO board.
*/
public static final int IOIO_PORT = 4545;
@Override
public void getFactories(Collection<IOIOConnectionFactory> result) {
result.add(new IOIOConnectionFactory() {
private Integer port_ = Integer.valueOf(IOIO_PORT);
@Override
public String getType() {
return SocketIOIOConnection.class.getCanonicalName();
}
@Override
public Object getExtra() {
return port_;
}
@Override | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIOConnection.java
// public interface IOIOConnection {
// void waitForConnect() throws ConnectionLostException;
//
// void disconnect();
//
// InputStream getInputStream() throws ConnectionLostException;
//
// OutputStream getOutputStream() throws ConnectionLostException;
//
// /**
// * Can this connection be closed. Normally the answer would be "true", but
// * some weird connections cannot be closed and need the higher layer to do
// * a "soft close" instead.
// *
// * @return true This connection can be closed.
// */
// boolean canClose();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionBootstrap.java
// public interface IOIOConnectionBootstrap {
// public void getFactories(Collection<IOIOConnectionFactory> result);
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionFactory.java
// public interface IOIOConnectionFactory {
// /**
// * A unique name of the connection type. Typically a fully-qualified
// * name of the connection class.
// */
// public String getType();
//
// /**
// * Extra information on the connection. This is specific to the
// * connection type. For example, for a Bluetooth connection, this is an
// * array containing the name and the Bluetooth address of the remote
// * IOIO.
// */
// public Object getExtra();
//
// public IOIOConnection createConnection();
// }
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/SocketIOIOConnectionBootstrap.java
import ioio.lib.api.IOIOConnection;
import ioio.lib.spi.IOIOConnectionBootstrap;
import ioio.lib.spi.IOIOConnectionFactory;
import java.util.Collection;
/*
* Copyright 2011 Ytai Ben-Tsvi. All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARSHAN POURSOHI OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied.
*/
package ioio.lib.impl;
public class SocketIOIOConnectionBootstrap implements IOIOConnectionBootstrap {
/**
* The TCP port used for communicating with the IOIO board.
*/
public static final int IOIO_PORT = 4545;
@Override
public void getFactories(Collection<IOIOConnectionFactory> result) {
result.add(new IOIOConnectionFactory() {
private Integer port_ = Integer.valueOf(IOIO_PORT);
@Override
public String getType() {
return SocketIOIOConnection.class.getCanonicalName();
}
@Override
public Object getExtra() {
return port_;
}
@Override | public IOIOConnection createConnection() { |
flyver/Flyver-SDK | IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIO.java | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/PulseInput.java
// public enum PulseMode {
// /**
// * Positive pulse measurement (rising-edge-to-falling-edge).
// */
// POSITIVE(1),
// /**
// * Negative pulse measurement (falling-edge-to-rising-edge).
// */
// NEGATIVE(1),
// /**
// * Frequency measurement (rising-edge-to-rising-edge).
// */
// FREQ(1),
// /**
// * Frequency measurement (rising-edge-to-rising-edge) with 4x scaling.
// */
// FREQ_SCALE_4(4),
// /**
// * Frequency measurement (rising-edge-to-rising-edge) with 16x scaling.
// */
// FREQ_SCALE_16(16);
//
// /**
// * The scaling factor as an integer.
// */
// public final int scaling;
//
// private PulseMode(int s) {
// scaling = s;
// }
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/TwiMaster.java
// enum Rate {
// RATE_100KHz, RATE_400KHz, RATE_1MHz
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/Uart.java
// enum Parity {
// /**
// * No parity.
// */
// NONE,
// /**
// * Even parity.
// */
// EVEN,
// /**
// * Odd parity.
// */
// ODD
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/Uart.java
// enum StopBits {
// /**
// * One stop bit.
// */
// ONE,
// /**
// * Two stop bits.
// */
// TWO
// }
| import ioio.lib.api.PulseInput.PulseMode;
import ioio.lib.api.TwiMaster.Rate;
import ioio.lib.api.Uart.Parity;
import ioio.lib.api.Uart.StopBits;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.api.exception.IncompatibilityException;
import ioio.lib.api.exception.OutOfResourceException;
import java.io.Closeable; | * periodic signal.
* <p/>
* Note that not every pin can be used as pulse input. In addition, the total number of
* concurrent pulse input modules in use is limited. See board documentation for the legal pins
* and limit on concurrent usage.
* <p/>
* The pin will operate in this mode until close() is invoked on the returned interface. It is
* illegal to open a pin that has already been opened and has not been closed. A connection must
* have been established prior to calling this method, by invoking {@link #waitForConnect()}.
*
* @param spec Pin specification, consisting of the pin number, as labeled on the board, and the
* mode, which determines whether the pin will be floating, pull-up or pull-down. See
* {@link DigitalInput.Spec.Mode} for more information.
* @param rate The clock rate to use for timing the signal. A faster clock rate will result in
* better precision but will only be able to measure narrow pulses / high
* frequencies.
* @param mode The mode in which to operate. Determines whether the module will measure pulse
* durations or frequency.
* @param doublePrecision Whether to open a double-precision pulse input module. Double- precision modules
* enable reading of much longer pulses and lower frequencies with high accuracy than
* single precision modules. However, their number is limited, so when possible, and
* if the resources are all needed, use single-precision. For more details on the
* exact spec of single- vs. double- precision, see {@link PulseInput}.
* @return An instance of the {@link PulseInput}, which can be used to obtain the data.
* @throws ConnectionLostException Connection was lost before or during the execution of this method.
* @throws OutOfResourceException This is a runtime exception, so it is not necessary to catch it if the client
* guarantees that the total number of concurrent PWM resources is not exceeded.
* @see PulseInput
*/
public PulseInput openPulseInput(DigitalInput.Spec spec, PulseInput.ClockRate rate, | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/PulseInput.java
// public enum PulseMode {
// /**
// * Positive pulse measurement (rising-edge-to-falling-edge).
// */
// POSITIVE(1),
// /**
// * Negative pulse measurement (falling-edge-to-rising-edge).
// */
// NEGATIVE(1),
// /**
// * Frequency measurement (rising-edge-to-rising-edge).
// */
// FREQ(1),
// /**
// * Frequency measurement (rising-edge-to-rising-edge) with 4x scaling.
// */
// FREQ_SCALE_4(4),
// /**
// * Frequency measurement (rising-edge-to-rising-edge) with 16x scaling.
// */
// FREQ_SCALE_16(16);
//
// /**
// * The scaling factor as an integer.
// */
// public final int scaling;
//
// private PulseMode(int s) {
// scaling = s;
// }
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/TwiMaster.java
// enum Rate {
// RATE_100KHz, RATE_400KHz, RATE_1MHz
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/Uart.java
// enum Parity {
// /**
// * No parity.
// */
// NONE,
// /**
// * Even parity.
// */
// EVEN,
// /**
// * Odd parity.
// */
// ODD
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/Uart.java
// enum StopBits {
// /**
// * One stop bit.
// */
// ONE,
// /**
// * Two stop bits.
// */
// TWO
// }
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIO.java
import ioio.lib.api.PulseInput.PulseMode;
import ioio.lib.api.TwiMaster.Rate;
import ioio.lib.api.Uart.Parity;
import ioio.lib.api.Uart.StopBits;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.api.exception.IncompatibilityException;
import ioio.lib.api.exception.OutOfResourceException;
import java.io.Closeable;
* periodic signal.
* <p/>
* Note that not every pin can be used as pulse input. In addition, the total number of
* concurrent pulse input modules in use is limited. See board documentation for the legal pins
* and limit on concurrent usage.
* <p/>
* The pin will operate in this mode until close() is invoked on the returned interface. It is
* illegal to open a pin that has already been opened and has not been closed. A connection must
* have been established prior to calling this method, by invoking {@link #waitForConnect()}.
*
* @param spec Pin specification, consisting of the pin number, as labeled on the board, and the
* mode, which determines whether the pin will be floating, pull-up or pull-down. See
* {@link DigitalInput.Spec.Mode} for more information.
* @param rate The clock rate to use for timing the signal. A faster clock rate will result in
* better precision but will only be able to measure narrow pulses / high
* frequencies.
* @param mode The mode in which to operate. Determines whether the module will measure pulse
* durations or frequency.
* @param doublePrecision Whether to open a double-precision pulse input module. Double- precision modules
* enable reading of much longer pulses and lower frequencies with high accuracy than
* single precision modules. However, their number is limited, so when possible, and
* if the resources are all needed, use single-precision. For more details on the
* exact spec of single- vs. double- precision, see {@link PulseInput}.
* @return An instance of the {@link PulseInput}, which can be used to obtain the data.
* @throws ConnectionLostException Connection was lost before or during the execution of this method.
* @throws OutOfResourceException This is a runtime exception, so it is not necessary to catch it if the client
* guarantees that the total number of concurrent PWM resources is not exceeded.
* @see PulseInput
*/
public PulseInput openPulseInput(DigitalInput.Spec spec, PulseInput.ClockRate rate, | PulseInput.PulseMode mode, boolean doublePrecision) throws ConnectionLostException; |
flyver/Flyver-SDK | IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIO.java | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/PulseInput.java
// public enum PulseMode {
// /**
// * Positive pulse measurement (rising-edge-to-falling-edge).
// */
// POSITIVE(1),
// /**
// * Negative pulse measurement (falling-edge-to-rising-edge).
// */
// NEGATIVE(1),
// /**
// * Frequency measurement (rising-edge-to-rising-edge).
// */
// FREQ(1),
// /**
// * Frequency measurement (rising-edge-to-rising-edge) with 4x scaling.
// */
// FREQ_SCALE_4(4),
// /**
// * Frequency measurement (rising-edge-to-rising-edge) with 16x scaling.
// */
// FREQ_SCALE_16(16);
//
// /**
// * The scaling factor as an integer.
// */
// public final int scaling;
//
// private PulseMode(int s) {
// scaling = s;
// }
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/TwiMaster.java
// enum Rate {
// RATE_100KHz, RATE_400KHz, RATE_1MHz
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/Uart.java
// enum Parity {
// /**
// * No parity.
// */
// NONE,
// /**
// * Even parity.
// */
// EVEN,
// /**
// * Odd parity.
// */
// ODD
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/Uart.java
// enum StopBits {
// /**
// * One stop bit.
// */
// ONE,
// /**
// * Two stop bits.
// */
// TWO
// }
| import ioio.lib.api.PulseInput.PulseMode;
import ioio.lib.api.TwiMaster.Rate;
import ioio.lib.api.Uart.Parity;
import ioio.lib.api.Uart.StopBits;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.api.exception.IncompatibilityException;
import ioio.lib.api.exception.OutOfResourceException;
import java.io.Closeable; | * UART is a very common hardware communication protocol, enabling full- duplex, asynchronous
* point-to-point data transfer. It typically serves for opening consoles or as a basis for
* higher-level protocols, such as MIDI RS-232, and RS-485.
* <p/>
* Note that not every pin can be used for UART RX or TX. In addition, the total number of
* concurrent UART modules in use is limited. See board documentation for the legal pins and
* limit on concurrent usage.
* <p/>
* The UART module will operate, and the pins will work in their respective modes until close()
* is invoked on the returned interface. It is illegal to use pins that have already been opened
* and has not been closed. A connection must have been established prior to calling this
* method, by invoking {@link #waitForConnect()}.
*
* @param rx Pin specification for the RX pin, consisting of the pin number, as labeled on the
* board, and the mode, which determines whether the pin will be floating, pull-up or
* pull-down. See {@link DigitalInput.Spec.Mode} for more information. null can be
* passed to designate that we do not want RX input to this module.
* @param tx Pin specification for the TX pin, consisting of the pin number, as labeled on the
* board, and the mode, which determines whether the pin will be normal or
* open-drain. See {@link DigitalOutput.Spec.Mode} for more information. null can be
* passed to designate that we do not want TX output to this module.
* @param baud The clock frequency of the UART module in Hz.
* @param parity The parity mode, as in {@link Parity}.
* @param stopbits Number of stop bits, as in {@link StopBits}.
* @return Interface of the assigned module.
* @throws ConnectionLostException Connection was lost before or during the execution of this method.
* @throws OutOfResourceException This is a runtime exception, so it is not necessary to catch it if the client
* guarantees that the total number of concurrent UART resources is not exceeded.
* @see Uart
*/ | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/PulseInput.java
// public enum PulseMode {
// /**
// * Positive pulse measurement (rising-edge-to-falling-edge).
// */
// POSITIVE(1),
// /**
// * Negative pulse measurement (falling-edge-to-rising-edge).
// */
// NEGATIVE(1),
// /**
// * Frequency measurement (rising-edge-to-rising-edge).
// */
// FREQ(1),
// /**
// * Frequency measurement (rising-edge-to-rising-edge) with 4x scaling.
// */
// FREQ_SCALE_4(4),
// /**
// * Frequency measurement (rising-edge-to-rising-edge) with 16x scaling.
// */
// FREQ_SCALE_16(16);
//
// /**
// * The scaling factor as an integer.
// */
// public final int scaling;
//
// private PulseMode(int s) {
// scaling = s;
// }
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/TwiMaster.java
// enum Rate {
// RATE_100KHz, RATE_400KHz, RATE_1MHz
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/Uart.java
// enum Parity {
// /**
// * No parity.
// */
// NONE,
// /**
// * Even parity.
// */
// EVEN,
// /**
// * Odd parity.
// */
// ODD
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/Uart.java
// enum StopBits {
// /**
// * One stop bit.
// */
// ONE,
// /**
// * Two stop bits.
// */
// TWO
// }
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIO.java
import ioio.lib.api.PulseInput.PulseMode;
import ioio.lib.api.TwiMaster.Rate;
import ioio.lib.api.Uart.Parity;
import ioio.lib.api.Uart.StopBits;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.api.exception.IncompatibilityException;
import ioio.lib.api.exception.OutOfResourceException;
import java.io.Closeable;
* UART is a very common hardware communication protocol, enabling full- duplex, asynchronous
* point-to-point data transfer. It typically serves for opening consoles or as a basis for
* higher-level protocols, such as MIDI RS-232, and RS-485.
* <p/>
* Note that not every pin can be used for UART RX or TX. In addition, the total number of
* concurrent UART modules in use is limited. See board documentation for the legal pins and
* limit on concurrent usage.
* <p/>
* The UART module will operate, and the pins will work in their respective modes until close()
* is invoked on the returned interface. It is illegal to use pins that have already been opened
* and has not been closed. A connection must have been established prior to calling this
* method, by invoking {@link #waitForConnect()}.
*
* @param rx Pin specification for the RX pin, consisting of the pin number, as labeled on the
* board, and the mode, which determines whether the pin will be floating, pull-up or
* pull-down. See {@link DigitalInput.Spec.Mode} for more information. null can be
* passed to designate that we do not want RX input to this module.
* @param tx Pin specification for the TX pin, consisting of the pin number, as labeled on the
* board, and the mode, which determines whether the pin will be normal or
* open-drain. See {@link DigitalOutput.Spec.Mode} for more information. null can be
* passed to designate that we do not want TX output to this module.
* @param baud The clock frequency of the UART module in Hz.
* @param parity The parity mode, as in {@link Parity}.
* @param stopbits Number of stop bits, as in {@link StopBits}.
* @return Interface of the assigned module.
* @throws ConnectionLostException Connection was lost before or during the execution of this method.
* @throws OutOfResourceException This is a runtime exception, so it is not necessary to catch it if the client
* guarantees that the total number of concurrent UART resources is not exceeded.
* @see Uart
*/ | public Uart openUart(DigitalInput.Spec rx, DigitalOutput.Spec tx, int baud, Parity parity, |
flyver/Flyver-SDK | IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIO.java | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/PulseInput.java
// public enum PulseMode {
// /**
// * Positive pulse measurement (rising-edge-to-falling-edge).
// */
// POSITIVE(1),
// /**
// * Negative pulse measurement (falling-edge-to-rising-edge).
// */
// NEGATIVE(1),
// /**
// * Frequency measurement (rising-edge-to-rising-edge).
// */
// FREQ(1),
// /**
// * Frequency measurement (rising-edge-to-rising-edge) with 4x scaling.
// */
// FREQ_SCALE_4(4),
// /**
// * Frequency measurement (rising-edge-to-rising-edge) with 16x scaling.
// */
// FREQ_SCALE_16(16);
//
// /**
// * The scaling factor as an integer.
// */
// public final int scaling;
//
// private PulseMode(int s) {
// scaling = s;
// }
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/TwiMaster.java
// enum Rate {
// RATE_100KHz, RATE_400KHz, RATE_1MHz
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/Uart.java
// enum Parity {
// /**
// * No parity.
// */
// NONE,
// /**
// * Even parity.
// */
// EVEN,
// /**
// * Odd parity.
// */
// ODD
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/Uart.java
// enum StopBits {
// /**
// * One stop bit.
// */
// ONE,
// /**
// * Two stop bits.
// */
// TWO
// }
| import ioio.lib.api.PulseInput.PulseMode;
import ioio.lib.api.TwiMaster.Rate;
import ioio.lib.api.Uart.Parity;
import ioio.lib.api.Uart.StopBits;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.api.exception.IncompatibilityException;
import ioio.lib.api.exception.OutOfResourceException;
import java.io.Closeable; | * point-to-point data transfer. It typically serves for opening consoles or as a basis for
* higher-level protocols, such as MIDI RS-232, and RS-485.
* <p/>
* Note that not every pin can be used for UART RX or TX. In addition, the total number of
* concurrent UART modules in use is limited. See board documentation for the legal pins and
* limit on concurrent usage.
* <p/>
* The UART module will operate, and the pins will work in their respective modes until close()
* is invoked on the returned interface. It is illegal to use pins that have already been opened
* and has not been closed. A connection must have been established prior to calling this
* method, by invoking {@link #waitForConnect()}.
*
* @param rx Pin specification for the RX pin, consisting of the pin number, as labeled on the
* board, and the mode, which determines whether the pin will be floating, pull-up or
* pull-down. See {@link DigitalInput.Spec.Mode} for more information. null can be
* passed to designate that we do not want RX input to this module.
* @param tx Pin specification for the TX pin, consisting of the pin number, as labeled on the
* board, and the mode, which determines whether the pin will be normal or
* open-drain. See {@link DigitalOutput.Spec.Mode} for more information. null can be
* passed to designate that we do not want TX output to this module.
* @param baud The clock frequency of the UART module in Hz.
* @param parity The parity mode, as in {@link Parity}.
* @param stopbits Number of stop bits, as in {@link StopBits}.
* @return Interface of the assigned module.
* @throws ConnectionLostException Connection was lost before or during the execution of this method.
* @throws OutOfResourceException This is a runtime exception, so it is not necessary to catch it if the client
* guarantees that the total number of concurrent UART resources is not exceeded.
* @see Uart
*/
public Uart openUart(DigitalInput.Spec rx, DigitalOutput.Spec tx, int baud, Parity parity, | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/PulseInput.java
// public enum PulseMode {
// /**
// * Positive pulse measurement (rising-edge-to-falling-edge).
// */
// POSITIVE(1),
// /**
// * Negative pulse measurement (falling-edge-to-rising-edge).
// */
// NEGATIVE(1),
// /**
// * Frequency measurement (rising-edge-to-rising-edge).
// */
// FREQ(1),
// /**
// * Frequency measurement (rising-edge-to-rising-edge) with 4x scaling.
// */
// FREQ_SCALE_4(4),
// /**
// * Frequency measurement (rising-edge-to-rising-edge) with 16x scaling.
// */
// FREQ_SCALE_16(16);
//
// /**
// * The scaling factor as an integer.
// */
// public final int scaling;
//
// private PulseMode(int s) {
// scaling = s;
// }
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/TwiMaster.java
// enum Rate {
// RATE_100KHz, RATE_400KHz, RATE_1MHz
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/Uart.java
// enum Parity {
// /**
// * No parity.
// */
// NONE,
// /**
// * Even parity.
// */
// EVEN,
// /**
// * Odd parity.
// */
// ODD
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/Uart.java
// enum StopBits {
// /**
// * One stop bit.
// */
// ONE,
// /**
// * Two stop bits.
// */
// TWO
// }
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIO.java
import ioio.lib.api.PulseInput.PulseMode;
import ioio.lib.api.TwiMaster.Rate;
import ioio.lib.api.Uart.Parity;
import ioio.lib.api.Uart.StopBits;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.api.exception.IncompatibilityException;
import ioio.lib.api.exception.OutOfResourceException;
import java.io.Closeable;
* point-to-point data transfer. It typically serves for opening consoles or as a basis for
* higher-level protocols, such as MIDI RS-232, and RS-485.
* <p/>
* Note that not every pin can be used for UART RX or TX. In addition, the total number of
* concurrent UART modules in use is limited. See board documentation for the legal pins and
* limit on concurrent usage.
* <p/>
* The UART module will operate, and the pins will work in their respective modes until close()
* is invoked on the returned interface. It is illegal to use pins that have already been opened
* and has not been closed. A connection must have been established prior to calling this
* method, by invoking {@link #waitForConnect()}.
*
* @param rx Pin specification for the RX pin, consisting of the pin number, as labeled on the
* board, and the mode, which determines whether the pin will be floating, pull-up or
* pull-down. See {@link DigitalInput.Spec.Mode} for more information. null can be
* passed to designate that we do not want RX input to this module.
* @param tx Pin specification for the TX pin, consisting of the pin number, as labeled on the
* board, and the mode, which determines whether the pin will be normal or
* open-drain. See {@link DigitalOutput.Spec.Mode} for more information. null can be
* passed to designate that we do not want TX output to this module.
* @param baud The clock frequency of the UART module in Hz.
* @param parity The parity mode, as in {@link Parity}.
* @param stopbits Number of stop bits, as in {@link StopBits}.
* @return Interface of the assigned module.
* @throws ConnectionLostException Connection was lost before or during the execution of this method.
* @throws OutOfResourceException This is a runtime exception, so it is not necessary to catch it if the client
* guarantees that the total number of concurrent UART resources is not exceeded.
* @see Uart
*/
public Uart openUart(DigitalInput.Spec rx, DigitalOutput.Spec tx, int baud, Parity parity, | StopBits stopbits) throws ConnectionLostException; |
flyver/Flyver-SDK | IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIO.java | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/PulseInput.java
// public enum PulseMode {
// /**
// * Positive pulse measurement (rising-edge-to-falling-edge).
// */
// POSITIVE(1),
// /**
// * Negative pulse measurement (falling-edge-to-rising-edge).
// */
// NEGATIVE(1),
// /**
// * Frequency measurement (rising-edge-to-rising-edge).
// */
// FREQ(1),
// /**
// * Frequency measurement (rising-edge-to-rising-edge) with 4x scaling.
// */
// FREQ_SCALE_4(4),
// /**
// * Frequency measurement (rising-edge-to-rising-edge) with 16x scaling.
// */
// FREQ_SCALE_16(16);
//
// /**
// * The scaling factor as an integer.
// */
// public final int scaling;
//
// private PulseMode(int s) {
// scaling = s;
// }
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/TwiMaster.java
// enum Rate {
// RATE_100KHz, RATE_400KHz, RATE_1MHz
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/Uart.java
// enum Parity {
// /**
// * No parity.
// */
// NONE,
// /**
// * Even parity.
// */
// EVEN,
// /**
// * Odd parity.
// */
// ODD
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/Uart.java
// enum StopBits {
// /**
// * One stop bit.
// */
// ONE,
// /**
// * Two stop bits.
// */
// TWO
// }
| import ioio.lib.api.PulseInput.PulseMode;
import ioio.lib.api.TwiMaster.Rate;
import ioio.lib.api.Uart.Parity;
import ioio.lib.api.Uart.StopBits;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.api.exception.IncompatibilityException;
import ioio.lib.api.exception.OutOfResourceException;
import java.io.Closeable; | * @param clk Pin specification for the CLK pin, consisting of the pin number, as labeled on the
* board, and the mode, which determines whether the pin will be normal or
* open-drain. See {@link DigitalOutput.Spec.Mode} for more information.
* @param slaveSelect An array of pin specifications for each of the slaves' SS (Slave Select) pin. The
* index of this array designates the slave index, used later to refer to this slave.
* The spec is consisting of the pin number, as labeled on the board, and the mode,
* which determines whether the pin will be normal or open-drain. See
* {@link DigitalOutput.Spec.Mode} for more information.
* @param config The configuration of the SPI module. See {@link SpiMaster.Config} for details.
* @return Interface of the assigned module.
* @throws ConnectionLostException Connection was lost before or during the execution of this method.
* @throws OutOfResourceException This is a runtime exception, so it is not necessary to catch it if the client
* guarantees that the total number of concurrent SPI resources is not exceeded.
* @see SpiMaster
*/
public SpiMaster openSpiMaster(DigitalInput.Spec miso, DigitalOutput.Spec mosi,
DigitalOutput.Spec clk, DigitalOutput.Spec[] slaveSelect, SpiMaster.Config config)
throws ConnectionLostException;
/**
* Shorthand for
* {@link #openSpiMaster(ioio.lib.api.DigitalInput.Spec, ioio.lib.api.DigitalOutput.Spec, ioio.lib.api.DigitalOutput.Spec, ioio.lib.api.DigitalOutput.Spec[], ioio.lib.api.SpiMaster.Config)}
* , where the pins are all open with the default modes and default configuration values are
* used.
*
* @see #openSpiMaster(ioio.lib.api.DigitalInput.Spec, ioio.lib.api.DigitalOutput.Spec,
* ioio.lib.api.DigitalOutput.Spec, ioio.lib.api.DigitalOutput.Spec[],
* ioio.lib.api.SpiMaster.Config)
*/
public SpiMaster openSpiMaster(int miso, int mosi, int clk, int[] slaveSelect, | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/PulseInput.java
// public enum PulseMode {
// /**
// * Positive pulse measurement (rising-edge-to-falling-edge).
// */
// POSITIVE(1),
// /**
// * Negative pulse measurement (falling-edge-to-rising-edge).
// */
// NEGATIVE(1),
// /**
// * Frequency measurement (rising-edge-to-rising-edge).
// */
// FREQ(1),
// /**
// * Frequency measurement (rising-edge-to-rising-edge) with 4x scaling.
// */
// FREQ_SCALE_4(4),
// /**
// * Frequency measurement (rising-edge-to-rising-edge) with 16x scaling.
// */
// FREQ_SCALE_16(16);
//
// /**
// * The scaling factor as an integer.
// */
// public final int scaling;
//
// private PulseMode(int s) {
// scaling = s;
// }
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/TwiMaster.java
// enum Rate {
// RATE_100KHz, RATE_400KHz, RATE_1MHz
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/Uart.java
// enum Parity {
// /**
// * No parity.
// */
// NONE,
// /**
// * Even parity.
// */
// EVEN,
// /**
// * Odd parity.
// */
// ODD
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/Uart.java
// enum StopBits {
// /**
// * One stop bit.
// */
// ONE,
// /**
// * Two stop bits.
// */
// TWO
// }
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIO.java
import ioio.lib.api.PulseInput.PulseMode;
import ioio.lib.api.TwiMaster.Rate;
import ioio.lib.api.Uart.Parity;
import ioio.lib.api.Uart.StopBits;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.api.exception.IncompatibilityException;
import ioio.lib.api.exception.OutOfResourceException;
import java.io.Closeable;
* @param clk Pin specification for the CLK pin, consisting of the pin number, as labeled on the
* board, and the mode, which determines whether the pin will be normal or
* open-drain. See {@link DigitalOutput.Spec.Mode} for more information.
* @param slaveSelect An array of pin specifications for each of the slaves' SS (Slave Select) pin. The
* index of this array designates the slave index, used later to refer to this slave.
* The spec is consisting of the pin number, as labeled on the board, and the mode,
* which determines whether the pin will be normal or open-drain. See
* {@link DigitalOutput.Spec.Mode} for more information.
* @param config The configuration of the SPI module. See {@link SpiMaster.Config} for details.
* @return Interface of the assigned module.
* @throws ConnectionLostException Connection was lost before or during the execution of this method.
* @throws OutOfResourceException This is a runtime exception, so it is not necessary to catch it if the client
* guarantees that the total number of concurrent SPI resources is not exceeded.
* @see SpiMaster
*/
public SpiMaster openSpiMaster(DigitalInput.Spec miso, DigitalOutput.Spec mosi,
DigitalOutput.Spec clk, DigitalOutput.Spec[] slaveSelect, SpiMaster.Config config)
throws ConnectionLostException;
/**
* Shorthand for
* {@link #openSpiMaster(ioio.lib.api.DigitalInput.Spec, ioio.lib.api.DigitalOutput.Spec, ioio.lib.api.DigitalOutput.Spec, ioio.lib.api.DigitalOutput.Spec[], ioio.lib.api.SpiMaster.Config)}
* , where the pins are all open with the default modes and default configuration values are
* used.
*
* @see #openSpiMaster(ioio.lib.api.DigitalInput.Spec, ioio.lib.api.DigitalOutput.Spec,
* ioio.lib.api.DigitalOutput.Spec, ioio.lib.api.DigitalOutput.Spec[],
* ioio.lib.api.SpiMaster.Config)
*/
public SpiMaster openSpiMaster(int miso, int mosi, int clk, int[] slaveSelect, | SpiMaster.Rate rate) throws ConnectionLostException; |
flyver/Flyver-SDK | IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/UartImpl.java | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/Uart.java
// public interface Uart extends Closeable {
// /**
// * Parity-bit mode.
// */
// enum Parity {
// /**
// * No parity.
// */
// NONE,
// /**
// * Even parity.
// */
// EVEN,
// /**
// * Odd parity.
// */
// ODD
// }
//
// /**
// * Number of stop-bits.
// */
// enum StopBits {
// /**
// * One stop bit.
// */
// ONE,
// /**
// * Two stop bits.
// */
// TWO
// }
//
// /**
// * Gets the input stream.
// *
// * @return An input stream.
// */
// public InputStream getInputStream();
//
// /**
// * Gets the output stream.
// *
// * @return An output stream.
// */
// public OutputStream getOutputStream();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/FlowControlledOutputStream.java
// interface Sender {
// void send(byte[] data, int size);
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/IncomingState.java
// interface DataModuleListener {
// void dataReceived(byte[] data, int size);
//
// void reportAdditionalBuffer(int bytesToAdd);
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/Log.java
// public class Log {
// public static int println(int priority, String tag, String msg) {
// return android.util.Log.println(priority, tag, msg);
// }
//
// public static void e(String tag, String message) {
// android.util.Log.e(tag, message);
// }
//
// public static void e(String tag, String message, Throwable tr) {
// android.util.Log.e(tag, message, tr);
// }
//
// public static void w(String tag, String message) {
// android.util.Log.w(tag, message);
// }
//
// public static void w(String tag, String message, Throwable tr) {
// android.util.Log.w(tag, message);
// }
//
// public static void i(String tag, String message) {
// android.util.Log.i(tag, message);
// }
//
// public static void d(String tag, String message) {
// android.util.Log.d(tag, message);
// }
//
// public static void v(String tag, String message) {
// android.util.Log.v(tag, message);
// }
// }
| import java.io.OutputStream;
import ioio.lib.api.Uart;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.impl.FlowControlledOutputStream.Sender;
import ioio.lib.impl.IncomingState.DataModuleListener;
import ioio.lib.impl.ResourceManager.Resource;
import ioio.lib.spi.Log;
import java.io.IOException;
import java.io.InputStream; | /*
* Copyright 2011 Ytai Ben-Tsvi. All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARSHAN POURSOHI OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied.
*/
package ioio.lib.impl;
class UartImpl extends AbstractResource implements DataModuleListener, Sender, Uart {
private static final int MAX_PACKET = 64;
private final Resource uart_;
private final Resource rxPin_;
private final Resource txPin_;
private final FlowControlledOutputStream outgoing_ = new FlowControlledOutputStream(this, MAX_PACKET);
private final QueueInputStream incoming_ = new QueueInputStream();
public UartImpl(IOIOImpl ioio, Resource txPin, Resource rxPin, Resource uartNum) throws ConnectionLostException {
super(ioio);
uart_ = uartNum;
rxPin_ = rxPin;
txPin_ = txPin;
}
@Override
public void dataReceived(byte[] data, int size) {
incoming_.write(data, size);
}
@Override
public void send(byte[] data, int size) {
try {
ioio_.protocol_.uartData(uart_.id, size, data);
} catch (IOException e) { | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/Uart.java
// public interface Uart extends Closeable {
// /**
// * Parity-bit mode.
// */
// enum Parity {
// /**
// * No parity.
// */
// NONE,
// /**
// * Even parity.
// */
// EVEN,
// /**
// * Odd parity.
// */
// ODD
// }
//
// /**
// * Number of stop-bits.
// */
// enum StopBits {
// /**
// * One stop bit.
// */
// ONE,
// /**
// * Two stop bits.
// */
// TWO
// }
//
// /**
// * Gets the input stream.
// *
// * @return An input stream.
// */
// public InputStream getInputStream();
//
// /**
// * Gets the output stream.
// *
// * @return An output stream.
// */
// public OutputStream getOutputStream();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/FlowControlledOutputStream.java
// interface Sender {
// void send(byte[] data, int size);
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/IncomingState.java
// interface DataModuleListener {
// void dataReceived(byte[] data, int size);
//
// void reportAdditionalBuffer(int bytesToAdd);
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/Log.java
// public class Log {
// public static int println(int priority, String tag, String msg) {
// return android.util.Log.println(priority, tag, msg);
// }
//
// public static void e(String tag, String message) {
// android.util.Log.e(tag, message);
// }
//
// public static void e(String tag, String message, Throwable tr) {
// android.util.Log.e(tag, message, tr);
// }
//
// public static void w(String tag, String message) {
// android.util.Log.w(tag, message);
// }
//
// public static void w(String tag, String message, Throwable tr) {
// android.util.Log.w(tag, message);
// }
//
// public static void i(String tag, String message) {
// android.util.Log.i(tag, message);
// }
//
// public static void d(String tag, String message) {
// android.util.Log.d(tag, message);
// }
//
// public static void v(String tag, String message) {
// android.util.Log.v(tag, message);
// }
// }
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/UartImpl.java
import java.io.OutputStream;
import ioio.lib.api.Uart;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.impl.FlowControlledOutputStream.Sender;
import ioio.lib.impl.IncomingState.DataModuleListener;
import ioio.lib.impl.ResourceManager.Resource;
import ioio.lib.spi.Log;
import java.io.IOException;
import java.io.InputStream;
/*
* Copyright 2011 Ytai Ben-Tsvi. All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARSHAN POURSOHI OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied.
*/
package ioio.lib.impl;
class UartImpl extends AbstractResource implements DataModuleListener, Sender, Uart {
private static final int MAX_PACKET = 64;
private final Resource uart_;
private final Resource rxPin_;
private final Resource txPin_;
private final FlowControlledOutputStream outgoing_ = new FlowControlledOutputStream(this, MAX_PACKET);
private final QueueInputStream incoming_ = new QueueInputStream();
public UartImpl(IOIOImpl ioio, Resource txPin, Resource rxPin, Resource uartNum) throws ConnectionLostException {
super(ioio);
uart_ = uartNum;
rxPin_ = rxPin;
txPin_ = txPin;
}
@Override
public void dataReceived(byte[] data, int size) {
incoming_.write(data, size);
}
@Override
public void send(byte[] data, int size) {
try {
ioio_.protocol_.uartData(uart_.id, size, data);
} catch (IOException e) { | Log.e("UartImpl", e.getMessage()); |
flyver/Flyver-SDK | IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionFactory.java | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIOConnection.java
// public interface IOIOConnection {
// void waitForConnect() throws ConnectionLostException;
//
// void disconnect();
//
// InputStream getInputStream() throws ConnectionLostException;
//
// OutputStream getOutputStream() throws ConnectionLostException;
//
// /**
// * Can this connection be closed. Normally the answer would be "true", but
// * some weird connections cannot be closed and need the higher layer to do
// * a "soft close" instead.
// *
// * @return true This connection can be closed.
// */
// boolean canClose();
// }
| import ioio.lib.api.IOIOConnection; | /*
* Copyright 2013 Ytai Ben-Tsvi. All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARSHAN POURSOHI OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied.
*/
package ioio.lib.spi;
public interface IOIOConnectionFactory {
/**
* A unique name of the connection type. Typically a fully-qualified
* name of the connection class.
*/
public String getType();
/**
* Extra information on the connection. This is specific to the
* connection type. For example, for a Bluetooth connection, this is an
* array containing the name and the Bluetooth address of the remote
* IOIO.
*/
public Object getExtra();
| // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIOConnection.java
// public interface IOIOConnection {
// void waitForConnect() throws ConnectionLostException;
//
// void disconnect();
//
// InputStream getInputStream() throws ConnectionLostException;
//
// OutputStream getOutputStream() throws ConnectionLostException;
//
// /**
// * Can this connection be closed. Normally the answer would be "true", but
// * some weird connections cannot be closed and need the higher layer to do
// * a "soft close" instead.
// *
// * @return true This connection can be closed.
// */
// boolean canClose();
// }
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionFactory.java
import ioio.lib.api.IOIOConnection;
/*
* Copyright 2013 Ytai Ben-Tsvi. All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARSHAN POURSOHI OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied.
*/
package ioio.lib.spi;
public interface IOIOConnectionFactory {
/**
* A unique name of the connection type. Typically a fully-qualified
* name of the connection class.
*/
public String getType();
/**
* Extra information on the connection. This is specific to the
* connection type. For example, for a Bluetooth connection, this is an
* array containing the name and the Bluetooth address of the remote
* IOIO.
*/
public Object getExtra();
| public IOIOConnection createConnection(); |
flyver/Flyver-SDK | IOIO/iOIOLibBT/src/main/java/ioio/lib/android/bluetooth/BluetoothIOIOConnectionBootstrap.java | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIOConnection.java
// public interface IOIOConnection {
// void waitForConnect() throws ConnectionLostException;
//
// void disconnect();
//
// InputStream getInputStream() throws ConnectionLostException;
//
// OutputStream getOutputStream() throws ConnectionLostException;
//
// /**
// * Can this connection be closed. Normally the answer would be "true", but
// * some weird connections cannot be closed and need the higher layer to do
// * a "soft close" instead.
// *
// * @return true This connection can be closed.
// */
// boolean canClose();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionBootstrap.java
// public interface IOIOConnectionBootstrap {
// public void getFactories(Collection<IOIOConnectionFactory> result);
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionFactory.java
// public interface IOIOConnectionFactory {
// /**
// * A unique name of the connection type. Typically a fully-qualified
// * name of the connection class.
// */
// public String getType();
//
// /**
// * Extra information on the connection. This is specific to the
// * connection type. For example, for a Bluetooth connection, this is an
// * array containing the name and the Bluetooth address of the remote
// * IOIO.
// */
// public Object getExtra();
//
// public IOIOConnection createConnection();
// }
| import android.util.Log;
import java.util.Collection;
import java.util.Set;
import ioio.lib.api.IOIOConnection;
import ioio.lib.spi.IOIOConnectionBootstrap;
import ioio.lib.spi.IOIOConnectionFactory;
import ioio.lib.spi.NoRuntimeSupportException;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice; | /*
* Copyright 2011 Ytai Ben-Tsvi. All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARSHAN POURSOHI OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied.
*/
package ioio.lib.android.bluetooth;
public class BluetoothIOIOConnectionBootstrap implements
IOIOConnectionBootstrap {
private static final String TAG = "BluetoothIOIOConnectionDiscovery";
private final BluetoothAdapter adapter_;
public BluetoothIOIOConnectionBootstrap() throws NoRuntimeSupportException {
try {
adapter_ = BluetoothAdapter.getDefaultAdapter();
if (adapter_ != null) {
return;
}
} catch (Throwable e) {
}
throw new NoRuntimeSupportException(
"Bluetooth is not supported on this device.");
}
@Override | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIOConnection.java
// public interface IOIOConnection {
// void waitForConnect() throws ConnectionLostException;
//
// void disconnect();
//
// InputStream getInputStream() throws ConnectionLostException;
//
// OutputStream getOutputStream() throws ConnectionLostException;
//
// /**
// * Can this connection be closed. Normally the answer would be "true", but
// * some weird connections cannot be closed and need the higher layer to do
// * a "soft close" instead.
// *
// * @return true This connection can be closed.
// */
// boolean canClose();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionBootstrap.java
// public interface IOIOConnectionBootstrap {
// public void getFactories(Collection<IOIOConnectionFactory> result);
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionFactory.java
// public interface IOIOConnectionFactory {
// /**
// * A unique name of the connection type. Typically a fully-qualified
// * name of the connection class.
// */
// public String getType();
//
// /**
// * Extra information on the connection. This is specific to the
// * connection type. For example, for a Bluetooth connection, this is an
// * array containing the name and the Bluetooth address of the remote
// * IOIO.
// */
// public Object getExtra();
//
// public IOIOConnection createConnection();
// }
// Path: IOIO/iOIOLibBT/src/main/java/ioio/lib/android/bluetooth/BluetoothIOIOConnectionBootstrap.java
import android.util.Log;
import java.util.Collection;
import java.util.Set;
import ioio.lib.api.IOIOConnection;
import ioio.lib.spi.IOIOConnectionBootstrap;
import ioio.lib.spi.IOIOConnectionFactory;
import ioio.lib.spi.NoRuntimeSupportException;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
/*
* Copyright 2011 Ytai Ben-Tsvi. All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARSHAN POURSOHI OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied.
*/
package ioio.lib.android.bluetooth;
public class BluetoothIOIOConnectionBootstrap implements
IOIOConnectionBootstrap {
private static final String TAG = "BluetoothIOIOConnectionDiscovery";
private final BluetoothAdapter adapter_;
public BluetoothIOIOConnectionBootstrap() throws NoRuntimeSupportException {
try {
adapter_ = BluetoothAdapter.getDefaultAdapter();
if (adapter_ != null) {
return;
}
} catch (Throwable e) {
}
throw new NoRuntimeSupportException(
"Bluetooth is not supported on this device.");
}
@Override | public void getFactories(Collection<IOIOConnectionFactory> result) { |
flyver/Flyver-SDK | IOIO/iOIOLibBT/src/main/java/ioio/lib/android/bluetooth/BluetoothIOIOConnectionBootstrap.java | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIOConnection.java
// public interface IOIOConnection {
// void waitForConnect() throws ConnectionLostException;
//
// void disconnect();
//
// InputStream getInputStream() throws ConnectionLostException;
//
// OutputStream getOutputStream() throws ConnectionLostException;
//
// /**
// * Can this connection be closed. Normally the answer would be "true", but
// * some weird connections cannot be closed and need the higher layer to do
// * a "soft close" instead.
// *
// * @return true This connection can be closed.
// */
// boolean canClose();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionBootstrap.java
// public interface IOIOConnectionBootstrap {
// public void getFactories(Collection<IOIOConnectionFactory> result);
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionFactory.java
// public interface IOIOConnectionFactory {
// /**
// * A unique name of the connection type. Typically a fully-qualified
// * name of the connection class.
// */
// public String getType();
//
// /**
// * Extra information on the connection. This is specific to the
// * connection type. For example, for a Bluetooth connection, this is an
// * array containing the name and the Bluetooth address of the remote
// * IOIO.
// */
// public Object getExtra();
//
// public IOIOConnection createConnection();
// }
| import android.util.Log;
import java.util.Collection;
import java.util.Set;
import ioio.lib.api.IOIOConnection;
import ioio.lib.spi.IOIOConnectionBootstrap;
import ioio.lib.spi.IOIOConnectionFactory;
import ioio.lib.spi.NoRuntimeSupportException;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice; | adapter_ = BluetoothAdapter.getDefaultAdapter();
if (adapter_ != null) {
return;
}
} catch (Throwable e) {
}
throw new NoRuntimeSupportException(
"Bluetooth is not supported on this device.");
}
@Override
public void getFactories(Collection<IOIOConnectionFactory> result) {
try {
Set<BluetoothDevice> bondedDevices = adapter_.getBondedDevices();
for (final BluetoothDevice device : bondedDevices) {
if (device.getName().startsWith("IOIO")) {
result.add(new IOIOConnectionFactory() {
@Override
public String getType() {
return BluetoothIOIOConnection.class
.getCanonicalName();
}
@Override
public Object getExtra() {
return new Object[]{device.getName(),
device.getAddress()};
}
@Override | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIOConnection.java
// public interface IOIOConnection {
// void waitForConnect() throws ConnectionLostException;
//
// void disconnect();
//
// InputStream getInputStream() throws ConnectionLostException;
//
// OutputStream getOutputStream() throws ConnectionLostException;
//
// /**
// * Can this connection be closed. Normally the answer would be "true", but
// * some weird connections cannot be closed and need the higher layer to do
// * a "soft close" instead.
// *
// * @return true This connection can be closed.
// */
// boolean canClose();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionBootstrap.java
// public interface IOIOConnectionBootstrap {
// public void getFactories(Collection<IOIOConnectionFactory> result);
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionFactory.java
// public interface IOIOConnectionFactory {
// /**
// * A unique name of the connection type. Typically a fully-qualified
// * name of the connection class.
// */
// public String getType();
//
// /**
// * Extra information on the connection. This is specific to the
// * connection type. For example, for a Bluetooth connection, this is an
// * array containing the name and the Bluetooth address of the remote
// * IOIO.
// */
// public Object getExtra();
//
// public IOIOConnection createConnection();
// }
// Path: IOIO/iOIOLibBT/src/main/java/ioio/lib/android/bluetooth/BluetoothIOIOConnectionBootstrap.java
import android.util.Log;
import java.util.Collection;
import java.util.Set;
import ioio.lib.api.IOIOConnection;
import ioio.lib.spi.IOIOConnectionBootstrap;
import ioio.lib.spi.IOIOConnectionFactory;
import ioio.lib.spi.NoRuntimeSupportException;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
adapter_ = BluetoothAdapter.getDefaultAdapter();
if (adapter_ != null) {
return;
}
} catch (Throwable e) {
}
throw new NoRuntimeSupportException(
"Bluetooth is not supported on this device.");
}
@Override
public void getFactories(Collection<IOIOConnectionFactory> result) {
try {
Set<BluetoothDevice> bondedDevices = adapter_.getBondedDevices();
for (final BluetoothDevice device : bondedDevices) {
if (device.getName().startsWith("IOIO")) {
result.add(new IOIOConnectionFactory() {
@Override
public String getType() {
return BluetoothIOIOConnection.class
.getCanonicalName();
}
@Override
public Object getExtra() {
return new Object[]{device.getName(),
device.getAddress()};
}
@Override | public IOIOConnection createConnection() { |
flyver/Flyver-SDK | IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/TwiMasterImpl.java | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/TwiMaster.java
// public interface TwiMaster extends Closeable {
// enum Rate {
// RATE_100KHz, RATE_400KHz, RATE_1MHz
// }
//
// /**
// * An object that can be waited on for asynchronous calls.
// */
// public interface Result {
// /**
// * Wait until the asynchronous call which returned this instance is
// * complete.
// *
// * @return true if TWI transaction succeeded.
// * @throws ConnectionLostException Connection with the IOIO has been lost.
// * @throws InterruptedException This operation has been interrupted.
// */
// public boolean waitReady() throws ConnectionLostException,
// InterruptedException;
// }
//
// /**
// * Perform a single TWI transaction which includes optional transmission and
// * optional reception of data to a single slave. This is a blocking
// * operation that can take a few milliseconds to a few tens of milliseconds.
// * To abort this operation, client can interrupt the blocked thread.
// *
// * @param address The slave address, either 7-bit or 10-bit. Note that in some
// * TWI device documentation the documented addresses are actually
// * 2x the address values used here, as they regard the trailing
// * 0-bit as part of the address.
// * @param tenBitAddr Whether this is a 10-bit addressing mode.
// * @param writeData The request data.
// * @param writeSize The number of bytes to write. Valid value are 0-255.
// * @param readData The array where the response should be stored.
// * @param readSize The expected number of response bytes. Valid value are 0-255.
// * @return Whether operation succeeded.
// * @throws ConnectionLostException Connection to the IOIO has been lost.
// * @throws InterruptedException Calling thread has been interrupted.
// */
// public boolean writeRead(int address, boolean tenBitAddr, byte[] writeData,
// int writeSize, byte[] readData, int readSize)
// throws ConnectionLostException, InterruptedException;
//
// /**
// * Asynchronous version of
// * {@link #writeRead(int, boolean, byte[], int, byte[], int)}. Returns
// * immediately and provides a {@link Result} object on which the client can
// * wait for the result.
// *
// * @see #writeRead(int, boolean, byte[], int, byte[], int)
// */
// public Result writeReadAsync(int address, boolean tenBitAddr,
// byte[] writeData, int writeSize, byte[] readData, int readSize)
// throws ConnectionLostException;
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/IncomingState.java
// interface DataModuleListener {
// void dataReceived(byte[] data, int size);
//
// void reportAdditionalBuffer(int bytesToAdd);
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/Log.java
// public class Log {
// public static int println(int priority, String tag, String msg) {
// return android.util.Log.println(priority, tag, msg);
// }
//
// public static void e(String tag, String message) {
// android.util.Log.e(tag, message);
// }
//
// public static void e(String tag, String message, Throwable tr) {
// android.util.Log.e(tag, message, tr);
// }
//
// public static void w(String tag, String message) {
// android.util.Log.w(tag, message);
// }
//
// public static void w(String tag, String message, Throwable tr) {
// android.util.Log.w(tag, message);
// }
//
// public static void i(String tag, String message) {
// android.util.Log.i(tag, message);
// }
//
// public static void d(String tag, String message) {
// android.util.Log.d(tag, message);
// }
//
// public static void v(String tag, String message) {
// android.util.Log.v(tag, message);
// }
// }
| import java.util.concurrent.ConcurrentLinkedQueue;
import ioio.lib.api.TwiMaster;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.impl.FlowControlledPacketSender.Packet;
import ioio.lib.impl.FlowControlledPacketSender.Sender;
import ioio.lib.impl.IncomingState.DataModuleListener;
import ioio.lib.impl.ResourceManager.Resource;
import ioio.lib.spi.Log;
import java.io.IOException;
import java.util.Queue; | }
@Override
public boolean writeRead(int address, boolean tenBitAddr, byte[] writeData,
int writeSize, byte[] readData, int readSize)
throws ConnectionLostException, InterruptedException {
Result result = writeReadAsync(address, tenBitAddr, writeData,
writeSize, readData, readSize);
return result.waitReady();
}
@Override
public Result writeReadAsync(int address, boolean tenBitAddr,
byte[] writeData, int writeSize, byte[] readData, int readSize)
throws ConnectionLostException {
checkState();
TwiResult result = new TwiResult(readData);
OutgoingPacket p = new OutgoingPacket();
p.writeSize_ = writeSize;
p.writeData_ = writeData;
p.tenBitAddr_ = tenBitAddr;
p.readSize_ = readSize;
p.addr_ = address;
synchronized (this) {
pendingRequests_.add(result);
try {
outgoing_.write(p);
} catch (IOException e) { | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/TwiMaster.java
// public interface TwiMaster extends Closeable {
// enum Rate {
// RATE_100KHz, RATE_400KHz, RATE_1MHz
// }
//
// /**
// * An object that can be waited on for asynchronous calls.
// */
// public interface Result {
// /**
// * Wait until the asynchronous call which returned this instance is
// * complete.
// *
// * @return true if TWI transaction succeeded.
// * @throws ConnectionLostException Connection with the IOIO has been lost.
// * @throws InterruptedException This operation has been interrupted.
// */
// public boolean waitReady() throws ConnectionLostException,
// InterruptedException;
// }
//
// /**
// * Perform a single TWI transaction which includes optional transmission and
// * optional reception of data to a single slave. This is a blocking
// * operation that can take a few milliseconds to a few tens of milliseconds.
// * To abort this operation, client can interrupt the blocked thread.
// *
// * @param address The slave address, either 7-bit or 10-bit. Note that in some
// * TWI device documentation the documented addresses are actually
// * 2x the address values used here, as they regard the trailing
// * 0-bit as part of the address.
// * @param tenBitAddr Whether this is a 10-bit addressing mode.
// * @param writeData The request data.
// * @param writeSize The number of bytes to write. Valid value are 0-255.
// * @param readData The array where the response should be stored.
// * @param readSize The expected number of response bytes. Valid value are 0-255.
// * @return Whether operation succeeded.
// * @throws ConnectionLostException Connection to the IOIO has been lost.
// * @throws InterruptedException Calling thread has been interrupted.
// */
// public boolean writeRead(int address, boolean tenBitAddr, byte[] writeData,
// int writeSize, byte[] readData, int readSize)
// throws ConnectionLostException, InterruptedException;
//
// /**
// * Asynchronous version of
// * {@link #writeRead(int, boolean, byte[], int, byte[], int)}. Returns
// * immediately and provides a {@link Result} object on which the client can
// * wait for the result.
// *
// * @see #writeRead(int, boolean, byte[], int, byte[], int)
// */
// public Result writeReadAsync(int address, boolean tenBitAddr,
// byte[] writeData, int writeSize, byte[] readData, int readSize)
// throws ConnectionLostException;
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/IncomingState.java
// interface DataModuleListener {
// void dataReceived(byte[] data, int size);
//
// void reportAdditionalBuffer(int bytesToAdd);
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/Log.java
// public class Log {
// public static int println(int priority, String tag, String msg) {
// return android.util.Log.println(priority, tag, msg);
// }
//
// public static void e(String tag, String message) {
// android.util.Log.e(tag, message);
// }
//
// public static void e(String tag, String message, Throwable tr) {
// android.util.Log.e(tag, message, tr);
// }
//
// public static void w(String tag, String message) {
// android.util.Log.w(tag, message);
// }
//
// public static void w(String tag, String message, Throwable tr) {
// android.util.Log.w(tag, message);
// }
//
// public static void i(String tag, String message) {
// android.util.Log.i(tag, message);
// }
//
// public static void d(String tag, String message) {
// android.util.Log.d(tag, message);
// }
//
// public static void v(String tag, String message) {
// android.util.Log.v(tag, message);
// }
// }
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/TwiMasterImpl.java
import java.util.concurrent.ConcurrentLinkedQueue;
import ioio.lib.api.TwiMaster;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.impl.FlowControlledPacketSender.Packet;
import ioio.lib.impl.FlowControlledPacketSender.Sender;
import ioio.lib.impl.IncomingState.DataModuleListener;
import ioio.lib.impl.ResourceManager.Resource;
import ioio.lib.spi.Log;
import java.io.IOException;
import java.util.Queue;
}
@Override
public boolean writeRead(int address, boolean tenBitAddr, byte[] writeData,
int writeSize, byte[] readData, int readSize)
throws ConnectionLostException, InterruptedException {
Result result = writeReadAsync(address, tenBitAddr, writeData,
writeSize, readData, readSize);
return result.waitReady();
}
@Override
public Result writeReadAsync(int address, boolean tenBitAddr,
byte[] writeData, int writeSize, byte[] readData, int readSize)
throws ConnectionLostException {
checkState();
TwiResult result = new TwiResult(readData);
OutgoingPacket p = new OutgoingPacket();
p.writeSize_ = writeSize;
p.writeData_ = writeData;
p.tenBitAddr_ = tenBitAddr;
p.readSize_ = readSize;
p.addr_ = address;
synchronized (this) {
pendingRequests_.add(result);
try {
outgoing_.write(p);
} catch (IOException e) { | Log.e("SpiMasterImpl", "Exception caught", e); |
flyver/Flyver-SDK | utils/src/main/java/co/flyver/utils/flyverMQ/FlyverMQProducer.java | // Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/NoSuchTopicException.java
// public class NoSuchTopicException extends Exception {
// public NoSuchTopicException(String detailMessage) {
// super(detailMessage);
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/ProducerAlreadyRegisteredException.java
// public class ProducerAlreadyRegisteredException extends Exception {
// public ProducerAlreadyRegisteredException(String detailMessage) {
// super(detailMessage);
// }
// }
| import co.flyver.utils.flyverMQ.exceptions.NoSuchTopicException;
import co.flyver.utils.flyverMQ.exceptions.ProducerAlreadyRegisteredException; | package co.flyver.utils.flyverMQ;
/**
* Created by Petar Petrov on 1/12/15.
*/
/**
* Abstract class implementing MQ producer functionallity
* Every producer must subclass it before registering for the message queue
*/
public abstract class FlyverMQProducer {
final String TAG = "Producers";
String topic;
boolean registered = false;
protected FlyverMQProducer() {
}
public FlyverMQProducer(String topic) {
this.topic = topic;
}
public void addMessage(FlyverMQMessage msg) {
if(registered) {
try {
FlyverMQ.getInstance().addMessage(this, msg); | // Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/NoSuchTopicException.java
// public class NoSuchTopicException extends Exception {
// public NoSuchTopicException(String detailMessage) {
// super(detailMessage);
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/ProducerAlreadyRegisteredException.java
// public class ProducerAlreadyRegisteredException extends Exception {
// public ProducerAlreadyRegisteredException(String detailMessage) {
// super(detailMessage);
// }
// }
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/FlyverMQProducer.java
import co.flyver.utils.flyverMQ.exceptions.NoSuchTopicException;
import co.flyver.utils.flyverMQ.exceptions.ProducerAlreadyRegisteredException;
package co.flyver.utils.flyverMQ;
/**
* Created by Petar Petrov on 1/12/15.
*/
/**
* Abstract class implementing MQ producer functionallity
* Every producer must subclass it before registering for the message queue
*/
public abstract class FlyverMQProducer {
final String TAG = "Producers";
String topic;
boolean registered = false;
protected FlyverMQProducer() {
}
public FlyverMQProducer(String topic) {
this.topic = topic;
}
public void addMessage(FlyverMQMessage msg) {
if(registered) {
try {
FlyverMQ.getInstance().addMessage(this, msg); | } catch (NoSuchTopicException e) { |
flyver/Flyver-SDK | utils/src/main/java/co/flyver/utils/flyverMQ/FlyverMQProducer.java | // Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/NoSuchTopicException.java
// public class NoSuchTopicException extends Exception {
// public NoSuchTopicException(String detailMessage) {
// super(detailMessage);
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/ProducerAlreadyRegisteredException.java
// public class ProducerAlreadyRegisteredException extends Exception {
// public ProducerAlreadyRegisteredException(String detailMessage) {
// super(detailMessage);
// }
// }
| import co.flyver.utils.flyverMQ.exceptions.NoSuchTopicException;
import co.flyver.utils.flyverMQ.exceptions.ProducerAlreadyRegisteredException; | package co.flyver.utils.flyverMQ;
/**
* Created by Petar Petrov on 1/12/15.
*/
/**
* Abstract class implementing MQ producer functionallity
* Every producer must subclass it before registering for the message queue
*/
public abstract class FlyverMQProducer {
final String TAG = "Producers";
String topic;
boolean registered = false;
protected FlyverMQProducer() {
}
public FlyverMQProducer(String topic) {
this.topic = topic;
}
public void addMessage(FlyverMQMessage msg) {
if(registered) {
try {
FlyverMQ.getInstance().addMessage(this, msg);
} catch (NoSuchTopicException e) {
e.printStackTrace();
}
}
}
| // Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/NoSuchTopicException.java
// public class NoSuchTopicException extends Exception {
// public NoSuchTopicException(String detailMessage) {
// super(detailMessage);
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/ProducerAlreadyRegisteredException.java
// public class ProducerAlreadyRegisteredException extends Exception {
// public ProducerAlreadyRegisteredException(String detailMessage) {
// super(detailMessage);
// }
// }
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/FlyverMQProducer.java
import co.flyver.utils.flyverMQ.exceptions.NoSuchTopicException;
import co.flyver.utils.flyverMQ.exceptions.ProducerAlreadyRegisteredException;
package co.flyver.utils.flyverMQ;
/**
* Created by Petar Petrov on 1/12/15.
*/
/**
* Abstract class implementing MQ producer functionallity
* Every producer must subclass it before registering for the message queue
*/
public abstract class FlyverMQProducer {
final String TAG = "Producers";
String topic;
boolean registered = false;
protected FlyverMQProducer() {
}
public FlyverMQProducer(String topic) {
this.topic = topic;
}
public void addMessage(FlyverMQMessage msg) {
if(registered) {
try {
FlyverMQ.getInstance().addMessage(this, msg);
} catch (NoSuchTopicException e) {
e.printStackTrace();
}
}
}
| public void register(boolean removeExisting) throws ProducerAlreadyRegisteredException { |
flyver/Flyver-SDK | IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/QueueInputStream.java | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/Log.java
// public class Log {
// public static int println(int priority, String tag, String msg) {
// return android.util.Log.println(priority, tag, msg);
// }
//
// public static void e(String tag, String message) {
// android.util.Log.e(tag, message);
// }
//
// public static void e(String tag, String message, Throwable tr) {
// android.util.Log.e(tag, message, tr);
// }
//
// public static void w(String tag, String message) {
// android.util.Log.w(tag, message);
// }
//
// public static void w(String tag, String message, Throwable tr) {
// android.util.Log.w(tag, message);
// }
//
// public static void i(String tag, String message) {
// android.util.Log.i(tag, message);
// }
//
// public static void d(String tag, String message) {
// android.util.Log.d(tag, message);
// }
//
// public static void v(String tag, String message) {
// android.util.Log.v(tag, message);
// }
// }
| import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import ioio.lib.spi.Log;
import java.io.IOException;
import java.io.InputStream; | @Override
synchronized public int read(byte[] b, int off, int len) throws IOException {
if (len == 0) {
return 0;
}
try {
while (state_ == State.OPEN && queue_.isEmpty()) {
wait();
}
if (state_ == State.KILLED) {
throw new IOException("Stream has been closed");
}
if (state_ == State.CLOSED && queue_.isEmpty()) {
return -1;
}
if (len > queue_.size()) {
len = queue_.size();
}
for (int i = 0; i < len; ++i) {
b[off++] = queue_.remove();
}
return len;
} catch (InterruptedException e) {
throw new IOException("Interrupted");
}
}
synchronized public void write(byte[] data, int size) {
for (int i = 0; i < size; ++i) {
if (queue_.size() == Constants.BUFFER_SIZE) { | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/Log.java
// public class Log {
// public static int println(int priority, String tag, String msg) {
// return android.util.Log.println(priority, tag, msg);
// }
//
// public static void e(String tag, String message) {
// android.util.Log.e(tag, message);
// }
//
// public static void e(String tag, String message, Throwable tr) {
// android.util.Log.e(tag, message, tr);
// }
//
// public static void w(String tag, String message) {
// android.util.Log.w(tag, message);
// }
//
// public static void w(String tag, String message, Throwable tr) {
// android.util.Log.w(tag, message);
// }
//
// public static void i(String tag, String message) {
// android.util.Log.i(tag, message);
// }
//
// public static void d(String tag, String message) {
// android.util.Log.d(tag, message);
// }
//
// public static void v(String tag, String message) {
// android.util.Log.v(tag, message);
// }
// }
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/QueueInputStream.java
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import ioio.lib.spi.Log;
import java.io.IOException;
import java.io.InputStream;
@Override
synchronized public int read(byte[] b, int off, int len) throws IOException {
if (len == 0) {
return 0;
}
try {
while (state_ == State.OPEN && queue_.isEmpty()) {
wait();
}
if (state_ == State.KILLED) {
throw new IOException("Stream has been closed");
}
if (state_ == State.CLOSED && queue_.isEmpty()) {
return -1;
}
if (len > queue_.size()) {
len = queue_.size();
}
for (int i = 0; i < len; ++i) {
b[off++] = queue_.remove();
}
return len;
} catch (InterruptedException e) {
throw new IOException("Interrupted");
}
}
synchronized public void write(byte[] data, int size) {
for (int i = 0; i < size; ++i) {
if (queue_.size() == Constants.BUFFER_SIZE) { | Log.e("QueueInputStream", "Buffer overflow, discarding data"); |
flyver/Flyver-SDK | IOIO/iOIOLibAndroidDevice/src/main/java/ioio/lib/android/device/DeviceConnectionBootstrap.java | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIOConnection.java
// public interface IOIOConnection {
// void waitForConnect() throws ConnectionLostException;
//
// void disconnect();
//
// InputStream getInputStream() throws ConnectionLostException;
//
// OutputStream getOutputStream() throws ConnectionLostException;
//
// /**
// * Can this connection be closed. Normally the answer would be "true", but
// * some weird connections cannot be closed and need the higher layer to do
// * a "soft close" instead.
// *
// * @return true This connection can be closed.
// */
// boolean canClose();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/FixedReadBufferedInputStream.java
// public class FixedReadBufferedInputStream extends InputStream {
// private int bufferIndex_ = 0;
// private int validData_ = 0;
// private final byte[] buffer_;
// private final InputStream source_;
//
// public FixedReadBufferedInputStream(InputStream source, int size) {
// buffer_ = new byte[size];
// source_ = source;
// }
//
// @Override
// public int available() throws IOException {
// return validData_ - bufferIndex_;
// }
//
// @Override
// public void close() throws IOException {
// source_.close();
// }
//
// @Override
// public int read(byte[] buffer, int offset, int length) throws IOException {
// fillIfEmpty();
// if (validData_ == -1) {
// return -1;
// }
// length = Math.min(length, validData_ - bufferIndex_);
// System.arraycopy(buffer_, bufferIndex_, buffer, offset, length);
// bufferIndex_ += length;
// return length;
// }
//
// @Override
// public int read(byte[] buffer) throws IOException {
// return read(buffer, 0, buffer.length);
// }
//
// @Override
// public int read() throws IOException {
// fillIfEmpty();
// if (validData_ == -1) {
// return -1;
// }
// return buffer_[bufferIndex_++] & 0xFF;
// }
//
// @Override
// public long skip(long byteCount) throws IOException {
// long skipped = 0;
// while (byteCount > 0) {
// fillIfEmpty();
// if (validData_ == -1) {
// return skipped;
// }
// int count = (int) Math.min(available(), byteCount);
// byteCount -= count;
// bufferIndex_ += count;
// skipped += count;
// }
// return skipped;
// }
//
// private void fillIfEmpty() throws IOException {
// while (available() == 0 && validData_ != -1) {
// fill();
// }
// }
//
// private void fill() throws IOException {
// bufferIndex_ = 0;
// validData_ = source_.read(buffer_);
// }
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionBootstrap.java
// public interface IOIOConnectionBootstrap {
// public void getFactories(Collection<IOIOConnectionFactory> result);
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionFactory.java
// public interface IOIOConnectionFactory {
// /**
// * A unique name of the connection type. Typically a fully-qualified
// * name of the connection class.
// */
// public String getType();
//
// /**
// * Extra information on the connection. This is specific to the
// * connection type. For example, for a Bluetooth connection, this is an
// * array containing the name and the Bluetooth address of the remote
// * IOIO.
// */
// public Object getExtra();
//
// public IOIOConnection createConnection();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/util/android/ContextWrapperDependent.java
// public interface ContextWrapperDependent {
// public void onCreate(ContextWrapper wrapper);
//
// public void onDestroy();
//
// public void open();
//
// public void reopen();
//
// public void close();
// }
| import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.HashMap;
import ioio.lib.api.IOIOConnection;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.impl.FixedReadBufferedInputStream;
import ioio.lib.spi.IOIOConnectionBootstrap;
import ioio.lib.spi.IOIOConnectionFactory;
import ioio.lib.spi.NoRuntimeSupportException;
import ioio.lib.util.android.ContextWrapperDependent; | }
// State-related signals.
private State state_ = State.CLOSED;
private boolean shouldOpen_ = false;
private boolean shouldOpenDevice_ = false;
private Permission permission_ = Permission.UNKNOWN;
// Android-ism.
private ContextWrapper activity_;
private PendingIntent pendingIntent_;
// USB device stuff.
private UsbManager usbManager_;
private UsbDevice device_;
private UsbDeviceConnection connection_;
private UsbInterface controlInterface_;
private UsbInterface dataInterface_;
private UsbEndpoint epIn_;
private UsbEndpoint epOut_;
private InputStream inputStream_;
private OutputStream outputStream_;
public DeviceConnectionBootstrap() {
if (Build.VERSION.SDK_INT < 12) {
throw new NoRuntimeSupportException("OTG is not supported on this device.");
}
}
@Override | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIOConnection.java
// public interface IOIOConnection {
// void waitForConnect() throws ConnectionLostException;
//
// void disconnect();
//
// InputStream getInputStream() throws ConnectionLostException;
//
// OutputStream getOutputStream() throws ConnectionLostException;
//
// /**
// * Can this connection be closed. Normally the answer would be "true", but
// * some weird connections cannot be closed and need the higher layer to do
// * a "soft close" instead.
// *
// * @return true This connection can be closed.
// */
// boolean canClose();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/FixedReadBufferedInputStream.java
// public class FixedReadBufferedInputStream extends InputStream {
// private int bufferIndex_ = 0;
// private int validData_ = 0;
// private final byte[] buffer_;
// private final InputStream source_;
//
// public FixedReadBufferedInputStream(InputStream source, int size) {
// buffer_ = new byte[size];
// source_ = source;
// }
//
// @Override
// public int available() throws IOException {
// return validData_ - bufferIndex_;
// }
//
// @Override
// public void close() throws IOException {
// source_.close();
// }
//
// @Override
// public int read(byte[] buffer, int offset, int length) throws IOException {
// fillIfEmpty();
// if (validData_ == -1) {
// return -1;
// }
// length = Math.min(length, validData_ - bufferIndex_);
// System.arraycopy(buffer_, bufferIndex_, buffer, offset, length);
// bufferIndex_ += length;
// return length;
// }
//
// @Override
// public int read(byte[] buffer) throws IOException {
// return read(buffer, 0, buffer.length);
// }
//
// @Override
// public int read() throws IOException {
// fillIfEmpty();
// if (validData_ == -1) {
// return -1;
// }
// return buffer_[bufferIndex_++] & 0xFF;
// }
//
// @Override
// public long skip(long byteCount) throws IOException {
// long skipped = 0;
// while (byteCount > 0) {
// fillIfEmpty();
// if (validData_ == -1) {
// return skipped;
// }
// int count = (int) Math.min(available(), byteCount);
// byteCount -= count;
// bufferIndex_ += count;
// skipped += count;
// }
// return skipped;
// }
//
// private void fillIfEmpty() throws IOException {
// while (available() == 0 && validData_ != -1) {
// fill();
// }
// }
//
// private void fill() throws IOException {
// bufferIndex_ = 0;
// validData_ = source_.read(buffer_);
// }
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionBootstrap.java
// public interface IOIOConnectionBootstrap {
// public void getFactories(Collection<IOIOConnectionFactory> result);
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionFactory.java
// public interface IOIOConnectionFactory {
// /**
// * A unique name of the connection type. Typically a fully-qualified
// * name of the connection class.
// */
// public String getType();
//
// /**
// * Extra information on the connection. This is specific to the
// * connection type. For example, for a Bluetooth connection, this is an
// * array containing the name and the Bluetooth address of the remote
// * IOIO.
// */
// public Object getExtra();
//
// public IOIOConnection createConnection();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/util/android/ContextWrapperDependent.java
// public interface ContextWrapperDependent {
// public void onCreate(ContextWrapper wrapper);
//
// public void onDestroy();
//
// public void open();
//
// public void reopen();
//
// public void close();
// }
// Path: IOIO/iOIOLibAndroidDevice/src/main/java/ioio/lib/android/device/DeviceConnectionBootstrap.java
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.HashMap;
import ioio.lib.api.IOIOConnection;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.impl.FixedReadBufferedInputStream;
import ioio.lib.spi.IOIOConnectionBootstrap;
import ioio.lib.spi.IOIOConnectionFactory;
import ioio.lib.spi.NoRuntimeSupportException;
import ioio.lib.util.android.ContextWrapperDependent;
}
// State-related signals.
private State state_ = State.CLOSED;
private boolean shouldOpen_ = false;
private boolean shouldOpenDevice_ = false;
private Permission permission_ = Permission.UNKNOWN;
// Android-ism.
private ContextWrapper activity_;
private PendingIntent pendingIntent_;
// USB device stuff.
private UsbManager usbManager_;
private UsbDevice device_;
private UsbDeviceConnection connection_;
private UsbInterface controlInterface_;
private UsbInterface dataInterface_;
private UsbEndpoint epIn_;
private UsbEndpoint epOut_;
private InputStream inputStream_;
private OutputStream outputStream_;
public DeviceConnectionBootstrap() {
if (Build.VERSION.SDK_INT < 12) {
throw new NoRuntimeSupportException("OTG is not supported on this device.");
}
}
@Override | public void getFactories(Collection<IOIOConnectionFactory> result) { |
flyver/Flyver-SDK | IOIO/iOIOLibAndroidDevice/src/main/java/ioio/lib/android/device/DeviceConnectionBootstrap.java | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIOConnection.java
// public interface IOIOConnection {
// void waitForConnect() throws ConnectionLostException;
//
// void disconnect();
//
// InputStream getInputStream() throws ConnectionLostException;
//
// OutputStream getOutputStream() throws ConnectionLostException;
//
// /**
// * Can this connection be closed. Normally the answer would be "true", but
// * some weird connections cannot be closed and need the higher layer to do
// * a "soft close" instead.
// *
// * @return true This connection can be closed.
// */
// boolean canClose();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/FixedReadBufferedInputStream.java
// public class FixedReadBufferedInputStream extends InputStream {
// private int bufferIndex_ = 0;
// private int validData_ = 0;
// private final byte[] buffer_;
// private final InputStream source_;
//
// public FixedReadBufferedInputStream(InputStream source, int size) {
// buffer_ = new byte[size];
// source_ = source;
// }
//
// @Override
// public int available() throws IOException {
// return validData_ - bufferIndex_;
// }
//
// @Override
// public void close() throws IOException {
// source_.close();
// }
//
// @Override
// public int read(byte[] buffer, int offset, int length) throws IOException {
// fillIfEmpty();
// if (validData_ == -1) {
// return -1;
// }
// length = Math.min(length, validData_ - bufferIndex_);
// System.arraycopy(buffer_, bufferIndex_, buffer, offset, length);
// bufferIndex_ += length;
// return length;
// }
//
// @Override
// public int read(byte[] buffer) throws IOException {
// return read(buffer, 0, buffer.length);
// }
//
// @Override
// public int read() throws IOException {
// fillIfEmpty();
// if (validData_ == -1) {
// return -1;
// }
// return buffer_[bufferIndex_++] & 0xFF;
// }
//
// @Override
// public long skip(long byteCount) throws IOException {
// long skipped = 0;
// while (byteCount > 0) {
// fillIfEmpty();
// if (validData_ == -1) {
// return skipped;
// }
// int count = (int) Math.min(available(), byteCount);
// byteCount -= count;
// bufferIndex_ += count;
// skipped += count;
// }
// return skipped;
// }
//
// private void fillIfEmpty() throws IOException {
// while (available() == 0 && validData_ != -1) {
// fill();
// }
// }
//
// private void fill() throws IOException {
// bufferIndex_ = 0;
// validData_ = source_.read(buffer_);
// }
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionBootstrap.java
// public interface IOIOConnectionBootstrap {
// public void getFactories(Collection<IOIOConnectionFactory> result);
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionFactory.java
// public interface IOIOConnectionFactory {
// /**
// * A unique name of the connection type. Typically a fully-qualified
// * name of the connection class.
// */
// public String getType();
//
// /**
// * Extra information on the connection. This is specific to the
// * connection type. For example, for a Bluetooth connection, this is an
// * array containing the name and the Bluetooth address of the remote
// * IOIO.
// */
// public Object getExtra();
//
// public IOIOConnection createConnection();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/util/android/ContextWrapperDependent.java
// public interface ContextWrapperDependent {
// public void onCreate(ContextWrapper wrapper);
//
// public void onDestroy();
//
// public void open();
//
// public void reopen();
//
// public void close();
// }
| import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.HashMap;
import ioio.lib.api.IOIOConnection;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.impl.FixedReadBufferedInputStream;
import ioio.lib.spi.IOIOConnectionBootstrap;
import ioio.lib.spi.IOIOConnectionFactory;
import ioio.lib.spi.NoRuntimeSupportException;
import ioio.lib.util.android.ContextWrapperDependent; | private UsbManager usbManager_;
private UsbDevice device_;
private UsbDeviceConnection connection_;
private UsbInterface controlInterface_;
private UsbInterface dataInterface_;
private UsbEndpoint epIn_;
private UsbEndpoint epOut_;
private InputStream inputStream_;
private OutputStream outputStream_;
public DeviceConnectionBootstrap() {
if (Build.VERSION.SDK_INT < 12) {
throw new NoRuntimeSupportException("OTG is not supported on this device.");
}
}
@Override
public void getFactories(Collection<IOIOConnectionFactory> result) {
result.add(new IOIOConnectionFactory() {
@Override
public String getType() {
return DeviceConnectionBootstrap.class.getCanonicalName();
}
@Override
public Object getExtra() {
return null;
}
@Override | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIOConnection.java
// public interface IOIOConnection {
// void waitForConnect() throws ConnectionLostException;
//
// void disconnect();
//
// InputStream getInputStream() throws ConnectionLostException;
//
// OutputStream getOutputStream() throws ConnectionLostException;
//
// /**
// * Can this connection be closed. Normally the answer would be "true", but
// * some weird connections cannot be closed and need the higher layer to do
// * a "soft close" instead.
// *
// * @return true This connection can be closed.
// */
// boolean canClose();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/FixedReadBufferedInputStream.java
// public class FixedReadBufferedInputStream extends InputStream {
// private int bufferIndex_ = 0;
// private int validData_ = 0;
// private final byte[] buffer_;
// private final InputStream source_;
//
// public FixedReadBufferedInputStream(InputStream source, int size) {
// buffer_ = new byte[size];
// source_ = source;
// }
//
// @Override
// public int available() throws IOException {
// return validData_ - bufferIndex_;
// }
//
// @Override
// public void close() throws IOException {
// source_.close();
// }
//
// @Override
// public int read(byte[] buffer, int offset, int length) throws IOException {
// fillIfEmpty();
// if (validData_ == -1) {
// return -1;
// }
// length = Math.min(length, validData_ - bufferIndex_);
// System.arraycopy(buffer_, bufferIndex_, buffer, offset, length);
// bufferIndex_ += length;
// return length;
// }
//
// @Override
// public int read(byte[] buffer) throws IOException {
// return read(buffer, 0, buffer.length);
// }
//
// @Override
// public int read() throws IOException {
// fillIfEmpty();
// if (validData_ == -1) {
// return -1;
// }
// return buffer_[bufferIndex_++] & 0xFF;
// }
//
// @Override
// public long skip(long byteCount) throws IOException {
// long skipped = 0;
// while (byteCount > 0) {
// fillIfEmpty();
// if (validData_ == -1) {
// return skipped;
// }
// int count = (int) Math.min(available(), byteCount);
// byteCount -= count;
// bufferIndex_ += count;
// skipped += count;
// }
// return skipped;
// }
//
// private void fillIfEmpty() throws IOException {
// while (available() == 0 && validData_ != -1) {
// fill();
// }
// }
//
// private void fill() throws IOException {
// bufferIndex_ = 0;
// validData_ = source_.read(buffer_);
// }
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionBootstrap.java
// public interface IOIOConnectionBootstrap {
// public void getFactories(Collection<IOIOConnectionFactory> result);
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionFactory.java
// public interface IOIOConnectionFactory {
// /**
// * A unique name of the connection type. Typically a fully-qualified
// * name of the connection class.
// */
// public String getType();
//
// /**
// * Extra information on the connection. This is specific to the
// * connection type. For example, for a Bluetooth connection, this is an
// * array containing the name and the Bluetooth address of the remote
// * IOIO.
// */
// public Object getExtra();
//
// public IOIOConnection createConnection();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/util/android/ContextWrapperDependent.java
// public interface ContextWrapperDependent {
// public void onCreate(ContextWrapper wrapper);
//
// public void onDestroy();
//
// public void open();
//
// public void reopen();
//
// public void close();
// }
// Path: IOIO/iOIOLibAndroidDevice/src/main/java/ioio/lib/android/device/DeviceConnectionBootstrap.java
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.HashMap;
import ioio.lib.api.IOIOConnection;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.impl.FixedReadBufferedInputStream;
import ioio.lib.spi.IOIOConnectionBootstrap;
import ioio.lib.spi.IOIOConnectionFactory;
import ioio.lib.spi.NoRuntimeSupportException;
import ioio.lib.util.android.ContextWrapperDependent;
private UsbManager usbManager_;
private UsbDevice device_;
private UsbDeviceConnection connection_;
private UsbInterface controlInterface_;
private UsbInterface dataInterface_;
private UsbEndpoint epIn_;
private UsbEndpoint epOut_;
private InputStream inputStream_;
private OutputStream outputStream_;
public DeviceConnectionBootstrap() {
if (Build.VERSION.SDK_INT < 12) {
throw new NoRuntimeSupportException("OTG is not supported on this device.");
}
}
@Override
public void getFactories(Collection<IOIOConnectionFactory> result) {
result.add(new IOIOConnectionFactory() {
@Override
public String getType() {
return DeviceConnectionBootstrap.class.getCanonicalName();
}
@Override
public Object getExtra() {
return null;
}
@Override | public IOIOConnection createConnection() { |
flyver/Flyver-SDK | IOIO/iOIOLibAndroidDevice/src/main/java/ioio/lib/android/device/DeviceConnectionBootstrap.java | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIOConnection.java
// public interface IOIOConnection {
// void waitForConnect() throws ConnectionLostException;
//
// void disconnect();
//
// InputStream getInputStream() throws ConnectionLostException;
//
// OutputStream getOutputStream() throws ConnectionLostException;
//
// /**
// * Can this connection be closed. Normally the answer would be "true", but
// * some weird connections cannot be closed and need the higher layer to do
// * a "soft close" instead.
// *
// * @return true This connection can be closed.
// */
// boolean canClose();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/FixedReadBufferedInputStream.java
// public class FixedReadBufferedInputStream extends InputStream {
// private int bufferIndex_ = 0;
// private int validData_ = 0;
// private final byte[] buffer_;
// private final InputStream source_;
//
// public FixedReadBufferedInputStream(InputStream source, int size) {
// buffer_ = new byte[size];
// source_ = source;
// }
//
// @Override
// public int available() throws IOException {
// return validData_ - bufferIndex_;
// }
//
// @Override
// public void close() throws IOException {
// source_.close();
// }
//
// @Override
// public int read(byte[] buffer, int offset, int length) throws IOException {
// fillIfEmpty();
// if (validData_ == -1) {
// return -1;
// }
// length = Math.min(length, validData_ - bufferIndex_);
// System.arraycopy(buffer_, bufferIndex_, buffer, offset, length);
// bufferIndex_ += length;
// return length;
// }
//
// @Override
// public int read(byte[] buffer) throws IOException {
// return read(buffer, 0, buffer.length);
// }
//
// @Override
// public int read() throws IOException {
// fillIfEmpty();
// if (validData_ == -1) {
// return -1;
// }
// return buffer_[bufferIndex_++] & 0xFF;
// }
//
// @Override
// public long skip(long byteCount) throws IOException {
// long skipped = 0;
// while (byteCount > 0) {
// fillIfEmpty();
// if (validData_ == -1) {
// return skipped;
// }
// int count = (int) Math.min(available(), byteCount);
// byteCount -= count;
// bufferIndex_ += count;
// skipped += count;
// }
// return skipped;
// }
//
// private void fillIfEmpty() throws IOException {
// while (available() == 0 && validData_ != -1) {
// fill();
// }
// }
//
// private void fill() throws IOException {
// bufferIndex_ = 0;
// validData_ = source_.read(buffer_);
// }
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionBootstrap.java
// public interface IOIOConnectionBootstrap {
// public void getFactories(Collection<IOIOConnectionFactory> result);
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionFactory.java
// public interface IOIOConnectionFactory {
// /**
// * A unique name of the connection type. Typically a fully-qualified
// * name of the connection class.
// */
// public String getType();
//
// /**
// * Extra information on the connection. This is specific to the
// * connection type. For example, for a Bluetooth connection, this is an
// * array containing the name and the Bluetooth address of the remote
// * IOIO.
// */
// public Object getExtra();
//
// public IOIOConnection createConnection();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/util/android/ContextWrapperDependent.java
// public interface ContextWrapperDependent {
// public void onCreate(ContextWrapper wrapper);
//
// public void onDestroy();
//
// public void open();
//
// public void reopen();
//
// public void close();
// }
| import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.HashMap;
import ioio.lib.api.IOIOConnection;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.impl.FixedReadBufferedInputStream;
import ioio.lib.spi.IOIOConnectionBootstrap;
import ioio.lib.spi.IOIOConnectionFactory;
import ioio.lib.spi.NoRuntimeSupportException;
import ioio.lib.util.android.ContextWrapperDependent; | epIn_ = ep0;
epOut_ = ep1;
} else if (ep0.getDirection() == UsbConstants.USB_DIR_OUT
&& ep1.getDirection() == UsbConstants.USB_DIR_IN) {
epIn_ = ep1;
epOut_ = ep0;
} else {
Log.e(TAG, "Endpoints directions are not compatible.");
return false;
}
return true;
}
/**
* Claim interfaces and create the I/O streams.
* <p/>
* If the call succeeds it returns {@code true} and the caller is responsible to call
* {@link #closeStreams()}. If the call fails, it returns (@code false} and no clean-up is
* required from the caller.
*
* @precondition The device is attached, permission has been granted to connect to it, and the
* descriptor has been processed.
*/
private boolean openStreams() {
// Claim interfaces.
if (connection_.claimInterface(controlInterface_, true)) {
if (connection_.claimInterface(dataInterface_, true)) {
// Raise DTR.
if (setDTR(true)) {
// Create streams. Buffer them with a reasonable buffer sizes. | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIOConnection.java
// public interface IOIOConnection {
// void waitForConnect() throws ConnectionLostException;
//
// void disconnect();
//
// InputStream getInputStream() throws ConnectionLostException;
//
// OutputStream getOutputStream() throws ConnectionLostException;
//
// /**
// * Can this connection be closed. Normally the answer would be "true", but
// * some weird connections cannot be closed and need the higher layer to do
// * a "soft close" instead.
// *
// * @return true This connection can be closed.
// */
// boolean canClose();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/FixedReadBufferedInputStream.java
// public class FixedReadBufferedInputStream extends InputStream {
// private int bufferIndex_ = 0;
// private int validData_ = 0;
// private final byte[] buffer_;
// private final InputStream source_;
//
// public FixedReadBufferedInputStream(InputStream source, int size) {
// buffer_ = new byte[size];
// source_ = source;
// }
//
// @Override
// public int available() throws IOException {
// return validData_ - bufferIndex_;
// }
//
// @Override
// public void close() throws IOException {
// source_.close();
// }
//
// @Override
// public int read(byte[] buffer, int offset, int length) throws IOException {
// fillIfEmpty();
// if (validData_ == -1) {
// return -1;
// }
// length = Math.min(length, validData_ - bufferIndex_);
// System.arraycopy(buffer_, bufferIndex_, buffer, offset, length);
// bufferIndex_ += length;
// return length;
// }
//
// @Override
// public int read(byte[] buffer) throws IOException {
// return read(buffer, 0, buffer.length);
// }
//
// @Override
// public int read() throws IOException {
// fillIfEmpty();
// if (validData_ == -1) {
// return -1;
// }
// return buffer_[bufferIndex_++] & 0xFF;
// }
//
// @Override
// public long skip(long byteCount) throws IOException {
// long skipped = 0;
// while (byteCount > 0) {
// fillIfEmpty();
// if (validData_ == -1) {
// return skipped;
// }
// int count = (int) Math.min(available(), byteCount);
// byteCount -= count;
// bufferIndex_ += count;
// skipped += count;
// }
// return skipped;
// }
//
// private void fillIfEmpty() throws IOException {
// while (available() == 0 && validData_ != -1) {
// fill();
// }
// }
//
// private void fill() throws IOException {
// bufferIndex_ = 0;
// validData_ = source_.read(buffer_);
// }
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionBootstrap.java
// public interface IOIOConnectionBootstrap {
// public void getFactories(Collection<IOIOConnectionFactory> result);
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionFactory.java
// public interface IOIOConnectionFactory {
// /**
// * A unique name of the connection type. Typically a fully-qualified
// * name of the connection class.
// */
// public String getType();
//
// /**
// * Extra information on the connection. This is specific to the
// * connection type. For example, for a Bluetooth connection, this is an
// * array containing the name and the Bluetooth address of the remote
// * IOIO.
// */
// public Object getExtra();
//
// public IOIOConnection createConnection();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/util/android/ContextWrapperDependent.java
// public interface ContextWrapperDependent {
// public void onCreate(ContextWrapper wrapper);
//
// public void onDestroy();
//
// public void open();
//
// public void reopen();
//
// public void close();
// }
// Path: IOIO/iOIOLibAndroidDevice/src/main/java/ioio/lib/android/device/DeviceConnectionBootstrap.java
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.HashMap;
import ioio.lib.api.IOIOConnection;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.impl.FixedReadBufferedInputStream;
import ioio.lib.spi.IOIOConnectionBootstrap;
import ioio.lib.spi.IOIOConnectionFactory;
import ioio.lib.spi.NoRuntimeSupportException;
import ioio.lib.util.android.ContextWrapperDependent;
epIn_ = ep0;
epOut_ = ep1;
} else if (ep0.getDirection() == UsbConstants.USB_DIR_OUT
&& ep1.getDirection() == UsbConstants.USB_DIR_IN) {
epIn_ = ep1;
epOut_ = ep0;
} else {
Log.e(TAG, "Endpoints directions are not compatible.");
return false;
}
return true;
}
/**
* Claim interfaces and create the I/O streams.
* <p/>
* If the call succeeds it returns {@code true} and the caller is responsible to call
* {@link #closeStreams()}. If the call fails, it returns (@code false} and no clean-up is
* required from the caller.
*
* @precondition The device is attached, permission has been granted to connect to it, and the
* descriptor has been processed.
*/
private boolean openStreams() {
// Claim interfaces.
if (connection_.claimInterface(controlInterface_, true)) {
if (connection_.claimInterface(dataInterface_, true)) {
// Raise DTR.
if (setDTR(true)) {
// Create streams. Buffer them with a reasonable buffer sizes. | inputStream_ = new FixedReadBufferedInputStream(new Streams.DeviceInputStream( |
flyver/Flyver-SDK | IOIO/iOIOLibAndroid/src/main/java/ioio/lib/util/IOIOConnectionManager.java | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionFactory.java
// public interface IOIOConnectionFactory {
// /**
// * A unique name of the connection type. Typically a fully-qualified
// * name of the connection class.
// */
// public String getType();
//
// /**
// * Extra information on the connection. This is specific to the
// * connection type. For example, for a Bluetooth connection, this is an
// * array containing the name and the Bluetooth address of the remote
// * IOIO.
// */
// public Object getExtra();
//
// public IOIOConnection createConnection();
// }
| import java.util.LinkedList;
import ioio.lib.spi.IOIOConnectionFactory;
import java.util.Collection; | /*
* Copyright 2012 Ytai Ben-Tsvi. All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARSHAN POURSOHI OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied.
*/
package ioio.lib.util;
/**
* Manages IOIO threads per connection.
* <p/>
* This class will take care of creating a thread for each possible IOIO
* connection, and cleaning up these threads. Client is responsible for providing the
* actual threads, by implementing the IOIOConnectionThreadProvider interface.
* <p/>
* Basic usage is:
* <ul>
* <li>Create a IOIOConnectionManager instance, pass a IOIOConnectionThreadProvider.</li>
* <li>Call {@link #start()}. This will invoke {@link IOIOConnectionThreadProvider#createThreadFromFactory(IOIOConnectionFactory)}
* for every possible connection (more precisely, for every IOIOConnectionFactory). Return null if you do not wish to create a thread for a certain connection type.</li>
* <li>When done, call {@link #stop()}. This will call {@link Thread#abort()} for each running thread and then join them.</li>
* </ul>
*/
public class IOIOConnectionManager {
private final IOIOConnectionThreadProvider provider_;
public IOIOConnectionManager(IOIOConnectionThreadProvider provider) {
provider_ = provider;
}
public abstract static class Thread extends java.lang.Thread {
public abstract void abort();
}
public void start() {
createAllThreads();
startAllThreads();
}
public void stop() {
abortAllThreads();
try {
joinAllThreads();
} catch (InterruptedException e) {
}
}
public interface IOIOConnectionThreadProvider { | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/spi/IOIOConnectionFactory.java
// public interface IOIOConnectionFactory {
// /**
// * A unique name of the connection type. Typically a fully-qualified
// * name of the connection class.
// */
// public String getType();
//
// /**
// * Extra information on the connection. This is specific to the
// * connection type. For example, for a Bluetooth connection, this is an
// * array containing the name and the Bluetooth address of the remote
// * IOIO.
// */
// public Object getExtra();
//
// public IOIOConnection createConnection();
// }
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/util/IOIOConnectionManager.java
import java.util.LinkedList;
import ioio.lib.spi.IOIOConnectionFactory;
import java.util.Collection;
/*
* Copyright 2012 Ytai Ben-Tsvi. All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARSHAN POURSOHI OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied.
*/
package ioio.lib.util;
/**
* Manages IOIO threads per connection.
* <p/>
* This class will take care of creating a thread for each possible IOIO
* connection, and cleaning up these threads. Client is responsible for providing the
* actual threads, by implementing the IOIOConnectionThreadProvider interface.
* <p/>
* Basic usage is:
* <ul>
* <li>Create a IOIOConnectionManager instance, pass a IOIOConnectionThreadProvider.</li>
* <li>Call {@link #start()}. This will invoke {@link IOIOConnectionThreadProvider#createThreadFromFactory(IOIOConnectionFactory)}
* for every possible connection (more precisely, for every IOIOConnectionFactory). Return null if you do not wish to create a thread for a certain connection type.</li>
* <li>When done, call {@link #stop()}. This will call {@link Thread#abort()} for each running thread and then join them.</li>
* </ul>
*/
public class IOIOConnectionManager {
private final IOIOConnectionThreadProvider provider_;
public IOIOConnectionManager(IOIOConnectionThreadProvider provider) {
provider_ = provider;
}
public abstract static class Thread extends java.lang.Thread {
public abstract void abort();
}
public void start() {
createAllThreads();
startAllThreads();
}
public void stop() {
abortAllThreads();
try {
joinAllThreads();
} catch (InterruptedException e) {
}
}
public interface IOIOConnectionThreadProvider { | public Thread createThreadFromFactory(IOIOConnectionFactory factory); |
flyver/Flyver-SDK | Client/src/main/java/co/flyver/Client/Client.java | // Path: IPC/src/main/java/co/flyver/IPC/JSONUtils.java
// public class JSONUtils {
// private static Gson mGson = new Gson();
// private static final String TAG = "JSONIPC";
//
// /**
// * Validates if a string is a valid JSON object
// *
// * @param json - String to be validated
// * @return - boolean, true if the string is a valid JSON object
// */
// public static boolean validateJson(String json) {
// try {
// mGson.fromJson(json, Object.class);
// return true;
// } catch (JsonSyntaxException e) {
// return false;
// }
// }
//
//
// private static <T> T fromJSON(String json, Type type) {
// if (validateJson(json)) {
// return mGson.fromJson(json, type);
// } else {
// return null;
// }
// }
//
// /**
// * Creates a generic type object from JSON
// * @param json - String describing the JSON object
// * @param type - Type derived from TypeToken, created with Google GSON
// * @param <T> - Generic object
// * @return
// */
// public static <T> T deserialize(String json, Type type) {
// T jsonObj;
// jsonObj = co.flyver.IPC.JSONUtils.fromJSON(json, type);
// if (jsonObj == null) {
// throw new NullPointerException("JSON is null");
// }
// return jsonObj;
// }
//
// /**
// * Creates a JSON from a generic object
// * @param t - Object to be serialzied into JSON
// * @param type - Type derived from TypeToken, created with Google GSON
// * @param <T> - Generic object
// * @return
// */
// public static <T> String serialize(T t, Type type) {
// return mGson.toJson(t, type);
// }
//
// public static <T> String serialize(T t) {
// return mGson.toJson(t);
// }
//
// }
| import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import co.flyver.IPC.JSONUtils; | private static boolean mConnected = false;
private IBinder mBinder = new LocalBinder();
public Client() {
super("Client");
}
public static void setServerIP(String sServerIP) {
Client.sServerIP = sServerIP;
}
public static void setLastToast(Toast sLastToast) {
Client.sLastToast = sLastToast;
}
public static void setMainContext(Context sMainContext) {
Client.sMainContext = sMainContext;
}
public static void registerCallback(String key, ClientCallback callback) {
if (callback != null) {
sCallbacks.put(key, callback);
}
}
public static void registerConnectionHooks(ConnectionHooks hooks) {
sConnectionHooks = hooks;
}
public static void sendMsg(String json) { | // Path: IPC/src/main/java/co/flyver/IPC/JSONUtils.java
// public class JSONUtils {
// private static Gson mGson = new Gson();
// private static final String TAG = "JSONIPC";
//
// /**
// * Validates if a string is a valid JSON object
// *
// * @param json - String to be validated
// * @return - boolean, true if the string is a valid JSON object
// */
// public static boolean validateJson(String json) {
// try {
// mGson.fromJson(json, Object.class);
// return true;
// } catch (JsonSyntaxException e) {
// return false;
// }
// }
//
//
// private static <T> T fromJSON(String json, Type type) {
// if (validateJson(json)) {
// return mGson.fromJson(json, type);
// } else {
// return null;
// }
// }
//
// /**
// * Creates a generic type object from JSON
// * @param json - String describing the JSON object
// * @param type - Type derived from TypeToken, created with Google GSON
// * @param <T> - Generic object
// * @return
// */
// public static <T> T deserialize(String json, Type type) {
// T jsonObj;
// jsonObj = co.flyver.IPC.JSONUtils.fromJSON(json, type);
// if (jsonObj == null) {
// throw new NullPointerException("JSON is null");
// }
// return jsonObj;
// }
//
// /**
// * Creates a JSON from a generic object
// * @param t - Object to be serialzied into JSON
// * @param type - Type derived from TypeToken, created with Google GSON
// * @param <T> - Generic object
// * @return
// */
// public static <T> String serialize(T t, Type type) {
// return mGson.toJson(t, type);
// }
//
// public static <T> String serialize(T t) {
// return mGson.toJson(t);
// }
//
// }
// Path: Client/src/main/java/co/flyver/Client/Client.java
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import co.flyver.IPC.JSONUtils;
private static boolean mConnected = false;
private IBinder mBinder = new LocalBinder();
public Client() {
super("Client");
}
public static void setServerIP(String sServerIP) {
Client.sServerIP = sServerIP;
}
public static void setLastToast(Toast sLastToast) {
Client.sLastToast = sLastToast;
}
public static void setMainContext(Context sMainContext) {
Client.sMainContext = sMainContext;
}
public static void registerCallback(String key, ClientCallback callback) {
if (callback != null) {
sCallbacks.put(key, callback);
}
}
public static void registerConnectionHooks(ConnectionHooks hooks) {
sConnectionHooks = hooks;
}
public static void sendMsg(String json) { | if(!JSONUtils.validateJson(json)) { |
flyver/Flyver-SDK | IOIO/iOIOLibBT/src/main/java/ioio/lib/android/bluetooth/BluetoothIOIOConnection.java | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIOConnection.java
// public interface IOIOConnection {
// void waitForConnect() throws ConnectionLostException;
//
// void disconnect();
//
// InputStream getInputStream() throws ConnectionLostException;
//
// OutputStream getOutputStream() throws ConnectionLostException;
//
// /**
// * Can this connection be closed. Normally the answer would be "true", but
// * some weird connections cannot be closed and need the higher layer to do
// * a "soft close" instead.
// *
// * @return true This connection can be closed.
// */
// boolean canClose();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/FixedReadBufferedInputStream.java
// public class FixedReadBufferedInputStream extends InputStream {
// private int bufferIndex_ = 0;
// private int validData_ = 0;
// private final byte[] buffer_;
// private final InputStream source_;
//
// public FixedReadBufferedInputStream(InputStream source, int size) {
// buffer_ = new byte[size];
// source_ = source;
// }
//
// @Override
// public int available() throws IOException {
// return validData_ - bufferIndex_;
// }
//
// @Override
// public void close() throws IOException {
// source_.close();
// }
//
// @Override
// public int read(byte[] buffer, int offset, int length) throws IOException {
// fillIfEmpty();
// if (validData_ == -1) {
// return -1;
// }
// length = Math.min(length, validData_ - bufferIndex_);
// System.arraycopy(buffer_, bufferIndex_, buffer, offset, length);
// bufferIndex_ += length;
// return length;
// }
//
// @Override
// public int read(byte[] buffer) throws IOException {
// return read(buffer, 0, buffer.length);
// }
//
// @Override
// public int read() throws IOException {
// fillIfEmpty();
// if (validData_ == -1) {
// return -1;
// }
// return buffer_[bufferIndex_++] & 0xFF;
// }
//
// @Override
// public long skip(long byteCount) throws IOException {
// long skipped = 0;
// while (byteCount > 0) {
// fillIfEmpty();
// if (validData_ == -1) {
// return skipped;
// }
// int count = (int) Math.min(available(), byteCount);
// byteCount -= count;
// bufferIndex_ += count;
// skipped += count;
// }
// return skipped;
// }
//
// private void fillIfEmpty() throws IOException {
// while (available() == 0 && validData_ != -1) {
// fill();
// }
// }
//
// private void fill() throws IOException {
// bufferIndex_ = 0;
// validData_ = source_.read(buffer_);
// }
// }
| import android.os.Build;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import ioio.lib.api.IOIOConnection;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.impl.FixedReadBufferedInputStream;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket; | if (disconnect_) {
throw new ConnectionLostException();
}
try {
socket_ = createSocket(device_);
} catch (IOException e) {
throw new ConnectionLostException(e);
}
}
// keep trying to connect as long as we're not aborting
while (true) {
try {
Log.v(TAG, "Attempting to connect to Bluetooth device: " + name_);
inputStream_ = socket_.getInputStream();
outputStream_ = socket_.getOutputStream();
socket_.connect();
Log.v(TAG, "Established connection to device " + name_
+ " address: " + address_);
break; // if we got here, we're connected
} catch (Exception e) {
if (disconnect_) {
throw new ConnectionLostException(e);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
}
}
}
// Success! Wrap the streams with a properly sized buffers. | // Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/api/IOIOConnection.java
// public interface IOIOConnection {
// void waitForConnect() throws ConnectionLostException;
//
// void disconnect();
//
// InputStream getInputStream() throws ConnectionLostException;
//
// OutputStream getOutputStream() throws ConnectionLostException;
//
// /**
// * Can this connection be closed. Normally the answer would be "true", but
// * some weird connections cannot be closed and need the higher layer to do
// * a "soft close" instead.
// *
// * @return true This connection can be closed.
// */
// boolean canClose();
// }
//
// Path: IOIO/iOIOLibAndroid/src/main/java/ioio/lib/impl/FixedReadBufferedInputStream.java
// public class FixedReadBufferedInputStream extends InputStream {
// private int bufferIndex_ = 0;
// private int validData_ = 0;
// private final byte[] buffer_;
// private final InputStream source_;
//
// public FixedReadBufferedInputStream(InputStream source, int size) {
// buffer_ = new byte[size];
// source_ = source;
// }
//
// @Override
// public int available() throws IOException {
// return validData_ - bufferIndex_;
// }
//
// @Override
// public void close() throws IOException {
// source_.close();
// }
//
// @Override
// public int read(byte[] buffer, int offset, int length) throws IOException {
// fillIfEmpty();
// if (validData_ == -1) {
// return -1;
// }
// length = Math.min(length, validData_ - bufferIndex_);
// System.arraycopy(buffer_, bufferIndex_, buffer, offset, length);
// bufferIndex_ += length;
// return length;
// }
//
// @Override
// public int read(byte[] buffer) throws IOException {
// return read(buffer, 0, buffer.length);
// }
//
// @Override
// public int read() throws IOException {
// fillIfEmpty();
// if (validData_ == -1) {
// return -1;
// }
// return buffer_[bufferIndex_++] & 0xFF;
// }
//
// @Override
// public long skip(long byteCount) throws IOException {
// long skipped = 0;
// while (byteCount > 0) {
// fillIfEmpty();
// if (validData_ == -1) {
// return skipped;
// }
// int count = (int) Math.min(available(), byteCount);
// byteCount -= count;
// bufferIndex_ += count;
// skipped += count;
// }
// return skipped;
// }
//
// private void fillIfEmpty() throws IOException {
// while (available() == 0 && validData_ != -1) {
// fill();
// }
// }
//
// private void fill() throws IOException {
// bufferIndex_ = 0;
// validData_ = source_.read(buffer_);
// }
// }
// Path: IOIO/iOIOLibBT/src/main/java/ioio/lib/android/bluetooth/BluetoothIOIOConnection.java
import android.os.Build;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import ioio.lib.api.IOIOConnection;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.impl.FixedReadBufferedInputStream;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
if (disconnect_) {
throw new ConnectionLostException();
}
try {
socket_ = createSocket(device_);
} catch (IOException e) {
throw new ConnectionLostException(e);
}
}
// keep trying to connect as long as we're not aborting
while (true) {
try {
Log.v(TAG, "Attempting to connect to Bluetooth device: " + name_);
inputStream_ = socket_.getInputStream();
outputStream_ = socket_.getOutputStream();
socket_.connect();
Log.v(TAG, "Established connection to device " + name_
+ " address: " + address_);
break; // if we got here, we're connected
} catch (Exception e) {
if (disconnect_) {
throw new ConnectionLostException(e);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
}
}
}
// Success! Wrap the streams with a properly sized buffers. | inputStream_ = new FixedReadBufferedInputStream(inputStream_, 64); |
flyver/Flyver-SDK | utils/src/main/java/co/flyver/utils/flyverMQ/FlyverMQ.java | // Path: utils/src/main/java/co/flyver/utils/CapacityQueue.java
// public class CapacityQueue<E> extends LinkedBlockingQueue<E> {
// private int limit;
//
// public CapacityQueue(int limit) {
// this.limit = limit;
// }
//
// @Override
// public boolean add(E e) {
// boolean added = super.add(e);
// while(added && size() > limit) {
// super.remove();
// }
// return added;
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/NoSuchTopicException.java
// public class NoSuchTopicException extends Exception {
// public NoSuchTopicException(String detailMessage) {
// super(detailMessage);
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/ProducerAlreadyRegisteredException.java
// public class ProducerAlreadyRegisteredException extends Exception {
// public ProducerAlreadyRegisteredException(String detailMessage) {
// super(detailMessage);
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/interfaces/FlyverMQCallback.java
// public interface FlyverMQCallback {
// /**
// * Called every time a producer is registered to the message queue
// * Used to notify components for new producers that they might be interested in
// * @param topic String, the topic of the messages sent by the producer
// */
// public void producerRegistered(String topic);
//
// /**
// * Called every time a producer is unregistered or replaced from the system
// * Used to notify components that a producer has disappeared, so they should unregister
// * for it's messages
// * @param topic String, the topic of the messages of the unregistered producer
// */
// public void producerUnregistered(String topic);
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/interfaces/FlyverMQConsumer.java
// public interface FlyverMQConsumer {
// /**
// * Data recieved callback for the consumer.
// * Called when a message with the associated topic
// * for the consumer is received in the message queue
// * @param message SimpleMQMessage data container
// */
// public void dataReceived(FlyverMQMessage message);
//
// /**
// * Consumer unregister hook
// * Called when the consumer is removed from the message queue
// */
// public void unregistered();
//
// //TODO: clarify if consumers need onPause/onResume functionallity
// public void paused();
// public void resumed();
// }
| import android.util.Log;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import co.flyver.utils.CapacityQueue;
import co.flyver.utils.flyverMQ.exceptions.NoSuchTopicException;
import co.flyver.utils.flyverMQ.exceptions.ProducerAlreadyRegisteredException;
import co.flyver.utils.flyverMQ.interfaces.FlyverMQCallback;
import co.flyver.utils.flyverMQ.interfaces.FlyverMQConsumer; | package co.flyver.utils.flyverMQ;
/**
* Created by Petar Petrov on 12/9/14.
*/
public class FlyverMQ {
/**
* Helper class
* Used to easily associate producers with an internal queue for their events
* Constructor can be passed only producer, and the queue will be dynamic LinkedList,
* or producer and size, and the queue will be CapacityQueue, which automatically removes
* the oldest objects, when it's capacity is reached
*/
private class SimpleMQProducerWrapper {
private FlyverMQProducer producer;
public FlyverMQProducer getProducer() {
return producer;
}
public BlockingQueue<FlyverMQMessage> getQueue() {
return queue;
}
private BlockingQueue<FlyverMQMessage> queue;
SimpleMQProducerWrapper(FlyverMQProducer producer) {
this.producer = producer;
queue = new LinkedBlockingQueue<>();
}
SimpleMQProducerWrapper(FlyverMQProducer producer, int size) {
this.producer = producer; | // Path: utils/src/main/java/co/flyver/utils/CapacityQueue.java
// public class CapacityQueue<E> extends LinkedBlockingQueue<E> {
// private int limit;
//
// public CapacityQueue(int limit) {
// this.limit = limit;
// }
//
// @Override
// public boolean add(E e) {
// boolean added = super.add(e);
// while(added && size() > limit) {
// super.remove();
// }
// return added;
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/NoSuchTopicException.java
// public class NoSuchTopicException extends Exception {
// public NoSuchTopicException(String detailMessage) {
// super(detailMessage);
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/ProducerAlreadyRegisteredException.java
// public class ProducerAlreadyRegisteredException extends Exception {
// public ProducerAlreadyRegisteredException(String detailMessage) {
// super(detailMessage);
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/interfaces/FlyverMQCallback.java
// public interface FlyverMQCallback {
// /**
// * Called every time a producer is registered to the message queue
// * Used to notify components for new producers that they might be interested in
// * @param topic String, the topic of the messages sent by the producer
// */
// public void producerRegistered(String topic);
//
// /**
// * Called every time a producer is unregistered or replaced from the system
// * Used to notify components that a producer has disappeared, so they should unregister
// * for it's messages
// * @param topic String, the topic of the messages of the unregistered producer
// */
// public void producerUnregistered(String topic);
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/interfaces/FlyverMQConsumer.java
// public interface FlyverMQConsumer {
// /**
// * Data recieved callback for the consumer.
// * Called when a message with the associated topic
// * for the consumer is received in the message queue
// * @param message SimpleMQMessage data container
// */
// public void dataReceived(FlyverMQMessage message);
//
// /**
// * Consumer unregister hook
// * Called when the consumer is removed from the message queue
// */
// public void unregistered();
//
// //TODO: clarify if consumers need onPause/onResume functionallity
// public void paused();
// public void resumed();
// }
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/FlyverMQ.java
import android.util.Log;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import co.flyver.utils.CapacityQueue;
import co.flyver.utils.flyverMQ.exceptions.NoSuchTopicException;
import co.flyver.utils.flyverMQ.exceptions.ProducerAlreadyRegisteredException;
import co.flyver.utils.flyverMQ.interfaces.FlyverMQCallback;
import co.flyver.utils.flyverMQ.interfaces.FlyverMQConsumer;
package co.flyver.utils.flyverMQ;
/**
* Created by Petar Petrov on 12/9/14.
*/
public class FlyverMQ {
/**
* Helper class
* Used to easily associate producers with an internal queue for their events
* Constructor can be passed only producer, and the queue will be dynamic LinkedList,
* or producer and size, and the queue will be CapacityQueue, which automatically removes
* the oldest objects, when it's capacity is reached
*/
private class SimpleMQProducerWrapper {
private FlyverMQProducer producer;
public FlyverMQProducer getProducer() {
return producer;
}
public BlockingQueue<FlyverMQMessage> getQueue() {
return queue;
}
private BlockingQueue<FlyverMQMessage> queue;
SimpleMQProducerWrapper(FlyverMQProducer producer) {
this.producer = producer;
queue = new LinkedBlockingQueue<>();
}
SimpleMQProducerWrapper(FlyverMQProducer producer, int size) {
this.producer = producer; | queue = new CapacityQueue<>(size); |
flyver/Flyver-SDK | utils/src/main/java/co/flyver/utils/flyverMQ/FlyverMQ.java | // Path: utils/src/main/java/co/flyver/utils/CapacityQueue.java
// public class CapacityQueue<E> extends LinkedBlockingQueue<E> {
// private int limit;
//
// public CapacityQueue(int limit) {
// this.limit = limit;
// }
//
// @Override
// public boolean add(E e) {
// boolean added = super.add(e);
// while(added && size() > limit) {
// super.remove();
// }
// return added;
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/NoSuchTopicException.java
// public class NoSuchTopicException extends Exception {
// public NoSuchTopicException(String detailMessage) {
// super(detailMessage);
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/ProducerAlreadyRegisteredException.java
// public class ProducerAlreadyRegisteredException extends Exception {
// public ProducerAlreadyRegisteredException(String detailMessage) {
// super(detailMessage);
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/interfaces/FlyverMQCallback.java
// public interface FlyverMQCallback {
// /**
// * Called every time a producer is registered to the message queue
// * Used to notify components for new producers that they might be interested in
// * @param topic String, the topic of the messages sent by the producer
// */
// public void producerRegistered(String topic);
//
// /**
// * Called every time a producer is unregistered or replaced from the system
// * Used to notify components that a producer has disappeared, so they should unregister
// * for it's messages
// * @param topic String, the topic of the messages of the unregistered producer
// */
// public void producerUnregistered(String topic);
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/interfaces/FlyverMQConsumer.java
// public interface FlyverMQConsumer {
// /**
// * Data recieved callback for the consumer.
// * Called when a message with the associated topic
// * for the consumer is received in the message queue
// * @param message SimpleMQMessage data container
// */
// public void dataReceived(FlyverMQMessage message);
//
// /**
// * Consumer unregister hook
// * Called when the consumer is removed from the message queue
// */
// public void unregistered();
//
// //TODO: clarify if consumers need onPause/onResume functionallity
// public void paused();
// public void resumed();
// }
| import android.util.Log;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import co.flyver.utils.CapacityQueue;
import co.flyver.utils.flyverMQ.exceptions.NoSuchTopicException;
import co.flyver.utils.flyverMQ.exceptions.ProducerAlreadyRegisteredException;
import co.flyver.utils.flyverMQ.interfaces.FlyverMQCallback;
import co.flyver.utils.flyverMQ.interfaces.FlyverMQConsumer; | package co.flyver.utils.flyverMQ;
/**
* Created by Petar Petrov on 12/9/14.
*/
public class FlyverMQ {
/**
* Helper class
* Used to easily associate producers with an internal queue for their events
* Constructor can be passed only producer, and the queue will be dynamic LinkedList,
* or producer and size, and the queue will be CapacityQueue, which automatically removes
* the oldest objects, when it's capacity is reached
*/
private class SimpleMQProducerWrapper {
private FlyverMQProducer producer;
public FlyverMQProducer getProducer() {
return producer;
}
public BlockingQueue<FlyverMQMessage> getQueue() {
return queue;
}
private BlockingQueue<FlyverMQMessage> queue;
SimpleMQProducerWrapper(FlyverMQProducer producer) {
this.producer = producer;
queue = new LinkedBlockingQueue<>();
}
SimpleMQProducerWrapper(FlyverMQProducer producer, int size) {
this.producer = producer;
queue = new CapacityQueue<>(size);
}
//prevent instantiating with an empty constructor
private SimpleMQProducerWrapper() {
}
public int getEventCount() {
return queue.size();
}
}
/**
* Helper class wrapping around asynchronous consumers
* Used to associate them with an internal semaphore
* as to avoid concurency issues
*/
protected class SimpleMQAsyncConsumerWrapper {
private Semaphore semaphore = new Semaphore(1); | // Path: utils/src/main/java/co/flyver/utils/CapacityQueue.java
// public class CapacityQueue<E> extends LinkedBlockingQueue<E> {
// private int limit;
//
// public CapacityQueue(int limit) {
// this.limit = limit;
// }
//
// @Override
// public boolean add(E e) {
// boolean added = super.add(e);
// while(added && size() > limit) {
// super.remove();
// }
// return added;
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/NoSuchTopicException.java
// public class NoSuchTopicException extends Exception {
// public NoSuchTopicException(String detailMessage) {
// super(detailMessage);
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/ProducerAlreadyRegisteredException.java
// public class ProducerAlreadyRegisteredException extends Exception {
// public ProducerAlreadyRegisteredException(String detailMessage) {
// super(detailMessage);
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/interfaces/FlyverMQCallback.java
// public interface FlyverMQCallback {
// /**
// * Called every time a producer is registered to the message queue
// * Used to notify components for new producers that they might be interested in
// * @param topic String, the topic of the messages sent by the producer
// */
// public void producerRegistered(String topic);
//
// /**
// * Called every time a producer is unregistered or replaced from the system
// * Used to notify components that a producer has disappeared, so they should unregister
// * for it's messages
// * @param topic String, the topic of the messages of the unregistered producer
// */
// public void producerUnregistered(String topic);
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/interfaces/FlyverMQConsumer.java
// public interface FlyverMQConsumer {
// /**
// * Data recieved callback for the consumer.
// * Called when a message with the associated topic
// * for the consumer is received in the message queue
// * @param message SimpleMQMessage data container
// */
// public void dataReceived(FlyverMQMessage message);
//
// /**
// * Consumer unregister hook
// * Called when the consumer is removed from the message queue
// */
// public void unregistered();
//
// //TODO: clarify if consumers need onPause/onResume functionallity
// public void paused();
// public void resumed();
// }
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/FlyverMQ.java
import android.util.Log;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import co.flyver.utils.CapacityQueue;
import co.flyver.utils.flyverMQ.exceptions.NoSuchTopicException;
import co.flyver.utils.flyverMQ.exceptions.ProducerAlreadyRegisteredException;
import co.flyver.utils.flyverMQ.interfaces.FlyverMQCallback;
import co.flyver.utils.flyverMQ.interfaces.FlyverMQConsumer;
package co.flyver.utils.flyverMQ;
/**
* Created by Petar Petrov on 12/9/14.
*/
public class FlyverMQ {
/**
* Helper class
* Used to easily associate producers with an internal queue for their events
* Constructor can be passed only producer, and the queue will be dynamic LinkedList,
* or producer and size, and the queue will be CapacityQueue, which automatically removes
* the oldest objects, when it's capacity is reached
*/
private class SimpleMQProducerWrapper {
private FlyverMQProducer producer;
public FlyverMQProducer getProducer() {
return producer;
}
public BlockingQueue<FlyverMQMessage> getQueue() {
return queue;
}
private BlockingQueue<FlyverMQMessage> queue;
SimpleMQProducerWrapper(FlyverMQProducer producer) {
this.producer = producer;
queue = new LinkedBlockingQueue<>();
}
SimpleMQProducerWrapper(FlyverMQProducer producer, int size) {
this.producer = producer;
queue = new CapacityQueue<>(size);
}
//prevent instantiating with an empty constructor
private SimpleMQProducerWrapper() {
}
public int getEventCount() {
return queue.size();
}
}
/**
* Helper class wrapping around asynchronous consumers
* Used to associate them with an internal semaphore
* as to avoid concurency issues
*/
protected class SimpleMQAsyncConsumerWrapper {
private Semaphore semaphore = new Semaphore(1); | private FlyverMQConsumer consumer; |
flyver/Flyver-SDK | utils/src/main/java/co/flyver/utils/flyverMQ/FlyverMQ.java | // Path: utils/src/main/java/co/flyver/utils/CapacityQueue.java
// public class CapacityQueue<E> extends LinkedBlockingQueue<E> {
// private int limit;
//
// public CapacityQueue(int limit) {
// this.limit = limit;
// }
//
// @Override
// public boolean add(E e) {
// boolean added = super.add(e);
// while(added && size() > limit) {
// super.remove();
// }
// return added;
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/NoSuchTopicException.java
// public class NoSuchTopicException extends Exception {
// public NoSuchTopicException(String detailMessage) {
// super(detailMessage);
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/ProducerAlreadyRegisteredException.java
// public class ProducerAlreadyRegisteredException extends Exception {
// public ProducerAlreadyRegisteredException(String detailMessage) {
// super(detailMessage);
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/interfaces/FlyverMQCallback.java
// public interface FlyverMQCallback {
// /**
// * Called every time a producer is registered to the message queue
// * Used to notify components for new producers that they might be interested in
// * @param topic String, the topic of the messages sent by the producer
// */
// public void producerRegistered(String topic);
//
// /**
// * Called every time a producer is unregistered or replaced from the system
// * Used to notify components that a producer has disappeared, so they should unregister
// * for it's messages
// * @param topic String, the topic of the messages of the unregistered producer
// */
// public void producerUnregistered(String topic);
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/interfaces/FlyverMQConsumer.java
// public interface FlyverMQConsumer {
// /**
// * Data recieved callback for the consumer.
// * Called when a message with the associated topic
// * for the consumer is received in the message queue
// * @param message SimpleMQMessage data container
// */
// public void dataReceived(FlyverMQMessage message);
//
// /**
// * Consumer unregister hook
// * Called when the consumer is removed from the message queue
// */
// public void unregistered();
//
// //TODO: clarify if consumers need onPause/onResume functionallity
// public void paused();
// public void resumed();
// }
| import android.util.Log;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import co.flyver.utils.CapacityQueue;
import co.flyver.utils.flyverMQ.exceptions.NoSuchTopicException;
import co.flyver.utils.flyverMQ.exceptions.ProducerAlreadyRegisteredException;
import co.flyver.utils.flyverMQ.interfaces.FlyverMQCallback;
import co.flyver.utils.flyverMQ.interfaces.FlyverMQConsumer; | }
sendMsg(wrapper, message);
}
}
}
}
private void sendMsg(final SimpleMQAsyncConsumerWrapper wrapper, final FlyverMQMessage msg) {
executorService.execute(new Runnable() {
@Override
public void run() {
try {
wrapper.getSemaphore().acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
wrapper.getConsumer().dataReceived(msg);
wrapper.getSemaphore().release();
}
});
}
}
private static FlyverMQ instance;
private final String TAG = "SimpleMQ";
private final String REGISTEREDMSG = "Producer already registered: ";
private final String NOTOPICMSG = "No such topic exists : ";
protected Map<String, LinkedList<FlyverMQProducer>> producers = new HashMap<>();
protected Map<String, LinkedList<SimpleMQAsyncConsumerWrapper>> asyncConsumers = new HashMap<>();
protected Map<String, LinkedList<FlyverMQConsumer>> rtConsumers = new HashMap<>(); | // Path: utils/src/main/java/co/flyver/utils/CapacityQueue.java
// public class CapacityQueue<E> extends LinkedBlockingQueue<E> {
// private int limit;
//
// public CapacityQueue(int limit) {
// this.limit = limit;
// }
//
// @Override
// public boolean add(E e) {
// boolean added = super.add(e);
// while(added && size() > limit) {
// super.remove();
// }
// return added;
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/NoSuchTopicException.java
// public class NoSuchTopicException extends Exception {
// public NoSuchTopicException(String detailMessage) {
// super(detailMessage);
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/ProducerAlreadyRegisteredException.java
// public class ProducerAlreadyRegisteredException extends Exception {
// public ProducerAlreadyRegisteredException(String detailMessage) {
// super(detailMessage);
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/interfaces/FlyverMQCallback.java
// public interface FlyverMQCallback {
// /**
// * Called every time a producer is registered to the message queue
// * Used to notify components for new producers that they might be interested in
// * @param topic String, the topic of the messages sent by the producer
// */
// public void producerRegistered(String topic);
//
// /**
// * Called every time a producer is unregistered or replaced from the system
// * Used to notify components that a producer has disappeared, so they should unregister
// * for it's messages
// * @param topic String, the topic of the messages of the unregistered producer
// */
// public void producerUnregistered(String topic);
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/interfaces/FlyverMQConsumer.java
// public interface FlyverMQConsumer {
// /**
// * Data recieved callback for the consumer.
// * Called when a message with the associated topic
// * for the consumer is received in the message queue
// * @param message SimpleMQMessage data container
// */
// public void dataReceived(FlyverMQMessage message);
//
// /**
// * Consumer unregister hook
// * Called when the consumer is removed from the message queue
// */
// public void unregistered();
//
// //TODO: clarify if consumers need onPause/onResume functionallity
// public void paused();
// public void resumed();
// }
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/FlyverMQ.java
import android.util.Log;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import co.flyver.utils.CapacityQueue;
import co.flyver.utils.flyverMQ.exceptions.NoSuchTopicException;
import co.flyver.utils.flyverMQ.exceptions.ProducerAlreadyRegisteredException;
import co.flyver.utils.flyverMQ.interfaces.FlyverMQCallback;
import co.flyver.utils.flyverMQ.interfaces.FlyverMQConsumer;
}
sendMsg(wrapper, message);
}
}
}
}
private void sendMsg(final SimpleMQAsyncConsumerWrapper wrapper, final FlyverMQMessage msg) {
executorService.execute(new Runnable() {
@Override
public void run() {
try {
wrapper.getSemaphore().acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
wrapper.getConsumer().dataReceived(msg);
wrapper.getSemaphore().release();
}
});
}
}
private static FlyverMQ instance;
private final String TAG = "SimpleMQ";
private final String REGISTEREDMSG = "Producer already registered: ";
private final String NOTOPICMSG = "No such topic exists : ";
protected Map<String, LinkedList<FlyverMQProducer>> producers = new HashMap<>();
protected Map<String, LinkedList<SimpleMQAsyncConsumerWrapper>> asyncConsumers = new HashMap<>();
protected Map<String, LinkedList<FlyverMQConsumer>> rtConsumers = new HashMap<>(); | protected LinkedList<FlyverMQCallback> registeredComponentCallbacks = new LinkedList<>(); |
flyver/Flyver-SDK | utils/src/main/java/co/flyver/utils/flyverMQ/FlyverMQ.java | // Path: utils/src/main/java/co/flyver/utils/CapacityQueue.java
// public class CapacityQueue<E> extends LinkedBlockingQueue<E> {
// private int limit;
//
// public CapacityQueue(int limit) {
// this.limit = limit;
// }
//
// @Override
// public boolean add(E e) {
// boolean added = super.add(e);
// while(added && size() > limit) {
// super.remove();
// }
// return added;
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/NoSuchTopicException.java
// public class NoSuchTopicException extends Exception {
// public NoSuchTopicException(String detailMessage) {
// super(detailMessage);
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/ProducerAlreadyRegisteredException.java
// public class ProducerAlreadyRegisteredException extends Exception {
// public ProducerAlreadyRegisteredException(String detailMessage) {
// super(detailMessage);
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/interfaces/FlyverMQCallback.java
// public interface FlyverMQCallback {
// /**
// * Called every time a producer is registered to the message queue
// * Used to notify components for new producers that they might be interested in
// * @param topic String, the topic of the messages sent by the producer
// */
// public void producerRegistered(String topic);
//
// /**
// * Called every time a producer is unregistered or replaced from the system
// * Used to notify components that a producer has disappeared, so they should unregister
// * for it's messages
// * @param topic String, the topic of the messages of the unregistered producer
// */
// public void producerUnregistered(String topic);
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/interfaces/FlyverMQConsumer.java
// public interface FlyverMQConsumer {
// /**
// * Data recieved callback for the consumer.
// * Called when a message with the associated topic
// * for the consumer is received in the message queue
// * @param message SimpleMQMessage data container
// */
// public void dataReceived(FlyverMQMessage message);
//
// /**
// * Consumer unregister hook
// * Called when the consumer is removed from the message queue
// */
// public void unregistered();
//
// //TODO: clarify if consumers need onPause/onResume functionallity
// public void paused();
// public void resumed();
// }
| import android.util.Log;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import co.flyver.utils.CapacityQueue;
import co.flyver.utils.flyverMQ.exceptions.NoSuchTopicException;
import co.flyver.utils.flyverMQ.exceptions.ProducerAlreadyRegisteredException;
import co.flyver.utils.flyverMQ.interfaces.FlyverMQCallback;
import co.flyver.utils.flyverMQ.interfaces.FlyverMQConsumer; | Thread worker = new Thread(new SimpleMQWorker());
worker.setDaemon(true);
worker.start();
return this;
}
/**
* Register an object, implementing the SimpleMQCallback interface
* which is used to monitor changes in the producers registration and deregistration
* from the components
*
* @param callback SimpleMQCallback, implementing onRegistered and onUnregistered methods
* @return this, as to allow chaining
*/
public FlyverMQ producersStatusCallback(FlyverMQCallback callback) {
registeredComponentCallbacks.add(callback);
return this;
}
/**
* Register an Object implementing the SimpleMQProducer interface to a topic
* All messages by this producer are enqueued for later processing
*
* @param producer Class implementing SimpleMQProducer interface
* @param topic String defining the topic of the producer
* @param removeExisting Set to true to remove previously registered producer for the topic
* @return this, to allow chaining
* @throws ProducerAlreadyRegisteredException - Throws the already registered exception if a producer is already registered,
* and the removeExisting flag is set to false
*/ | // Path: utils/src/main/java/co/flyver/utils/CapacityQueue.java
// public class CapacityQueue<E> extends LinkedBlockingQueue<E> {
// private int limit;
//
// public CapacityQueue(int limit) {
// this.limit = limit;
// }
//
// @Override
// public boolean add(E e) {
// boolean added = super.add(e);
// while(added && size() > limit) {
// super.remove();
// }
// return added;
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/NoSuchTopicException.java
// public class NoSuchTopicException extends Exception {
// public NoSuchTopicException(String detailMessage) {
// super(detailMessage);
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/ProducerAlreadyRegisteredException.java
// public class ProducerAlreadyRegisteredException extends Exception {
// public ProducerAlreadyRegisteredException(String detailMessage) {
// super(detailMessage);
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/interfaces/FlyverMQCallback.java
// public interface FlyverMQCallback {
// /**
// * Called every time a producer is registered to the message queue
// * Used to notify components for new producers that they might be interested in
// * @param topic String, the topic of the messages sent by the producer
// */
// public void producerRegistered(String topic);
//
// /**
// * Called every time a producer is unregistered or replaced from the system
// * Used to notify components that a producer has disappeared, so they should unregister
// * for it's messages
// * @param topic String, the topic of the messages of the unregistered producer
// */
// public void producerUnregistered(String topic);
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/interfaces/FlyverMQConsumer.java
// public interface FlyverMQConsumer {
// /**
// * Data recieved callback for the consumer.
// * Called when a message with the associated topic
// * for the consumer is received in the message queue
// * @param message SimpleMQMessage data container
// */
// public void dataReceived(FlyverMQMessage message);
//
// /**
// * Consumer unregister hook
// * Called when the consumer is removed from the message queue
// */
// public void unregistered();
//
// //TODO: clarify if consumers need onPause/onResume functionallity
// public void paused();
// public void resumed();
// }
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/FlyverMQ.java
import android.util.Log;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import co.flyver.utils.CapacityQueue;
import co.flyver.utils.flyverMQ.exceptions.NoSuchTopicException;
import co.flyver.utils.flyverMQ.exceptions.ProducerAlreadyRegisteredException;
import co.flyver.utils.flyverMQ.interfaces.FlyverMQCallback;
import co.flyver.utils.flyverMQ.interfaces.FlyverMQConsumer;
Thread worker = new Thread(new SimpleMQWorker());
worker.setDaemon(true);
worker.start();
return this;
}
/**
* Register an object, implementing the SimpleMQCallback interface
* which is used to monitor changes in the producers registration and deregistration
* from the components
*
* @param callback SimpleMQCallback, implementing onRegistered and onUnregistered methods
* @return this, as to allow chaining
*/
public FlyverMQ producersStatusCallback(FlyverMQCallback callback) {
registeredComponentCallbacks.add(callback);
return this;
}
/**
* Register an Object implementing the SimpleMQProducer interface to a topic
* All messages by this producer are enqueued for later processing
*
* @param producer Class implementing SimpleMQProducer interface
* @param topic String defining the topic of the producer
* @param removeExisting Set to true to remove previously registered producer for the topic
* @return this, to allow chaining
* @throws ProducerAlreadyRegisteredException - Throws the already registered exception if a producer is already registered,
* and the removeExisting flag is set to false
*/ | public FlyverMQ registerProducer(FlyverMQProducer producer, String topic, boolean removeExisting) throws ProducerAlreadyRegisteredException { |
flyver/Flyver-SDK | utils/src/main/java/co/flyver/utils/flyverMQ/FlyverMQ.java | // Path: utils/src/main/java/co/flyver/utils/CapacityQueue.java
// public class CapacityQueue<E> extends LinkedBlockingQueue<E> {
// private int limit;
//
// public CapacityQueue(int limit) {
// this.limit = limit;
// }
//
// @Override
// public boolean add(E e) {
// boolean added = super.add(e);
// while(added && size() > limit) {
// super.remove();
// }
// return added;
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/NoSuchTopicException.java
// public class NoSuchTopicException extends Exception {
// public NoSuchTopicException(String detailMessage) {
// super(detailMessage);
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/ProducerAlreadyRegisteredException.java
// public class ProducerAlreadyRegisteredException extends Exception {
// public ProducerAlreadyRegisteredException(String detailMessage) {
// super(detailMessage);
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/interfaces/FlyverMQCallback.java
// public interface FlyverMQCallback {
// /**
// * Called every time a producer is registered to the message queue
// * Used to notify components for new producers that they might be interested in
// * @param topic String, the topic of the messages sent by the producer
// */
// public void producerRegistered(String topic);
//
// /**
// * Called every time a producer is unregistered or replaced from the system
// * Used to notify components that a producer has disappeared, so they should unregister
// * for it's messages
// * @param topic String, the topic of the messages of the unregistered producer
// */
// public void producerUnregistered(String topic);
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/interfaces/FlyverMQConsumer.java
// public interface FlyverMQConsumer {
// /**
// * Data recieved callback for the consumer.
// * Called when a message with the associated topic
// * for the consumer is received in the message queue
// * @param message SimpleMQMessage data container
// */
// public void dataReceived(FlyverMQMessage message);
//
// /**
// * Consumer unregister hook
// * Called when the consumer is removed from the message queue
// */
// public void unregistered();
//
// //TODO: clarify if consumers need onPause/onResume functionallity
// public void paused();
// public void resumed();
// }
| import android.util.Log;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import co.flyver.utils.CapacityQueue;
import co.flyver.utils.flyverMQ.exceptions.NoSuchTopicException;
import co.flyver.utils.flyverMQ.exceptions.ProducerAlreadyRegisteredException;
import co.flyver.utils.flyverMQ.interfaces.FlyverMQCallback;
import co.flyver.utils.flyverMQ.interfaces.FlyverMQConsumer; | * Register an object, implementing the SimpleMQCallback interface
* which is used to monitor changes in the producers registration and deregistration
* from the components
*
* @param callback SimpleMQCallback, implementing onRegistered and onUnregistered methods
* @return this, as to allow chaining
*/
public FlyverMQ producersStatusCallback(FlyverMQCallback callback) {
registeredComponentCallbacks.add(callback);
return this;
}
/**
* Register an Object implementing the SimpleMQProducer interface to a topic
* All messages by this producer are enqueued for later processing
*
* @param producer Class implementing SimpleMQProducer interface
* @param topic String defining the topic of the producer
* @param removeExisting Set to true to remove previously registered producer for the topic
* @return this, to allow chaining
* @throws ProducerAlreadyRegisteredException - Throws the already registered exception if a producer is already registered,
* and the removeExisting flag is set to false
*/
public FlyverMQ registerProducer(FlyverMQProducer producer, String topic, boolean removeExisting) throws ProducerAlreadyRegisteredException {
if (topicExists(topic) && !removeExisting) {
throw new ProducerAlreadyRegisteredException(REGISTEREDMSG.concat(topic));
}
if (topicExists(topic)) {
try {
unregisterProducer(topic); | // Path: utils/src/main/java/co/flyver/utils/CapacityQueue.java
// public class CapacityQueue<E> extends LinkedBlockingQueue<E> {
// private int limit;
//
// public CapacityQueue(int limit) {
// this.limit = limit;
// }
//
// @Override
// public boolean add(E e) {
// boolean added = super.add(e);
// while(added && size() > limit) {
// super.remove();
// }
// return added;
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/NoSuchTopicException.java
// public class NoSuchTopicException extends Exception {
// public NoSuchTopicException(String detailMessage) {
// super(detailMessage);
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/exceptions/ProducerAlreadyRegisteredException.java
// public class ProducerAlreadyRegisteredException extends Exception {
// public ProducerAlreadyRegisteredException(String detailMessage) {
// super(detailMessage);
// }
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/interfaces/FlyverMQCallback.java
// public interface FlyverMQCallback {
// /**
// * Called every time a producer is registered to the message queue
// * Used to notify components for new producers that they might be interested in
// * @param topic String, the topic of the messages sent by the producer
// */
// public void producerRegistered(String topic);
//
// /**
// * Called every time a producer is unregistered or replaced from the system
// * Used to notify components that a producer has disappeared, so they should unregister
// * for it's messages
// * @param topic String, the topic of the messages of the unregistered producer
// */
// public void producerUnregistered(String topic);
// }
//
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/interfaces/FlyverMQConsumer.java
// public interface FlyverMQConsumer {
// /**
// * Data recieved callback for the consumer.
// * Called when a message with the associated topic
// * for the consumer is received in the message queue
// * @param message SimpleMQMessage data container
// */
// public void dataReceived(FlyverMQMessage message);
//
// /**
// * Consumer unregister hook
// * Called when the consumer is removed from the message queue
// */
// public void unregistered();
//
// //TODO: clarify if consumers need onPause/onResume functionallity
// public void paused();
// public void resumed();
// }
// Path: utils/src/main/java/co/flyver/utils/flyverMQ/FlyverMQ.java
import android.util.Log;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import co.flyver.utils.CapacityQueue;
import co.flyver.utils.flyverMQ.exceptions.NoSuchTopicException;
import co.flyver.utils.flyverMQ.exceptions.ProducerAlreadyRegisteredException;
import co.flyver.utils.flyverMQ.interfaces.FlyverMQCallback;
import co.flyver.utils.flyverMQ.interfaces.FlyverMQConsumer;
* Register an object, implementing the SimpleMQCallback interface
* which is used to monitor changes in the producers registration and deregistration
* from the components
*
* @param callback SimpleMQCallback, implementing onRegistered and onUnregistered methods
* @return this, as to allow chaining
*/
public FlyverMQ producersStatusCallback(FlyverMQCallback callback) {
registeredComponentCallbacks.add(callback);
return this;
}
/**
* Register an Object implementing the SimpleMQProducer interface to a topic
* All messages by this producer are enqueued for later processing
*
* @param producer Class implementing SimpleMQProducer interface
* @param topic String defining the topic of the producer
* @param removeExisting Set to true to remove previously registered producer for the topic
* @return this, to allow chaining
* @throws ProducerAlreadyRegisteredException - Throws the already registered exception if a producer is already registered,
* and the removeExisting flag is set to false
*/
public FlyverMQ registerProducer(FlyverMQProducer producer, String topic, boolean removeExisting) throws ProducerAlreadyRegisteredException {
if (topicExists(topic) && !removeExisting) {
throw new ProducerAlreadyRegisteredException(REGISTEREDMSG.concat(topic));
}
if (topicExists(topic)) {
try {
unregisterProducer(topic); | } catch (NoSuchTopicException e) { |
yarolegovich/MaterialPreferences | library/src/main/java/com/yarolegovich/mp/AbsMaterialCheckablePreference.java | // Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
| import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Checkable;
import com.yarolegovich.mp.io.StorageModule; |
public AbsMaterialCheckablePreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public AbsMaterialCheckablePreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onViewCreated() {
checkableWidget = (Checkable) findViewById(R.id.mp_checkable);
boolean isChecked = getValue();
checkableWidget.setChecked(isChecked);
addPreferenceClickListener(this);
}
@Override
public void onClick(View v) {
boolean newValue = !getValue();
checkableWidget.setChecked(newValue);
setValue(newValue);
}
@Override
public Boolean getValue() {
return storageModule.getBoolean(key, Boolean.parseBoolean(defaultValue));
}
@Override | // Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
// Path: library/src/main/java/com/yarolegovich/mp/AbsMaterialCheckablePreference.java
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Checkable;
import com.yarolegovich.mp.io.StorageModule;
public AbsMaterialCheckablePreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public AbsMaterialCheckablePreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onViewCreated() {
checkableWidget = (Checkable) findViewById(R.id.mp_checkable);
boolean isChecked = getValue();
checkableWidget.setChecked(isChecked);
addPreferenceClickListener(this);
}
@Override
public void onClick(View v) {
boolean newValue = !getValue();
checkableWidget.setChecked(newValue);
setValue(newValue);
}
@Override
public Boolean getValue() {
return storageModule.getBoolean(key, Boolean.parseBoolean(defaultValue));
}
@Override | public void setStorageModule(StorageModule storageModule) { |
yarolegovich/MaterialPreferences | library/src/main/java/com/yarolegovich/mp/view/ColorView.java | // Path: library/src/main/java/com/yarolegovich/mp/util/Utils.java
// public class Utils {
//
// private Utils() {}
//
// public static int dpToPixels(Context context, int dp) {
// Resources resources = context.getResources();
// DisplayMetrics metrics = resources.getDisplayMetrics();
// return Math.round(dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
// }
//
// public static int clickableBackground(Context context) {
// TypedValue outValue = new TypedValue();
// context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
// return outValue.resourceId;
// }
// }
| import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Build;
import androidx.annotation.ColorInt;
import android.util.AttributeSet;
import android.view.View;
import com.yarolegovich.mp.R;
import com.yarolegovich.mp.util.Utils; | int borderWidth = 0;
if (attrs != null) {
TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.ColorView);
try {
shapeType = ta.getInt(R.styleable.ColorView_mp_cv_shape, SHAPE_CIRCLE);
shapeColor = ta.getColor(R.styleable.ColorView_mp_cv_color, Color.WHITE);
borderColor = ta.getColor(R.styleable.ColorView_mp_cv_border_color, Color.BLACK);
borderWidth = ta.getDimensionPixelSize(R.styleable.ColorView_mp_cv_border_width, 0);
} finally {
ta.recycle();
}
}
currentShape = shapeType == SHAPE_CIRCLE ? new CircleShape() : new SquareShape();
shapePaint = new Paint();
shapePaint.setStyle(Paint.Style.FILL);
shapePaint.setColor(shapeColor);
borderPaint = new Paint();
borderPaint.setStyle(Paint.Style.STROKE);
borderPaint.setAntiAlias(true);
borderPaint.setStrokeWidth(borderWidth);
borderPaint.setColor(borderColor);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec); | // Path: library/src/main/java/com/yarolegovich/mp/util/Utils.java
// public class Utils {
//
// private Utils() {}
//
// public static int dpToPixels(Context context, int dp) {
// Resources resources = context.getResources();
// DisplayMetrics metrics = resources.getDisplayMetrics();
// return Math.round(dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
// }
//
// public static int clickableBackground(Context context) {
// TypedValue outValue = new TypedValue();
// context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
// return outValue.resourceId;
// }
// }
// Path: library/src/main/java/com/yarolegovich/mp/view/ColorView.java
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Build;
import androidx.annotation.ColorInt;
import android.util.AttributeSet;
import android.view.View;
import com.yarolegovich.mp.R;
import com.yarolegovich.mp.util.Utils;
int borderWidth = 0;
if (attrs != null) {
TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.ColorView);
try {
shapeType = ta.getInt(R.styleable.ColorView_mp_cv_shape, SHAPE_CIRCLE);
shapeColor = ta.getColor(R.styleable.ColorView_mp_cv_color, Color.WHITE);
borderColor = ta.getColor(R.styleable.ColorView_mp_cv_border_color, Color.BLACK);
borderWidth = ta.getDimensionPixelSize(R.styleable.ColorView_mp_cv_border_width, 0);
} finally {
ta.recycle();
}
}
currentShape = shapeType == SHAPE_CIRCLE ? new CircleShape() : new SquareShape();
shapePaint = new Paint();
shapePaint.setStyle(Paint.Style.FILL);
shapePaint.setColor(shapeColor);
borderPaint = new Paint();
borderPaint.setStyle(Paint.Style.STROKE);
borderPaint.setAntiAlias(true);
borderPaint.setStrokeWidth(borderWidth);
borderPaint.setColor(borderColor);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec); | int padding = Utils.dpToPixels(getContext(), PADDING_DP); |
yarolegovich/MaterialPreferences | library/src/main/java/com/yarolegovich/mp/MaterialPreferenceScreen.java | // Path: library/src/main/java/com/yarolegovich/mp/io/UserInputModule.java
// public interface UserInputModule {
//
// void showEditTextInput(
// String key,
// CharSequence title,
// CharSequence defaultValue,
// Listener<String> listener);
//
// void showSingleChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// int selected,
// Listener<String> listener);
//
// void showMultiChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// boolean[] defaultSelection,
// Listener<Set<String>> listener);
//
// void showColorSelectionInput(
// String key,
// CharSequence title,
// int defaultColor,
// Listener<Integer> color);
//
// interface Factory {
// UserInputModule create(Context context);
// }
//
// interface Listener<T> {
// void onInput(T value);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
| import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import com.yarolegovich.mp.io.UserInputModule;
import com.yarolegovich.mp.io.StorageModule;
import java.util.Collection;
import java.util.List; | package com.yarolegovich.mp;
/**
* Created by yarolegovich on 01.05.2016.
*/
public class MaterialPreferenceScreen extends ScrollView {
private LinearLayout container;
| // Path: library/src/main/java/com/yarolegovich/mp/io/UserInputModule.java
// public interface UserInputModule {
//
// void showEditTextInput(
// String key,
// CharSequence title,
// CharSequence defaultValue,
// Listener<String> listener);
//
// void showSingleChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// int selected,
// Listener<String> listener);
//
// void showMultiChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// boolean[] defaultSelection,
// Listener<Set<String>> listener);
//
// void showColorSelectionInput(
// String key,
// CharSequence title,
// int defaultColor,
// Listener<Integer> color);
//
// interface Factory {
// UserInputModule create(Context context);
// }
//
// interface Listener<T> {
// void onInput(T value);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
// Path: library/src/main/java/com/yarolegovich/mp/MaterialPreferenceScreen.java
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import com.yarolegovich.mp.io.UserInputModule;
import com.yarolegovich.mp.io.StorageModule;
import java.util.Collection;
import java.util.List;
package com.yarolegovich.mp;
/**
* Created by yarolegovich on 01.05.2016.
*/
public class MaterialPreferenceScreen extends ScrollView {
private LinearLayout container;
| private UserInputModule userInputModule; |
yarolegovich/MaterialPreferences | library/src/main/java/com/yarolegovich/mp/MaterialPreferenceScreen.java | // Path: library/src/main/java/com/yarolegovich/mp/io/UserInputModule.java
// public interface UserInputModule {
//
// void showEditTextInput(
// String key,
// CharSequence title,
// CharSequence defaultValue,
// Listener<String> listener);
//
// void showSingleChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// int selected,
// Listener<String> listener);
//
// void showMultiChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// boolean[] defaultSelection,
// Listener<Set<String>> listener);
//
// void showColorSelectionInput(
// String key,
// CharSequence title,
// int defaultColor,
// Listener<Integer> color);
//
// interface Factory {
// UserInputModule create(Context context);
// }
//
// interface Listener<T> {
// void onInput(T value);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
| import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import com.yarolegovich.mp.io.UserInputModule;
import com.yarolegovich.mp.io.StorageModule;
import java.util.Collection;
import java.util.List; | package com.yarolegovich.mp;
/**
* Created by yarolegovich on 01.05.2016.
*/
public class MaterialPreferenceScreen extends ScrollView {
private LinearLayout container;
private UserInputModule userInputModule; | // Path: library/src/main/java/com/yarolegovich/mp/io/UserInputModule.java
// public interface UserInputModule {
//
// void showEditTextInput(
// String key,
// CharSequence title,
// CharSequence defaultValue,
// Listener<String> listener);
//
// void showSingleChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// int selected,
// Listener<String> listener);
//
// void showMultiChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// boolean[] defaultSelection,
// Listener<Set<String>> listener);
//
// void showColorSelectionInput(
// String key,
// CharSequence title,
// int defaultColor,
// Listener<Integer> color);
//
// interface Factory {
// UserInputModule create(Context context);
// }
//
// interface Listener<T> {
// void onInput(T value);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
// Path: library/src/main/java/com/yarolegovich/mp/MaterialPreferenceScreen.java
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import com.yarolegovich.mp.io.UserInputModule;
import com.yarolegovich.mp.io.StorageModule;
import java.util.Collection;
import java.util.List;
package com.yarolegovich.mp;
/**
* Created by yarolegovich on 01.05.2016.
*/
public class MaterialPreferenceScreen extends ScrollView {
private LinearLayout container;
private UserInputModule userInputModule; | private StorageModule storageModule; |
yarolegovich/MaterialPreferences | library/src/main/java/com/yarolegovich/mp/AbsMaterialPreference.java | // Path: library/src/main/java/com/yarolegovich/mp/io/MaterialPreferences.java
// public class MaterialPreferences {
//
// private static final MaterialPreferences instance = new MaterialPreferences();
//
// public static MaterialPreferences instance() {
// return instance;
// }
//
// public static UserInputModule getUserInputModule(Context context) {
// return instance.userInputModuleFactory.create(context);
// }
//
// public static StorageModule getStorageModule(Context context) {
// return instance.storageModuleFactory.create(context);
// }
//
// private UserInputModule.Factory userInputModuleFactory;
// private StorageModule.Factory storageModuleFactory;
//
// private MaterialPreferences() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
// public MaterialPreferences setUserInputModule(UserInputModule.Factory factory) {
// userInputModuleFactory = factory;
// return this;
// }
//
// public MaterialPreferences setStorageModule(StorageModule.Factory factory) {
// storageModuleFactory = factory;
// return this;
// }
//
// public void setDefault() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
//
// private static class StandardUserInputFactory implements UserInputModule.Factory {
// @Override
// public UserInputModule create(Context context) {
// return new StandardUserInputModule(context);
// }
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/UserInputModule.java
// public interface UserInputModule {
//
// void showEditTextInput(
// String key,
// CharSequence title,
// CharSequence defaultValue,
// Listener<String> listener);
//
// void showSingleChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// int selected,
// Listener<String> listener);
//
// void showMultiChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// boolean[] defaultSelection,
// Listener<Set<String>> listener);
//
// void showColorSelectionInput(
// String key,
// CharSequence title,
// int defaultColor,
// Listener<Integer> color);
//
// interface Factory {
// UserInputModule create(Context context);
// }
//
// interface Listener<T> {
// void onInput(T value);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/util/CompositeClickListener.java
// public class CompositeClickListener implements View.OnClickListener {
//
// private List<View.OnClickListener> listeners;
//
// public CompositeClickListener() {
// listeners = new ArrayList<>();
// }
//
// @Override
// public void onClick(View v) {
// for (int i = listeners.size() - 1; i >= 0; i--) {
// listeners.get(i).onClick(v);
// }
// }
//
// public int addListener(View.OnClickListener listener) {
// listeners.add(listener);
// return listeners.size() - 1;
// }
//
// public void removeListener(View.OnClickListener listener) {
// listeners.remove(listener);
// }
//
// public void removeListener(int index) {
// listeners.remove(index);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/util/Utils.java
// public class Utils {
//
// private Utils() {}
//
// public static int dpToPixels(Context context, int dp) {
// Resources resources = context.getResources();
// DisplayMetrics metrics = resources.getDisplayMetrics();
// return Math.round(dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
// }
//
// public static int clickableBackground(Context context) {
// TypedValue outValue = new TypedValue();
// context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
// return outValue.resourceId;
// }
// }
| import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.core.content.ContextCompat;
import com.yarolegovich.mp.io.MaterialPreferences;
import com.yarolegovich.mp.io.StorageModule;
import com.yarolegovich.mp.io.UserInputModule;
import com.yarolegovich.mp.util.CompositeClickListener;
import com.yarolegovich.mp.util.Utils; | package com.yarolegovich.mp;
/**
* Created by yarolegovich on 01.05.2016.
*/
@SuppressWarnings("ResourceType")
abstract class AbsMaterialPreference<T> extends LinearLayout {
private TextView title;
private TextView summary;
private ImageView icon;
protected String defaultValue;
protected String key;
| // Path: library/src/main/java/com/yarolegovich/mp/io/MaterialPreferences.java
// public class MaterialPreferences {
//
// private static final MaterialPreferences instance = new MaterialPreferences();
//
// public static MaterialPreferences instance() {
// return instance;
// }
//
// public static UserInputModule getUserInputModule(Context context) {
// return instance.userInputModuleFactory.create(context);
// }
//
// public static StorageModule getStorageModule(Context context) {
// return instance.storageModuleFactory.create(context);
// }
//
// private UserInputModule.Factory userInputModuleFactory;
// private StorageModule.Factory storageModuleFactory;
//
// private MaterialPreferences() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
// public MaterialPreferences setUserInputModule(UserInputModule.Factory factory) {
// userInputModuleFactory = factory;
// return this;
// }
//
// public MaterialPreferences setStorageModule(StorageModule.Factory factory) {
// storageModuleFactory = factory;
// return this;
// }
//
// public void setDefault() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
//
// private static class StandardUserInputFactory implements UserInputModule.Factory {
// @Override
// public UserInputModule create(Context context) {
// return new StandardUserInputModule(context);
// }
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/UserInputModule.java
// public interface UserInputModule {
//
// void showEditTextInput(
// String key,
// CharSequence title,
// CharSequence defaultValue,
// Listener<String> listener);
//
// void showSingleChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// int selected,
// Listener<String> listener);
//
// void showMultiChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// boolean[] defaultSelection,
// Listener<Set<String>> listener);
//
// void showColorSelectionInput(
// String key,
// CharSequence title,
// int defaultColor,
// Listener<Integer> color);
//
// interface Factory {
// UserInputModule create(Context context);
// }
//
// interface Listener<T> {
// void onInput(T value);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/util/CompositeClickListener.java
// public class CompositeClickListener implements View.OnClickListener {
//
// private List<View.OnClickListener> listeners;
//
// public CompositeClickListener() {
// listeners = new ArrayList<>();
// }
//
// @Override
// public void onClick(View v) {
// for (int i = listeners.size() - 1; i >= 0; i--) {
// listeners.get(i).onClick(v);
// }
// }
//
// public int addListener(View.OnClickListener listener) {
// listeners.add(listener);
// return listeners.size() - 1;
// }
//
// public void removeListener(View.OnClickListener listener) {
// listeners.remove(listener);
// }
//
// public void removeListener(int index) {
// listeners.remove(index);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/util/Utils.java
// public class Utils {
//
// private Utils() {}
//
// public static int dpToPixels(Context context, int dp) {
// Resources resources = context.getResources();
// DisplayMetrics metrics = resources.getDisplayMetrics();
// return Math.round(dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
// }
//
// public static int clickableBackground(Context context) {
// TypedValue outValue = new TypedValue();
// context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
// return outValue.resourceId;
// }
// }
// Path: library/src/main/java/com/yarolegovich/mp/AbsMaterialPreference.java
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.core.content.ContextCompat;
import com.yarolegovich.mp.io.MaterialPreferences;
import com.yarolegovich.mp.io.StorageModule;
import com.yarolegovich.mp.io.UserInputModule;
import com.yarolegovich.mp.util.CompositeClickListener;
import com.yarolegovich.mp.util.Utils;
package com.yarolegovich.mp;
/**
* Created by yarolegovich on 01.05.2016.
*/
@SuppressWarnings("ResourceType")
abstract class AbsMaterialPreference<T> extends LinearLayout {
private TextView title;
private TextView summary;
private ImageView icon;
protected String defaultValue;
protected String key;
| protected UserInputModule userInputModule; |
yarolegovich/MaterialPreferences | library/src/main/java/com/yarolegovich/mp/AbsMaterialPreference.java | // Path: library/src/main/java/com/yarolegovich/mp/io/MaterialPreferences.java
// public class MaterialPreferences {
//
// private static final MaterialPreferences instance = new MaterialPreferences();
//
// public static MaterialPreferences instance() {
// return instance;
// }
//
// public static UserInputModule getUserInputModule(Context context) {
// return instance.userInputModuleFactory.create(context);
// }
//
// public static StorageModule getStorageModule(Context context) {
// return instance.storageModuleFactory.create(context);
// }
//
// private UserInputModule.Factory userInputModuleFactory;
// private StorageModule.Factory storageModuleFactory;
//
// private MaterialPreferences() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
// public MaterialPreferences setUserInputModule(UserInputModule.Factory factory) {
// userInputModuleFactory = factory;
// return this;
// }
//
// public MaterialPreferences setStorageModule(StorageModule.Factory factory) {
// storageModuleFactory = factory;
// return this;
// }
//
// public void setDefault() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
//
// private static class StandardUserInputFactory implements UserInputModule.Factory {
// @Override
// public UserInputModule create(Context context) {
// return new StandardUserInputModule(context);
// }
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/UserInputModule.java
// public interface UserInputModule {
//
// void showEditTextInput(
// String key,
// CharSequence title,
// CharSequence defaultValue,
// Listener<String> listener);
//
// void showSingleChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// int selected,
// Listener<String> listener);
//
// void showMultiChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// boolean[] defaultSelection,
// Listener<Set<String>> listener);
//
// void showColorSelectionInput(
// String key,
// CharSequence title,
// int defaultColor,
// Listener<Integer> color);
//
// interface Factory {
// UserInputModule create(Context context);
// }
//
// interface Listener<T> {
// void onInput(T value);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/util/CompositeClickListener.java
// public class CompositeClickListener implements View.OnClickListener {
//
// private List<View.OnClickListener> listeners;
//
// public CompositeClickListener() {
// listeners = new ArrayList<>();
// }
//
// @Override
// public void onClick(View v) {
// for (int i = listeners.size() - 1; i >= 0; i--) {
// listeners.get(i).onClick(v);
// }
// }
//
// public int addListener(View.OnClickListener listener) {
// listeners.add(listener);
// return listeners.size() - 1;
// }
//
// public void removeListener(View.OnClickListener listener) {
// listeners.remove(listener);
// }
//
// public void removeListener(int index) {
// listeners.remove(index);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/util/Utils.java
// public class Utils {
//
// private Utils() {}
//
// public static int dpToPixels(Context context, int dp) {
// Resources resources = context.getResources();
// DisplayMetrics metrics = resources.getDisplayMetrics();
// return Math.round(dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
// }
//
// public static int clickableBackground(Context context) {
// TypedValue outValue = new TypedValue();
// context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
// return outValue.resourceId;
// }
// }
| import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.core.content.ContextCompat;
import com.yarolegovich.mp.io.MaterialPreferences;
import com.yarolegovich.mp.io.StorageModule;
import com.yarolegovich.mp.io.UserInputModule;
import com.yarolegovich.mp.util.CompositeClickListener;
import com.yarolegovich.mp.util.Utils; | package com.yarolegovich.mp;
/**
* Created by yarolegovich on 01.05.2016.
*/
@SuppressWarnings("ResourceType")
abstract class AbsMaterialPreference<T> extends LinearLayout {
private TextView title;
private TextView summary;
private ImageView icon;
protected String defaultValue;
protected String key;
protected UserInputModule userInputModule; | // Path: library/src/main/java/com/yarolegovich/mp/io/MaterialPreferences.java
// public class MaterialPreferences {
//
// private static final MaterialPreferences instance = new MaterialPreferences();
//
// public static MaterialPreferences instance() {
// return instance;
// }
//
// public static UserInputModule getUserInputModule(Context context) {
// return instance.userInputModuleFactory.create(context);
// }
//
// public static StorageModule getStorageModule(Context context) {
// return instance.storageModuleFactory.create(context);
// }
//
// private UserInputModule.Factory userInputModuleFactory;
// private StorageModule.Factory storageModuleFactory;
//
// private MaterialPreferences() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
// public MaterialPreferences setUserInputModule(UserInputModule.Factory factory) {
// userInputModuleFactory = factory;
// return this;
// }
//
// public MaterialPreferences setStorageModule(StorageModule.Factory factory) {
// storageModuleFactory = factory;
// return this;
// }
//
// public void setDefault() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
//
// private static class StandardUserInputFactory implements UserInputModule.Factory {
// @Override
// public UserInputModule create(Context context) {
// return new StandardUserInputModule(context);
// }
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/UserInputModule.java
// public interface UserInputModule {
//
// void showEditTextInput(
// String key,
// CharSequence title,
// CharSequence defaultValue,
// Listener<String> listener);
//
// void showSingleChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// int selected,
// Listener<String> listener);
//
// void showMultiChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// boolean[] defaultSelection,
// Listener<Set<String>> listener);
//
// void showColorSelectionInput(
// String key,
// CharSequence title,
// int defaultColor,
// Listener<Integer> color);
//
// interface Factory {
// UserInputModule create(Context context);
// }
//
// interface Listener<T> {
// void onInput(T value);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/util/CompositeClickListener.java
// public class CompositeClickListener implements View.OnClickListener {
//
// private List<View.OnClickListener> listeners;
//
// public CompositeClickListener() {
// listeners = new ArrayList<>();
// }
//
// @Override
// public void onClick(View v) {
// for (int i = listeners.size() - 1; i >= 0; i--) {
// listeners.get(i).onClick(v);
// }
// }
//
// public int addListener(View.OnClickListener listener) {
// listeners.add(listener);
// return listeners.size() - 1;
// }
//
// public void removeListener(View.OnClickListener listener) {
// listeners.remove(listener);
// }
//
// public void removeListener(int index) {
// listeners.remove(index);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/util/Utils.java
// public class Utils {
//
// private Utils() {}
//
// public static int dpToPixels(Context context, int dp) {
// Resources resources = context.getResources();
// DisplayMetrics metrics = resources.getDisplayMetrics();
// return Math.round(dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
// }
//
// public static int clickableBackground(Context context) {
// TypedValue outValue = new TypedValue();
// context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
// return outValue.resourceId;
// }
// }
// Path: library/src/main/java/com/yarolegovich/mp/AbsMaterialPreference.java
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.core.content.ContextCompat;
import com.yarolegovich.mp.io.MaterialPreferences;
import com.yarolegovich.mp.io.StorageModule;
import com.yarolegovich.mp.io.UserInputModule;
import com.yarolegovich.mp.util.CompositeClickListener;
import com.yarolegovich.mp.util.Utils;
package com.yarolegovich.mp;
/**
* Created by yarolegovich on 01.05.2016.
*/
@SuppressWarnings("ResourceType")
abstract class AbsMaterialPreference<T> extends LinearLayout {
private TextView title;
private TextView summary;
private ImageView icon;
protected String defaultValue;
protected String key;
protected UserInputModule userInputModule; | protected StorageModule storageModule; |
yarolegovich/MaterialPreferences | library/src/main/java/com/yarolegovich/mp/AbsMaterialPreference.java | // Path: library/src/main/java/com/yarolegovich/mp/io/MaterialPreferences.java
// public class MaterialPreferences {
//
// private static final MaterialPreferences instance = new MaterialPreferences();
//
// public static MaterialPreferences instance() {
// return instance;
// }
//
// public static UserInputModule getUserInputModule(Context context) {
// return instance.userInputModuleFactory.create(context);
// }
//
// public static StorageModule getStorageModule(Context context) {
// return instance.storageModuleFactory.create(context);
// }
//
// private UserInputModule.Factory userInputModuleFactory;
// private StorageModule.Factory storageModuleFactory;
//
// private MaterialPreferences() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
// public MaterialPreferences setUserInputModule(UserInputModule.Factory factory) {
// userInputModuleFactory = factory;
// return this;
// }
//
// public MaterialPreferences setStorageModule(StorageModule.Factory factory) {
// storageModuleFactory = factory;
// return this;
// }
//
// public void setDefault() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
//
// private static class StandardUserInputFactory implements UserInputModule.Factory {
// @Override
// public UserInputModule create(Context context) {
// return new StandardUserInputModule(context);
// }
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/UserInputModule.java
// public interface UserInputModule {
//
// void showEditTextInput(
// String key,
// CharSequence title,
// CharSequence defaultValue,
// Listener<String> listener);
//
// void showSingleChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// int selected,
// Listener<String> listener);
//
// void showMultiChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// boolean[] defaultSelection,
// Listener<Set<String>> listener);
//
// void showColorSelectionInput(
// String key,
// CharSequence title,
// int defaultColor,
// Listener<Integer> color);
//
// interface Factory {
// UserInputModule create(Context context);
// }
//
// interface Listener<T> {
// void onInput(T value);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/util/CompositeClickListener.java
// public class CompositeClickListener implements View.OnClickListener {
//
// private List<View.OnClickListener> listeners;
//
// public CompositeClickListener() {
// listeners = new ArrayList<>();
// }
//
// @Override
// public void onClick(View v) {
// for (int i = listeners.size() - 1; i >= 0; i--) {
// listeners.get(i).onClick(v);
// }
// }
//
// public int addListener(View.OnClickListener listener) {
// listeners.add(listener);
// return listeners.size() - 1;
// }
//
// public void removeListener(View.OnClickListener listener) {
// listeners.remove(listener);
// }
//
// public void removeListener(int index) {
// listeners.remove(index);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/util/Utils.java
// public class Utils {
//
// private Utils() {}
//
// public static int dpToPixels(Context context, int dp) {
// Resources resources = context.getResources();
// DisplayMetrics metrics = resources.getDisplayMetrics();
// return Math.round(dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
// }
//
// public static int clickableBackground(Context context) {
// TypedValue outValue = new TypedValue();
// context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
// return outValue.resourceId;
// }
// }
| import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.core.content.ContextCompat;
import com.yarolegovich.mp.io.MaterialPreferences;
import com.yarolegovich.mp.io.StorageModule;
import com.yarolegovich.mp.io.UserInputModule;
import com.yarolegovich.mp.util.CompositeClickListener;
import com.yarolegovich.mp.util.Utils; | package com.yarolegovich.mp;
/**
* Created by yarolegovich on 01.05.2016.
*/
@SuppressWarnings("ResourceType")
abstract class AbsMaterialPreference<T> extends LinearLayout {
private TextView title;
private TextView summary;
private ImageView icon;
protected String defaultValue;
protected String key;
protected UserInputModule userInputModule;
protected StorageModule storageModule;
| // Path: library/src/main/java/com/yarolegovich/mp/io/MaterialPreferences.java
// public class MaterialPreferences {
//
// private static final MaterialPreferences instance = new MaterialPreferences();
//
// public static MaterialPreferences instance() {
// return instance;
// }
//
// public static UserInputModule getUserInputModule(Context context) {
// return instance.userInputModuleFactory.create(context);
// }
//
// public static StorageModule getStorageModule(Context context) {
// return instance.storageModuleFactory.create(context);
// }
//
// private UserInputModule.Factory userInputModuleFactory;
// private StorageModule.Factory storageModuleFactory;
//
// private MaterialPreferences() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
// public MaterialPreferences setUserInputModule(UserInputModule.Factory factory) {
// userInputModuleFactory = factory;
// return this;
// }
//
// public MaterialPreferences setStorageModule(StorageModule.Factory factory) {
// storageModuleFactory = factory;
// return this;
// }
//
// public void setDefault() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
//
// private static class StandardUserInputFactory implements UserInputModule.Factory {
// @Override
// public UserInputModule create(Context context) {
// return new StandardUserInputModule(context);
// }
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/UserInputModule.java
// public interface UserInputModule {
//
// void showEditTextInput(
// String key,
// CharSequence title,
// CharSequence defaultValue,
// Listener<String> listener);
//
// void showSingleChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// int selected,
// Listener<String> listener);
//
// void showMultiChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// boolean[] defaultSelection,
// Listener<Set<String>> listener);
//
// void showColorSelectionInput(
// String key,
// CharSequence title,
// int defaultColor,
// Listener<Integer> color);
//
// interface Factory {
// UserInputModule create(Context context);
// }
//
// interface Listener<T> {
// void onInput(T value);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/util/CompositeClickListener.java
// public class CompositeClickListener implements View.OnClickListener {
//
// private List<View.OnClickListener> listeners;
//
// public CompositeClickListener() {
// listeners = new ArrayList<>();
// }
//
// @Override
// public void onClick(View v) {
// for (int i = listeners.size() - 1; i >= 0; i--) {
// listeners.get(i).onClick(v);
// }
// }
//
// public int addListener(View.OnClickListener listener) {
// listeners.add(listener);
// return listeners.size() - 1;
// }
//
// public void removeListener(View.OnClickListener listener) {
// listeners.remove(listener);
// }
//
// public void removeListener(int index) {
// listeners.remove(index);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/util/Utils.java
// public class Utils {
//
// private Utils() {}
//
// public static int dpToPixels(Context context, int dp) {
// Resources resources = context.getResources();
// DisplayMetrics metrics = resources.getDisplayMetrics();
// return Math.round(dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
// }
//
// public static int clickableBackground(Context context) {
// TypedValue outValue = new TypedValue();
// context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
// return outValue.resourceId;
// }
// }
// Path: library/src/main/java/com/yarolegovich/mp/AbsMaterialPreference.java
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.core.content.ContextCompat;
import com.yarolegovich.mp.io.MaterialPreferences;
import com.yarolegovich.mp.io.StorageModule;
import com.yarolegovich.mp.io.UserInputModule;
import com.yarolegovich.mp.util.CompositeClickListener;
import com.yarolegovich.mp.util.Utils;
package com.yarolegovich.mp;
/**
* Created by yarolegovich on 01.05.2016.
*/
@SuppressWarnings("ResourceType")
abstract class AbsMaterialPreference<T> extends LinearLayout {
private TextView title;
private TextView summary;
private ImageView icon;
protected String defaultValue;
protected String key;
protected UserInputModule userInputModule;
protected StorageModule storageModule;
| private CompositeClickListener compositeClickListener; |
yarolegovich/MaterialPreferences | library/src/main/java/com/yarolegovich/mp/AbsMaterialPreference.java | // Path: library/src/main/java/com/yarolegovich/mp/io/MaterialPreferences.java
// public class MaterialPreferences {
//
// private static final MaterialPreferences instance = new MaterialPreferences();
//
// public static MaterialPreferences instance() {
// return instance;
// }
//
// public static UserInputModule getUserInputModule(Context context) {
// return instance.userInputModuleFactory.create(context);
// }
//
// public static StorageModule getStorageModule(Context context) {
// return instance.storageModuleFactory.create(context);
// }
//
// private UserInputModule.Factory userInputModuleFactory;
// private StorageModule.Factory storageModuleFactory;
//
// private MaterialPreferences() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
// public MaterialPreferences setUserInputModule(UserInputModule.Factory factory) {
// userInputModuleFactory = factory;
// return this;
// }
//
// public MaterialPreferences setStorageModule(StorageModule.Factory factory) {
// storageModuleFactory = factory;
// return this;
// }
//
// public void setDefault() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
//
// private static class StandardUserInputFactory implements UserInputModule.Factory {
// @Override
// public UserInputModule create(Context context) {
// return new StandardUserInputModule(context);
// }
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/UserInputModule.java
// public interface UserInputModule {
//
// void showEditTextInput(
// String key,
// CharSequence title,
// CharSequence defaultValue,
// Listener<String> listener);
//
// void showSingleChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// int selected,
// Listener<String> listener);
//
// void showMultiChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// boolean[] defaultSelection,
// Listener<Set<String>> listener);
//
// void showColorSelectionInput(
// String key,
// CharSequence title,
// int defaultColor,
// Listener<Integer> color);
//
// interface Factory {
// UserInputModule create(Context context);
// }
//
// interface Listener<T> {
// void onInput(T value);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/util/CompositeClickListener.java
// public class CompositeClickListener implements View.OnClickListener {
//
// private List<View.OnClickListener> listeners;
//
// public CompositeClickListener() {
// listeners = new ArrayList<>();
// }
//
// @Override
// public void onClick(View v) {
// for (int i = listeners.size() - 1; i >= 0; i--) {
// listeners.get(i).onClick(v);
// }
// }
//
// public int addListener(View.OnClickListener listener) {
// listeners.add(listener);
// return listeners.size() - 1;
// }
//
// public void removeListener(View.OnClickListener listener) {
// listeners.remove(listener);
// }
//
// public void removeListener(int index) {
// listeners.remove(index);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/util/Utils.java
// public class Utils {
//
// private Utils() {}
//
// public static int dpToPixels(Context context, int dp) {
// Resources resources = context.getResources();
// DisplayMetrics metrics = resources.getDisplayMetrics();
// return Math.round(dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
// }
//
// public static int clickableBackground(Context context) {
// TypedValue outValue = new TypedValue();
// context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
// return outValue.resourceId;
// }
// }
| import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.core.content.ContextCompat;
import com.yarolegovich.mp.io.MaterialPreferences;
import com.yarolegovich.mp.io.StorageModule;
import com.yarolegovich.mp.io.UserInputModule;
import com.yarolegovich.mp.util.CompositeClickListener;
import com.yarolegovich.mp.util.Utils; | }
public void removePreferenceClickListener(int index) {
compositeClickListener.removeListener(index);
}
public void setUserInputModule(UserInputModule userInputModule) {
this.userInputModule = userInputModule;
}
public void setStorageModule(StorageModule storageModule) {
this.storageModule = storageModule;
}
@Nullable
public String getKey() {
return key;
}
@LayoutRes
protected abstract int getLayout();
/*
* Template methods
*/
protected void onCollectAttributes(AttributeSet attrs) {
}
protected void onConfigureSelf() { | // Path: library/src/main/java/com/yarolegovich/mp/io/MaterialPreferences.java
// public class MaterialPreferences {
//
// private static final MaterialPreferences instance = new MaterialPreferences();
//
// public static MaterialPreferences instance() {
// return instance;
// }
//
// public static UserInputModule getUserInputModule(Context context) {
// return instance.userInputModuleFactory.create(context);
// }
//
// public static StorageModule getStorageModule(Context context) {
// return instance.storageModuleFactory.create(context);
// }
//
// private UserInputModule.Factory userInputModuleFactory;
// private StorageModule.Factory storageModuleFactory;
//
// private MaterialPreferences() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
// public MaterialPreferences setUserInputModule(UserInputModule.Factory factory) {
// userInputModuleFactory = factory;
// return this;
// }
//
// public MaterialPreferences setStorageModule(StorageModule.Factory factory) {
// storageModuleFactory = factory;
// return this;
// }
//
// public void setDefault() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
//
// private static class StandardUserInputFactory implements UserInputModule.Factory {
// @Override
// public UserInputModule create(Context context) {
// return new StandardUserInputModule(context);
// }
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/UserInputModule.java
// public interface UserInputModule {
//
// void showEditTextInput(
// String key,
// CharSequence title,
// CharSequence defaultValue,
// Listener<String> listener);
//
// void showSingleChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// int selected,
// Listener<String> listener);
//
// void showMultiChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// boolean[] defaultSelection,
// Listener<Set<String>> listener);
//
// void showColorSelectionInput(
// String key,
// CharSequence title,
// int defaultColor,
// Listener<Integer> color);
//
// interface Factory {
// UserInputModule create(Context context);
// }
//
// interface Listener<T> {
// void onInput(T value);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/util/CompositeClickListener.java
// public class CompositeClickListener implements View.OnClickListener {
//
// private List<View.OnClickListener> listeners;
//
// public CompositeClickListener() {
// listeners = new ArrayList<>();
// }
//
// @Override
// public void onClick(View v) {
// for (int i = listeners.size() - 1; i >= 0; i--) {
// listeners.get(i).onClick(v);
// }
// }
//
// public int addListener(View.OnClickListener listener) {
// listeners.add(listener);
// return listeners.size() - 1;
// }
//
// public void removeListener(View.OnClickListener listener) {
// listeners.remove(listener);
// }
//
// public void removeListener(int index) {
// listeners.remove(index);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/util/Utils.java
// public class Utils {
//
// private Utils() {}
//
// public static int dpToPixels(Context context, int dp) {
// Resources resources = context.getResources();
// DisplayMetrics metrics = resources.getDisplayMetrics();
// return Math.round(dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
// }
//
// public static int clickableBackground(Context context) {
// TypedValue outValue = new TypedValue();
// context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
// return outValue.resourceId;
// }
// }
// Path: library/src/main/java/com/yarolegovich/mp/AbsMaterialPreference.java
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.core.content.ContextCompat;
import com.yarolegovich.mp.io.MaterialPreferences;
import com.yarolegovich.mp.io.StorageModule;
import com.yarolegovich.mp.io.UserInputModule;
import com.yarolegovich.mp.util.CompositeClickListener;
import com.yarolegovich.mp.util.Utils;
}
public void removePreferenceClickListener(int index) {
compositeClickListener.removeListener(index);
}
public void setUserInputModule(UserInputModule userInputModule) {
this.userInputModule = userInputModule;
}
public void setStorageModule(StorageModule storageModule) {
this.storageModule = storageModule;
}
@Nullable
public String getKey() {
return key;
}
@LayoutRes
protected abstract int getLayout();
/*
* Template methods
*/
protected void onCollectAttributes(AttributeSet attrs) {
}
protected void onConfigureSelf() { | setBackgroundResource(Utils.clickableBackground(getContext())); |
yarolegovich/MaterialPreferences | library/src/main/java/com/yarolegovich/mp/MaterialSeekBarPreference.java | // Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/util/Utils.java
// public class Utils {
//
// private Utils() {}
//
// public static int dpToPixels(Context context, int dp) {
// Resources resources = context.getResources();
// DisplayMetrics metrics = resources.getDisplayMetrics();
// return Math.round(dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
// }
//
// public static int clickableBackground(Context context) {
// TypedValue outValue = new TypedValue();
// context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
// return outValue.resourceId;
// }
// }
| import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.appcompat.widget.AppCompatSeekBar;
import com.yarolegovich.mp.io.StorageModule;
import com.yarolegovich.mp.util.Utils;
import static com.yarolegovich.mp.R.styleable.MaterialSeekBarPreference;
import static com.yarolegovich.mp.R.styleable.MaterialSeekBarPreference_mp_max_val;
import static com.yarolegovich.mp.R.styleable.MaterialSeekBarPreference_mp_min_val;
import static com.yarolegovich.mp.R.styleable.MaterialSeekBarPreference_mp_show_val; | package com.yarolegovich.mp;
/**
* Created by yarolegovich on 15.05.2016.
*/
public class MaterialSeekBarPreference extends AbsMaterialPreference<Integer> {
private AppCompatSeekBar seekBar;
private TextView value;
private int minValue;
private int maxValue;
private boolean showValue;
public MaterialSeekBarPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MaterialSeekBarPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MaterialSeekBarPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onConfigureSelf() { | // Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/util/Utils.java
// public class Utils {
//
// private Utils() {}
//
// public static int dpToPixels(Context context, int dp) {
// Resources resources = context.getResources();
// DisplayMetrics metrics = resources.getDisplayMetrics();
// return Math.round(dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
// }
//
// public static int clickableBackground(Context context) {
// TypedValue outValue = new TypedValue();
// context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
// return outValue.resourceId;
// }
// }
// Path: library/src/main/java/com/yarolegovich/mp/MaterialSeekBarPreference.java
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.appcompat.widget.AppCompatSeekBar;
import com.yarolegovich.mp.io.StorageModule;
import com.yarolegovich.mp.util.Utils;
import static com.yarolegovich.mp.R.styleable.MaterialSeekBarPreference;
import static com.yarolegovich.mp.R.styleable.MaterialSeekBarPreference_mp_max_val;
import static com.yarolegovich.mp.R.styleable.MaterialSeekBarPreference_mp_min_val;
import static com.yarolegovich.mp.R.styleable.MaterialSeekBarPreference_mp_show_val;
package com.yarolegovich.mp;
/**
* Created by yarolegovich on 15.05.2016.
*/
public class MaterialSeekBarPreference extends AbsMaterialPreference<Integer> {
private AppCompatSeekBar seekBar;
private TextView value;
private int minValue;
private int maxValue;
private boolean showValue;
public MaterialSeekBarPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MaterialSeekBarPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MaterialSeekBarPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onConfigureSelf() { | int padding = Utils.dpToPixels(getContext(), 16); |
yarolegovich/MaterialPreferences | library/src/main/java/com/yarolegovich/mp/MaterialSeekBarPreference.java | // Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/util/Utils.java
// public class Utils {
//
// private Utils() {}
//
// public static int dpToPixels(Context context, int dp) {
// Resources resources = context.getResources();
// DisplayMetrics metrics = resources.getDisplayMetrics();
// return Math.round(dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
// }
//
// public static int clickableBackground(Context context) {
// TypedValue outValue = new TypedValue();
// context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
// return outValue.resourceId;
// }
// }
| import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.appcompat.widget.AppCompatSeekBar;
import com.yarolegovich.mp.io.StorageModule;
import com.yarolegovich.mp.util.Utils;
import static com.yarolegovich.mp.R.styleable.MaterialSeekBarPreference;
import static com.yarolegovich.mp.R.styleable.MaterialSeekBarPreference_mp_max_val;
import static com.yarolegovich.mp.R.styleable.MaterialSeekBarPreference_mp_min_val;
import static com.yarolegovich.mp.R.styleable.MaterialSeekBarPreference_mp_show_val; |
@Override
protected void onViewCreated() {
value = (TextView) findViewById(R.id.mp_value);
if (showValue) {
value.setVisibility(VISIBLE);
}
seekBar = (AppCompatSeekBar) findViewById(R.id.mp_seekbar);
seekBar.setOnSeekBarChangeListener(new ProgressSaver());
seekBar.setMax(maxValue - minValue);
setSeekBarValue(getValue());
}
@Override
public Integer getValue() {
try {
return storageModule.getInt(key, Integer.parseInt(defaultValue));
} catch (NumberFormatException e) {
throw new AssertionError(getContext().getString(R.string.exc_not_int_default));
}
}
@Override
public void setValue(Integer value) {
storageModule.saveInt(key, value);
setSeekBarValue(value);
}
@Override | // Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/util/Utils.java
// public class Utils {
//
// private Utils() {}
//
// public static int dpToPixels(Context context, int dp) {
// Resources resources = context.getResources();
// DisplayMetrics metrics = resources.getDisplayMetrics();
// return Math.round(dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
// }
//
// public static int clickableBackground(Context context) {
// TypedValue outValue = new TypedValue();
// context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
// return outValue.resourceId;
// }
// }
// Path: library/src/main/java/com/yarolegovich/mp/MaterialSeekBarPreference.java
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.appcompat.widget.AppCompatSeekBar;
import com.yarolegovich.mp.io.StorageModule;
import com.yarolegovich.mp.util.Utils;
import static com.yarolegovich.mp.R.styleable.MaterialSeekBarPreference;
import static com.yarolegovich.mp.R.styleable.MaterialSeekBarPreference_mp_max_val;
import static com.yarolegovich.mp.R.styleable.MaterialSeekBarPreference_mp_min_val;
import static com.yarolegovich.mp.R.styleable.MaterialSeekBarPreference_mp_show_val;
@Override
protected void onViewCreated() {
value = (TextView) findViewById(R.id.mp_value);
if (showValue) {
value.setVisibility(VISIBLE);
}
seekBar = (AppCompatSeekBar) findViewById(R.id.mp_seekbar);
seekBar.setOnSeekBarChangeListener(new ProgressSaver());
seekBar.setMax(maxValue - minValue);
setSeekBarValue(getValue());
}
@Override
public Integer getValue() {
try {
return storageModule.getInt(key, Integer.parseInt(defaultValue));
} catch (NumberFormatException e) {
throw new AssertionError(getContext().getString(R.string.exc_not_int_default));
}
}
@Override
public void setValue(Integer value) {
storageModule.saveInt(key, value);
setSeekBarValue(value);
}
@Override | public void setStorageModule(StorageModule storageModule) { |
yarolegovich/MaterialPreferences | library/src/main/java/com/yarolegovich/mp/MaterialMultiChoicePreference.java | // Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
| import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import com.yarolegovich.mp.io.StorageModule;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static com.yarolegovich.mp.R.styleable.*; | CharSequence[] defSelected = ta.getTextArray(MaterialMultiChoicePreference_mp_default_selected);
for (CharSequence cs : defSelected) {
defaultSelected.add(cs.toString());
}
}
} finally {
ta.recycle();
}
}
@Override
public Set<String> getValue() {
return storageModule.getStringSet(key, defaultSelected);
}
@Override
public void setValue(Set<String> value) {
storageModule.saveStringSet(key, value);
showNewValueIfNeeded(toRepresentation(value));
}
@Override
public void onClick(View v) {
userInputModule.showMultiChoiceInput(
key, getTitle(), entries, entryValues,
itemStates(getValue()),
this);
}
@Override | // Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
// Path: library/src/main/java/com/yarolegovich/mp/MaterialMultiChoicePreference.java
import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import com.yarolegovich.mp.io.StorageModule;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static com.yarolegovich.mp.R.styleable.*;
CharSequence[] defSelected = ta.getTextArray(MaterialMultiChoicePreference_mp_default_selected);
for (CharSequence cs : defSelected) {
defaultSelected.add(cs.toString());
}
}
} finally {
ta.recycle();
}
}
@Override
public Set<String> getValue() {
return storageModule.getStringSet(key, defaultSelected);
}
@Override
public void setValue(Set<String> value) {
storageModule.saveStringSet(key, value);
showNewValueIfNeeded(toRepresentation(value));
}
@Override
public void onClick(View v) {
userInputModule.showMultiChoiceInput(
key, getTitle(), entries, entryValues,
itemStates(getValue()),
this);
}
@Override | public void setStorageModule(StorageModule storageModule) { |
yarolegovich/MaterialPreferences | library/src/main/java/com/yarolegovich/mp/MaterialPreferenceCategory.java | // Path: library/src/main/java/com/yarolegovich/mp/util/Utils.java
// public static int dpToPixels(Context context, int dp) {
// Resources resources = context.getResources();
// DisplayMetrics metrics = resources.getDisplayMetrics();
// return Math.round(dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
// }
| import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
import static com.yarolegovich.mp.util.Utils.dpToPixels; | public MaterialPreferenceCategory(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public MaterialPreferenceCategory(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs);
}
private void init(AttributeSet attrs) {
int titleColor = -1;
String titleText = "";
if (attrs != null) {
TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.MaterialPreferenceCategory);
try {
if (ta.hasValue(R.styleable.MaterialPreferenceCategory_mpc_title)) {
titleText = ta.getString(R.styleable.MaterialPreferenceCategory_mpc_title);
}
titleColor = ta.getColor(R.styleable.MaterialPreferenceCategory_mpc_title_color, -1);
} finally {
ta.recycle();
}
}
inflate(getContext(), R.layout.view_preference_category, this);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT); | // Path: library/src/main/java/com/yarolegovich/mp/util/Utils.java
// public static int dpToPixels(Context context, int dp) {
// Resources resources = context.getResources();
// DisplayMetrics metrics = resources.getDisplayMetrics();
// return Math.round(dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
// }
// Path: library/src/main/java/com/yarolegovich/mp/MaterialPreferenceCategory.java
import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
import static com.yarolegovich.mp.util.Utils.dpToPixels;
public MaterialPreferenceCategory(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public MaterialPreferenceCategory(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs);
}
private void init(AttributeSet attrs) {
int titleColor = -1;
String titleText = "";
if (attrs != null) {
TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.MaterialPreferenceCategory);
try {
if (ta.hasValue(R.styleable.MaterialPreferenceCategory_mpc_title)) {
titleText = ta.getString(R.styleable.MaterialPreferenceCategory_mpc_title);
}
titleColor = ta.getColor(R.styleable.MaterialPreferenceCategory_mpc_title_color, -1);
} finally {
ta.recycle();
}
}
inflate(getContext(), R.layout.view_preference_category, this);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT); | params.setMargins(0, 0, 0, dpToPixels(getContext(), 4)); |
yarolegovich/MaterialPreferences | library/src/main/java/com/yarolegovich/mp/MaterialEditTextPreference.java | // Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
| import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import com.yarolegovich.mp.io.StorageModule; | package com.yarolegovich.mp;
/**
* Created by yarolegovich on 01.05.2016.
*/
public class MaterialEditTextPreference extends AbsMaterialTextValuePreference<String> {
public MaterialEditTextPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MaterialEditTextPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MaterialEditTextPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public String getValue() {
return storageModule.getString(key, defaultValue);
}
@Override
public void setValue(String value) {
storageModule.saveString(key, value);
showNewValueIfNeeded(value);
}
@Override | // Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
// Path: library/src/main/java/com/yarolegovich/mp/MaterialEditTextPreference.java
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import com.yarolegovich.mp.io.StorageModule;
package com.yarolegovich.mp;
/**
* Created by yarolegovich on 01.05.2016.
*/
public class MaterialEditTextPreference extends AbsMaterialTextValuePreference<String> {
public MaterialEditTextPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MaterialEditTextPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MaterialEditTextPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public String getValue() {
return storageModule.getString(key, defaultValue);
}
@Override
public void setValue(String value) {
storageModule.saveString(key, value);
showNewValueIfNeeded(value);
}
@Override | public void setStorageModule(StorageModule storageModule) { |
yarolegovich/MaterialPreferences | library/src/main/java/com/yarolegovich/mp/AbsMaterialTextValuePreference.java | // Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/UserInputModule.java
// public interface UserInputModule {
//
// void showEditTextInput(
// String key,
// CharSequence title,
// CharSequence defaultValue,
// Listener<String> listener);
//
// void showSingleChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// int selected,
// Listener<String> listener);
//
// void showMultiChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// boolean[] defaultSelection,
// Listener<Set<String>> listener);
//
// void showColorSelectionInput(
// String key,
// CharSequence title,
// int defaultColor,
// Listener<Integer> color);
//
// interface Factory {
// UserInputModule create(Context context);
// }
//
// interface Listener<T> {
// void onInput(T value);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/MaterialPreferences.java
// public class MaterialPreferences {
//
// private static final MaterialPreferences instance = new MaterialPreferences();
//
// public static MaterialPreferences instance() {
// return instance;
// }
//
// public static UserInputModule getUserInputModule(Context context) {
// return instance.userInputModuleFactory.create(context);
// }
//
// public static StorageModule getStorageModule(Context context) {
// return instance.storageModuleFactory.create(context);
// }
//
// private UserInputModule.Factory userInputModuleFactory;
// private StorageModule.Factory storageModuleFactory;
//
// private MaterialPreferences() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
// public MaterialPreferences setUserInputModule(UserInputModule.Factory factory) {
// userInputModuleFactory = factory;
// return this;
// }
//
// public MaterialPreferences setStorageModule(StorageModule.Factory factory) {
// storageModuleFactory = factory;
// return this;
// }
//
// public void setDefault() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
//
// private static class StandardUserInputFactory implements UserInputModule.Factory {
// @Override
// public UserInputModule create(Context context) {
// return new StandardUserInputModule(context);
// }
// }
// }
| import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;
import com.yarolegovich.mp.io.StorageModule;
import com.yarolegovich.mp.io.UserInputModule;
import com.yarolegovich.mp.io.MaterialPreferences;
import static com.yarolegovich.mp.R.styleable.*; | package com.yarolegovich.mp;
/**
* Created by yarolegovich on 05.05.2016.
*/
@SuppressWarnings("ResourceType")
abstract class AbsMaterialTextValuePreference<T> extends AbsMaterialPreference<T> implements | // Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/UserInputModule.java
// public interface UserInputModule {
//
// void showEditTextInput(
// String key,
// CharSequence title,
// CharSequence defaultValue,
// Listener<String> listener);
//
// void showSingleChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// int selected,
// Listener<String> listener);
//
// void showMultiChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// boolean[] defaultSelection,
// Listener<Set<String>> listener);
//
// void showColorSelectionInput(
// String key,
// CharSequence title,
// int defaultColor,
// Listener<Integer> color);
//
// interface Factory {
// UserInputModule create(Context context);
// }
//
// interface Listener<T> {
// void onInput(T value);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/MaterialPreferences.java
// public class MaterialPreferences {
//
// private static final MaterialPreferences instance = new MaterialPreferences();
//
// public static MaterialPreferences instance() {
// return instance;
// }
//
// public static UserInputModule getUserInputModule(Context context) {
// return instance.userInputModuleFactory.create(context);
// }
//
// public static StorageModule getStorageModule(Context context) {
// return instance.storageModuleFactory.create(context);
// }
//
// private UserInputModule.Factory userInputModuleFactory;
// private StorageModule.Factory storageModuleFactory;
//
// private MaterialPreferences() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
// public MaterialPreferences setUserInputModule(UserInputModule.Factory factory) {
// userInputModuleFactory = factory;
// return this;
// }
//
// public MaterialPreferences setStorageModule(StorageModule.Factory factory) {
// storageModuleFactory = factory;
// return this;
// }
//
// public void setDefault() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
//
// private static class StandardUserInputFactory implements UserInputModule.Factory {
// @Override
// public UserInputModule create(Context context) {
// return new StandardUserInputModule(context);
// }
// }
// }
// Path: library/src/main/java/com/yarolegovich/mp/AbsMaterialTextValuePreference.java
import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;
import com.yarolegovich.mp.io.StorageModule;
import com.yarolegovich.mp.io.UserInputModule;
import com.yarolegovich.mp.io.MaterialPreferences;
import static com.yarolegovich.mp.R.styleable.*;
package com.yarolegovich.mp;
/**
* Created by yarolegovich on 05.05.2016.
*/
@SuppressWarnings("ResourceType")
abstract class AbsMaterialTextValuePreference<T> extends AbsMaterialPreference<T> implements | UserInputModule.Listener<T>, android.view.View.OnClickListener { |
yarolegovich/MaterialPreferences | library/src/main/java/com/yarolegovich/mp/AbsMaterialTextValuePreference.java | // Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/UserInputModule.java
// public interface UserInputModule {
//
// void showEditTextInput(
// String key,
// CharSequence title,
// CharSequence defaultValue,
// Listener<String> listener);
//
// void showSingleChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// int selected,
// Listener<String> listener);
//
// void showMultiChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// boolean[] defaultSelection,
// Listener<Set<String>> listener);
//
// void showColorSelectionInput(
// String key,
// CharSequence title,
// int defaultColor,
// Listener<Integer> color);
//
// interface Factory {
// UserInputModule create(Context context);
// }
//
// interface Listener<T> {
// void onInput(T value);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/MaterialPreferences.java
// public class MaterialPreferences {
//
// private static final MaterialPreferences instance = new MaterialPreferences();
//
// public static MaterialPreferences instance() {
// return instance;
// }
//
// public static UserInputModule getUserInputModule(Context context) {
// return instance.userInputModuleFactory.create(context);
// }
//
// public static StorageModule getStorageModule(Context context) {
// return instance.storageModuleFactory.create(context);
// }
//
// private UserInputModule.Factory userInputModuleFactory;
// private StorageModule.Factory storageModuleFactory;
//
// private MaterialPreferences() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
// public MaterialPreferences setUserInputModule(UserInputModule.Factory factory) {
// userInputModuleFactory = factory;
// return this;
// }
//
// public MaterialPreferences setStorageModule(StorageModule.Factory factory) {
// storageModuleFactory = factory;
// return this;
// }
//
// public void setDefault() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
//
// private static class StandardUserInputFactory implements UserInputModule.Factory {
// @Override
// public UserInputModule create(Context context) {
// return new StandardUserInputModule(context);
// }
// }
// }
| import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;
import com.yarolegovich.mp.io.StorageModule;
import com.yarolegovich.mp.io.UserInputModule;
import com.yarolegovich.mp.io.MaterialPreferences;
import static com.yarolegovich.mp.R.styleable.*; | public AbsMaterialTextValuePreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AbsMaterialTextValuePreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public AbsMaterialTextValuePreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onCollectAttributes(AttributeSet attrs) {
TypedArray ta = getContext().obtainStyledAttributes(attrs, AbsMaterialTextValuePreference);
try {
showValueMode = ta.getInt(AbsMaterialTextValuePreference_mp_show_value, NOT_SHOW_VALUE);
} finally {
ta.recycle();
}
}
@Override
protected void onViewCreated() {
rightValue = (TextView) findViewById(R.id.mp_right_value);
showNewValueIfNeeded(toRepresentation(getValue()));
addPreferenceClickListener(this);
}
@Override | // Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/UserInputModule.java
// public interface UserInputModule {
//
// void showEditTextInput(
// String key,
// CharSequence title,
// CharSequence defaultValue,
// Listener<String> listener);
//
// void showSingleChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// int selected,
// Listener<String> listener);
//
// void showMultiChoiceInput(
// String key,
// CharSequence title,
// CharSequence[] displayItems,
// CharSequence[] values,
// boolean[] defaultSelection,
// Listener<Set<String>> listener);
//
// void showColorSelectionInput(
// String key,
// CharSequence title,
// int defaultColor,
// Listener<Integer> color);
//
// interface Factory {
// UserInputModule create(Context context);
// }
//
// interface Listener<T> {
// void onInput(T value);
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/MaterialPreferences.java
// public class MaterialPreferences {
//
// private static final MaterialPreferences instance = new MaterialPreferences();
//
// public static MaterialPreferences instance() {
// return instance;
// }
//
// public static UserInputModule getUserInputModule(Context context) {
// return instance.userInputModuleFactory.create(context);
// }
//
// public static StorageModule getStorageModule(Context context) {
// return instance.storageModuleFactory.create(context);
// }
//
// private UserInputModule.Factory userInputModuleFactory;
// private StorageModule.Factory storageModuleFactory;
//
// private MaterialPreferences() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
// public MaterialPreferences setUserInputModule(UserInputModule.Factory factory) {
// userInputModuleFactory = factory;
// return this;
// }
//
// public MaterialPreferences setStorageModule(StorageModule.Factory factory) {
// storageModuleFactory = factory;
// return this;
// }
//
// public void setDefault() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
//
// private static class StandardUserInputFactory implements UserInputModule.Factory {
// @Override
// public UserInputModule create(Context context) {
// return new StandardUserInputModule(context);
// }
// }
// }
// Path: library/src/main/java/com/yarolegovich/mp/AbsMaterialTextValuePreference.java
import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;
import com.yarolegovich.mp.io.StorageModule;
import com.yarolegovich.mp.io.UserInputModule;
import com.yarolegovich.mp.io.MaterialPreferences;
import static com.yarolegovich.mp.R.styleable.*;
public AbsMaterialTextValuePreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AbsMaterialTextValuePreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public AbsMaterialTextValuePreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onCollectAttributes(AttributeSet attrs) {
TypedArray ta = getContext().obtainStyledAttributes(attrs, AbsMaterialTextValuePreference);
try {
showValueMode = ta.getInt(AbsMaterialTextValuePreference_mp_show_value, NOT_SHOW_VALUE);
} finally {
ta.recycle();
}
}
@Override
protected void onViewCreated() {
rightValue = (TextView) findViewById(R.id.mp_right_value);
showNewValueIfNeeded(toRepresentation(getValue()));
addPreferenceClickListener(this);
}
@Override | public void setStorageModule(StorageModule storageModule) { |
yarolegovich/MaterialPreferences | sample/src/main/java/com/yarolegovich/materialprefsample/FillTheFormActivity.java | // Path: library/src/main/java/com/yarolegovich/mp/MaterialPreferenceScreen.java
// public class MaterialPreferenceScreen extends ScrollView {
//
// private LinearLayout container;
//
// private UserInputModule userInputModule;
// private StorageModule storageModule;
//
// public MaterialPreferenceScreen(Context context) {
// super(context);
// }
//
// public MaterialPreferenceScreen(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public MaterialPreferenceScreen(Context context, AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// }
//
// @TargetApi(Build.VERSION_CODES.LOLLIPOP)
// public MaterialPreferenceScreen(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
// super(context, attrs, defStyleAttr, defStyleRes);
// }
//
// {
// setFillViewport(true);
// LinearLayout container = new LinearLayout(getContext());
// container.setLayoutParams(new ViewGroup.LayoutParams(
// ViewGroup.LayoutParams.MATCH_PARENT,
// ViewGroup.LayoutParams.WRAP_CONTENT));
// container.setOrientation(LinearLayout.VERTICAL);
// addView(container);
// this.container = container;
// }
//
// public void changeViewsVisibility(List<Integer> viewIds, boolean visible) {
// int visibility = visible ? VISIBLE : GONE;
// changeViewsVisibility(container, viewIds, visibility);
// }
//
// public void setVisibilityController(int controllerId, List<Integer> controlledIds, boolean showWhenChecked) {
// setVisibilityController(
// (AbsMaterialCheckablePreference) findViewById(controllerId),
// controlledIds, showWhenChecked
// );
// }
//
// public void setVisibilityController(
// final AbsMaterialCheckablePreference controller,
// final List<Integer> controlledIds,
// final boolean showWhenChecked) {
// boolean shouldShow = showWhenChecked ? controller.getValue() : !controller.getValue();
// int initialVisibility = shouldShow ? View.VISIBLE : View.GONE;
// changeViewsVisibility(this, controlledIds, initialVisibility);
// controller.addPreferenceClickListener(new OnClickListener() {
// @Override
// public void onClick(View v) {
// boolean shouldShow = showWhenChecked ? controller.getValue() : !controller.getValue();
// int visibility = shouldShow ? View.VISIBLE : View.GONE;
// changeViewsVisibility(MaterialPreferenceScreen.this,
// controlledIds,
// visibility);
// }
// });
// }
//
// private void changeViewsVisibility(ViewGroup container, Collection<Integer> viewIds, int visibility) {
// for (int i = 0; i < container.getChildCount(); i++) {
// View child = container.getChildAt(i);
// if (child instanceof ViewGroup) {
// if (viewIds.contains(child.getId())) {
// child.setVisibility(visibility);
// } else if (!(child instanceof AbsMaterialPreference)) {
// changeViewsVisibility((ViewGroup) child, viewIds, visibility);
// }
// }
// if (viewIds.contains(child.getId())) {
// child.setVisibility(visibility);
// }
// }
// }
//
// UserInputModule getUserInputModule() {
// return userInputModule;
// }
//
// StorageModule getStorageModule() {
// return storageModule;
// }
//
// public void setUserInputModule(UserInputModule userInputModule) {
// this.userInputModule = userInputModule;
// setUserInputModuleRecursively(container, userInputModule);
// }
//
// public void setStorageModule(StorageModule storageModule) {
// this.storageModule = storageModule;
// setStorageModuleRecursively(container, storageModule);
// }
//
// private void setUserInputModuleRecursively(ViewGroup container, UserInputModule module) {
// for (int i = 0; i < container.getChildCount(); i++) {
// View child = container.getChildAt(i);
// if (child instanceof AbsMaterialPreference) {
// ((AbsMaterialPreference) child).setUserInputModule(module);
// } else if (child instanceof ViewGroup) {
// setUserInputModuleRecursively((ViewGroup) child, module);
// }
// }
// }
//
// private void setStorageModuleRecursively(ViewGroup container, StorageModule module) {
// for (int i = 0; i < container.getChildCount(); i++) {
// View child = container.getChildAt(i);
// if (child instanceof AbsMaterialPreference) {
// ((AbsMaterialPreference) child).setStorageModule(module);
// } else if (child instanceof ViewGroup) {
// setStorageModuleRecursively((ViewGroup) child, module);
// }
// }
// }
//
// @Override
// public void addView(View child) {
// if (container != null) {
// container.addView(child);
// } else {
// super.addView(child);
// }
// }
//
// @Override
// public void addView(View child, int index) {
// if (container != null) {
// container.addView(child, index);
// } else {
// super.addView(child, index);
// }
// }
//
// @Override
// public void addView(View child, ViewGroup.LayoutParams params) {
// if (container != null) {
// container.addView(child, params);
// } else {
// super.addView(child, params);
// }
// }
//
// @Override
// public void addView(View child, int index, ViewGroup.LayoutParams params) {
// if (container != null) {
// container.addView(child, index, params);
// } else {
// super.addView(child, index, params);
// }
// }
//
// }
| import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.yarolegovich.mp.MaterialPreferenceScreen; | package com.yarolegovich.materialprefsample;
/**
* Created by yarolegovich on 15.05.2016.
*/
public class FillTheFormActivity extends ToolbarActivity {
private Form form = new Form();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
setupToolbar();
| // Path: library/src/main/java/com/yarolegovich/mp/MaterialPreferenceScreen.java
// public class MaterialPreferenceScreen extends ScrollView {
//
// private LinearLayout container;
//
// private UserInputModule userInputModule;
// private StorageModule storageModule;
//
// public MaterialPreferenceScreen(Context context) {
// super(context);
// }
//
// public MaterialPreferenceScreen(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public MaterialPreferenceScreen(Context context, AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// }
//
// @TargetApi(Build.VERSION_CODES.LOLLIPOP)
// public MaterialPreferenceScreen(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
// super(context, attrs, defStyleAttr, defStyleRes);
// }
//
// {
// setFillViewport(true);
// LinearLayout container = new LinearLayout(getContext());
// container.setLayoutParams(new ViewGroup.LayoutParams(
// ViewGroup.LayoutParams.MATCH_PARENT,
// ViewGroup.LayoutParams.WRAP_CONTENT));
// container.setOrientation(LinearLayout.VERTICAL);
// addView(container);
// this.container = container;
// }
//
// public void changeViewsVisibility(List<Integer> viewIds, boolean visible) {
// int visibility = visible ? VISIBLE : GONE;
// changeViewsVisibility(container, viewIds, visibility);
// }
//
// public void setVisibilityController(int controllerId, List<Integer> controlledIds, boolean showWhenChecked) {
// setVisibilityController(
// (AbsMaterialCheckablePreference) findViewById(controllerId),
// controlledIds, showWhenChecked
// );
// }
//
// public void setVisibilityController(
// final AbsMaterialCheckablePreference controller,
// final List<Integer> controlledIds,
// final boolean showWhenChecked) {
// boolean shouldShow = showWhenChecked ? controller.getValue() : !controller.getValue();
// int initialVisibility = shouldShow ? View.VISIBLE : View.GONE;
// changeViewsVisibility(this, controlledIds, initialVisibility);
// controller.addPreferenceClickListener(new OnClickListener() {
// @Override
// public void onClick(View v) {
// boolean shouldShow = showWhenChecked ? controller.getValue() : !controller.getValue();
// int visibility = shouldShow ? View.VISIBLE : View.GONE;
// changeViewsVisibility(MaterialPreferenceScreen.this,
// controlledIds,
// visibility);
// }
// });
// }
//
// private void changeViewsVisibility(ViewGroup container, Collection<Integer> viewIds, int visibility) {
// for (int i = 0; i < container.getChildCount(); i++) {
// View child = container.getChildAt(i);
// if (child instanceof ViewGroup) {
// if (viewIds.contains(child.getId())) {
// child.setVisibility(visibility);
// } else if (!(child instanceof AbsMaterialPreference)) {
// changeViewsVisibility((ViewGroup) child, viewIds, visibility);
// }
// }
// if (viewIds.contains(child.getId())) {
// child.setVisibility(visibility);
// }
// }
// }
//
// UserInputModule getUserInputModule() {
// return userInputModule;
// }
//
// StorageModule getStorageModule() {
// return storageModule;
// }
//
// public void setUserInputModule(UserInputModule userInputModule) {
// this.userInputModule = userInputModule;
// setUserInputModuleRecursively(container, userInputModule);
// }
//
// public void setStorageModule(StorageModule storageModule) {
// this.storageModule = storageModule;
// setStorageModuleRecursively(container, storageModule);
// }
//
// private void setUserInputModuleRecursively(ViewGroup container, UserInputModule module) {
// for (int i = 0; i < container.getChildCount(); i++) {
// View child = container.getChildAt(i);
// if (child instanceof AbsMaterialPreference) {
// ((AbsMaterialPreference) child).setUserInputModule(module);
// } else if (child instanceof ViewGroup) {
// setUserInputModuleRecursively((ViewGroup) child, module);
// }
// }
// }
//
// private void setStorageModuleRecursively(ViewGroup container, StorageModule module) {
// for (int i = 0; i < container.getChildCount(); i++) {
// View child = container.getChildAt(i);
// if (child instanceof AbsMaterialPreference) {
// ((AbsMaterialPreference) child).setStorageModule(module);
// } else if (child instanceof ViewGroup) {
// setStorageModuleRecursively((ViewGroup) child, module);
// }
// }
// }
//
// @Override
// public void addView(View child) {
// if (container != null) {
// container.addView(child);
// } else {
// super.addView(child);
// }
// }
//
// @Override
// public void addView(View child, int index) {
// if (container != null) {
// container.addView(child, index);
// } else {
// super.addView(child, index);
// }
// }
//
// @Override
// public void addView(View child, ViewGroup.LayoutParams params) {
// if (container != null) {
// container.addView(child, params);
// } else {
// super.addView(child, params);
// }
// }
//
// @Override
// public void addView(View child, int index, ViewGroup.LayoutParams params) {
// if (container != null) {
// container.addView(child, index, params);
// } else {
// super.addView(child, index, params);
// }
// }
//
// }
// Path: sample/src/main/java/com/yarolegovich/materialprefsample/FillTheFormActivity.java
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.yarolegovich.mp.MaterialPreferenceScreen;
package com.yarolegovich.materialprefsample;
/**
* Created by yarolegovich on 15.05.2016.
*/
public class FillTheFormActivity extends ToolbarActivity {
private Form form = new Form();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
setupToolbar();
| MaterialPreferenceScreen screen = (MaterialPreferenceScreen) findViewById(R.id.preference_screen); |
yarolegovich/MaterialPreferences | sample/src/main/java/com/yarolegovich/materialprefsample/MainActivity.java | // Path: lovelyinput/src/main/java/com/yarolegovich/lovelyuserinput/LovelyInput.java
// public class LovelyInput implements UserInputModule.Factory {
//
// private Map<String, Integer> keyIconMappings;
// private Map<String, CharSequence> keyTitleMappings;
// private Map<String, CharSequence> keyMessageMappings;
//
// private int color;
//
// private LovelyInput() {
// keyIconMappings = Collections.emptyMap();
// keyTitleMappings = Collections.emptyMap();
// keyMessageMappings = Collections.emptyMap();
// }
//
// @Override
// public UserInputModule create(Context context) {
// return new LovelyInputModule(context)
// .setKeyMessageMapping(keyMessageMappings)
// .setKeyTitleMapping(keyTitleMappings)
// .setKeyIconMappings(keyIconMappings)
// .setTopColor(color);
// }
//
// public static class Builder {
//
// private LovelyInput factory;
//
// public Builder() {
// factory = new LovelyInput();
// }
//
// public Builder setTopColor(@ColorInt int color) {
// factory.color = color;
// return this;
// }
//
// public Builder setKeyTitleMappings(Map<String, CharSequence> mappings) {
// factory.keyTitleMappings = mappings;
// return this;
// }
//
// public Builder setKeyMessageMappings(Map<String, CharSequence> mappings) {
// factory.keyMessageMappings = mappings;
// return this;
// }
//
// public Builder setKeyIconMappings(Map<String, Integer> mappings) {
// factory.keyIconMappings = mappings;
// return this;
// }
//
// public LovelyInput build() {
// return factory;
// }
//
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/MaterialPreferences.java
// public class MaterialPreferences {
//
// private static final MaterialPreferences instance = new MaterialPreferences();
//
// public static MaterialPreferences instance() {
// return instance;
// }
//
// public static UserInputModule getUserInputModule(Context context) {
// return instance.userInputModuleFactory.create(context);
// }
//
// public static StorageModule getStorageModule(Context context) {
// return instance.storageModuleFactory.create(context);
// }
//
// private UserInputModule.Factory userInputModuleFactory;
// private StorageModule.Factory storageModuleFactory;
//
// private MaterialPreferences() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
// public MaterialPreferences setUserInputModule(UserInputModule.Factory factory) {
// userInputModuleFactory = factory;
// return this;
// }
//
// public MaterialPreferences setStorageModule(StorageModule.Factory factory) {
// storageModuleFactory = factory;
// return this;
// }
//
// public void setDefault() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
//
// private static class StandardUserInputFactory implements UserInputModule.Factory {
// @Override
// public UserInputModule create(Context context) {
// return new StandardUserInputModule(context);
// }
// }
// }
| import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.yarolegovich.lovelyuserinput.LovelyInput;
import com.yarolegovich.mp.io.MaterialPreferences;
import java.util.HashMap;
import java.util.Map; | }
@Override
protected void onDestroy() {
super.onDestroy();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.unregisterOnSharedPreferenceChangeListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.pref_form:
startActivity(new Intent(this, FillTheFormActivity.class));
break;
case R.id.pref_configs:
startActivity(new Intent(this, AppConfigsActivity.class));
break;
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(Prefs.keys().KEY_USE_LOVELY)) {
setUserInputModule(sharedPreferences.getBoolean(key, false));
}
}
private void setUserInputModule(boolean shouldUseLovelyModule) {
if (shouldUseLovelyModule) { | // Path: lovelyinput/src/main/java/com/yarolegovich/lovelyuserinput/LovelyInput.java
// public class LovelyInput implements UserInputModule.Factory {
//
// private Map<String, Integer> keyIconMappings;
// private Map<String, CharSequence> keyTitleMappings;
// private Map<String, CharSequence> keyMessageMappings;
//
// private int color;
//
// private LovelyInput() {
// keyIconMappings = Collections.emptyMap();
// keyTitleMappings = Collections.emptyMap();
// keyMessageMappings = Collections.emptyMap();
// }
//
// @Override
// public UserInputModule create(Context context) {
// return new LovelyInputModule(context)
// .setKeyMessageMapping(keyMessageMappings)
// .setKeyTitleMapping(keyTitleMappings)
// .setKeyIconMappings(keyIconMappings)
// .setTopColor(color);
// }
//
// public static class Builder {
//
// private LovelyInput factory;
//
// public Builder() {
// factory = new LovelyInput();
// }
//
// public Builder setTopColor(@ColorInt int color) {
// factory.color = color;
// return this;
// }
//
// public Builder setKeyTitleMappings(Map<String, CharSequence> mappings) {
// factory.keyTitleMappings = mappings;
// return this;
// }
//
// public Builder setKeyMessageMappings(Map<String, CharSequence> mappings) {
// factory.keyMessageMappings = mappings;
// return this;
// }
//
// public Builder setKeyIconMappings(Map<String, Integer> mappings) {
// factory.keyIconMappings = mappings;
// return this;
// }
//
// public LovelyInput build() {
// return factory;
// }
//
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/MaterialPreferences.java
// public class MaterialPreferences {
//
// private static final MaterialPreferences instance = new MaterialPreferences();
//
// public static MaterialPreferences instance() {
// return instance;
// }
//
// public static UserInputModule getUserInputModule(Context context) {
// return instance.userInputModuleFactory.create(context);
// }
//
// public static StorageModule getStorageModule(Context context) {
// return instance.storageModuleFactory.create(context);
// }
//
// private UserInputModule.Factory userInputModuleFactory;
// private StorageModule.Factory storageModuleFactory;
//
// private MaterialPreferences() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
// public MaterialPreferences setUserInputModule(UserInputModule.Factory factory) {
// userInputModuleFactory = factory;
// return this;
// }
//
// public MaterialPreferences setStorageModule(StorageModule.Factory factory) {
// storageModuleFactory = factory;
// return this;
// }
//
// public void setDefault() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
//
// private static class StandardUserInputFactory implements UserInputModule.Factory {
// @Override
// public UserInputModule create(Context context) {
// return new StandardUserInputModule(context);
// }
// }
// }
// Path: sample/src/main/java/com/yarolegovich/materialprefsample/MainActivity.java
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.yarolegovich.lovelyuserinput.LovelyInput;
import com.yarolegovich.mp.io.MaterialPreferences;
import java.util.HashMap;
import java.util.Map;
}
@Override
protected void onDestroy() {
super.onDestroy();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.unregisterOnSharedPreferenceChangeListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.pref_form:
startActivity(new Intent(this, FillTheFormActivity.class));
break;
case R.id.pref_configs:
startActivity(new Intent(this, AppConfigsActivity.class));
break;
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(Prefs.keys().KEY_USE_LOVELY)) {
setUserInputModule(sharedPreferences.getBoolean(key, false));
}
}
private void setUserInputModule(boolean shouldUseLovelyModule) {
if (shouldUseLovelyModule) { | MaterialPreferences.instance().setUserInputModule(createLovelyInputModule()); |
yarolegovich/MaterialPreferences | sample/src/main/java/com/yarolegovich/materialprefsample/MainActivity.java | // Path: lovelyinput/src/main/java/com/yarolegovich/lovelyuserinput/LovelyInput.java
// public class LovelyInput implements UserInputModule.Factory {
//
// private Map<String, Integer> keyIconMappings;
// private Map<String, CharSequence> keyTitleMappings;
// private Map<String, CharSequence> keyMessageMappings;
//
// private int color;
//
// private LovelyInput() {
// keyIconMappings = Collections.emptyMap();
// keyTitleMappings = Collections.emptyMap();
// keyMessageMappings = Collections.emptyMap();
// }
//
// @Override
// public UserInputModule create(Context context) {
// return new LovelyInputModule(context)
// .setKeyMessageMapping(keyMessageMappings)
// .setKeyTitleMapping(keyTitleMappings)
// .setKeyIconMappings(keyIconMappings)
// .setTopColor(color);
// }
//
// public static class Builder {
//
// private LovelyInput factory;
//
// public Builder() {
// factory = new LovelyInput();
// }
//
// public Builder setTopColor(@ColorInt int color) {
// factory.color = color;
// return this;
// }
//
// public Builder setKeyTitleMappings(Map<String, CharSequence> mappings) {
// factory.keyTitleMappings = mappings;
// return this;
// }
//
// public Builder setKeyMessageMappings(Map<String, CharSequence> mappings) {
// factory.keyMessageMappings = mappings;
// return this;
// }
//
// public Builder setKeyIconMappings(Map<String, Integer> mappings) {
// factory.keyIconMappings = mappings;
// return this;
// }
//
// public LovelyInput build() {
// return factory;
// }
//
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/MaterialPreferences.java
// public class MaterialPreferences {
//
// private static final MaterialPreferences instance = new MaterialPreferences();
//
// public static MaterialPreferences instance() {
// return instance;
// }
//
// public static UserInputModule getUserInputModule(Context context) {
// return instance.userInputModuleFactory.create(context);
// }
//
// public static StorageModule getStorageModule(Context context) {
// return instance.storageModuleFactory.create(context);
// }
//
// private UserInputModule.Factory userInputModuleFactory;
// private StorageModule.Factory storageModuleFactory;
//
// private MaterialPreferences() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
// public MaterialPreferences setUserInputModule(UserInputModule.Factory factory) {
// userInputModuleFactory = factory;
// return this;
// }
//
// public MaterialPreferences setStorageModule(StorageModule.Factory factory) {
// storageModuleFactory = factory;
// return this;
// }
//
// public void setDefault() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
//
// private static class StandardUserInputFactory implements UserInputModule.Factory {
// @Override
// public UserInputModule create(Context context) {
// return new StandardUserInputModule(context);
// }
// }
// }
| import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.yarolegovich.lovelyuserinput.LovelyInput;
import com.yarolegovich.mp.io.MaterialPreferences;
import java.util.HashMap;
import java.util.Map; | prefs.unregisterOnSharedPreferenceChangeListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.pref_form:
startActivity(new Intent(this, FillTheFormActivity.class));
break;
case R.id.pref_configs:
startActivity(new Intent(this, AppConfigsActivity.class));
break;
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(Prefs.keys().KEY_USE_LOVELY)) {
setUserInputModule(sharedPreferences.getBoolean(key, false));
}
}
private void setUserInputModule(boolean shouldUseLovelyModule) {
if (shouldUseLovelyModule) {
MaterialPreferences.instance().setUserInputModule(createLovelyInputModule());
} else {
MaterialPreferences.instance().setDefault();
}
}
| // Path: lovelyinput/src/main/java/com/yarolegovich/lovelyuserinput/LovelyInput.java
// public class LovelyInput implements UserInputModule.Factory {
//
// private Map<String, Integer> keyIconMappings;
// private Map<String, CharSequence> keyTitleMappings;
// private Map<String, CharSequence> keyMessageMappings;
//
// private int color;
//
// private LovelyInput() {
// keyIconMappings = Collections.emptyMap();
// keyTitleMappings = Collections.emptyMap();
// keyMessageMappings = Collections.emptyMap();
// }
//
// @Override
// public UserInputModule create(Context context) {
// return new LovelyInputModule(context)
// .setKeyMessageMapping(keyMessageMappings)
// .setKeyTitleMapping(keyTitleMappings)
// .setKeyIconMappings(keyIconMappings)
// .setTopColor(color);
// }
//
// public static class Builder {
//
// private LovelyInput factory;
//
// public Builder() {
// factory = new LovelyInput();
// }
//
// public Builder setTopColor(@ColorInt int color) {
// factory.color = color;
// return this;
// }
//
// public Builder setKeyTitleMappings(Map<String, CharSequence> mappings) {
// factory.keyTitleMappings = mappings;
// return this;
// }
//
// public Builder setKeyMessageMappings(Map<String, CharSequence> mappings) {
// factory.keyMessageMappings = mappings;
// return this;
// }
//
// public Builder setKeyIconMappings(Map<String, Integer> mappings) {
// factory.keyIconMappings = mappings;
// return this;
// }
//
// public LovelyInput build() {
// return factory;
// }
//
// }
// }
//
// Path: library/src/main/java/com/yarolegovich/mp/io/MaterialPreferences.java
// public class MaterialPreferences {
//
// private static final MaterialPreferences instance = new MaterialPreferences();
//
// public static MaterialPreferences instance() {
// return instance;
// }
//
// public static UserInputModule getUserInputModule(Context context) {
// return instance.userInputModuleFactory.create(context);
// }
//
// public static StorageModule getStorageModule(Context context) {
// return instance.storageModuleFactory.create(context);
// }
//
// private UserInputModule.Factory userInputModuleFactory;
// private StorageModule.Factory storageModuleFactory;
//
// private MaterialPreferences() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
// public MaterialPreferences setUserInputModule(UserInputModule.Factory factory) {
// userInputModuleFactory = factory;
// return this;
// }
//
// public MaterialPreferences setStorageModule(StorageModule.Factory factory) {
// storageModuleFactory = factory;
// return this;
// }
//
// public void setDefault() {
// userInputModuleFactory = new StandardUserInputFactory();
// storageModuleFactory = new SharedPrefsStorageFactory(null);
// }
//
//
// private static class StandardUserInputFactory implements UserInputModule.Factory {
// @Override
// public UserInputModule create(Context context) {
// return new StandardUserInputModule(context);
// }
// }
// }
// Path: sample/src/main/java/com/yarolegovich/materialprefsample/MainActivity.java
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.yarolegovich.lovelyuserinput.LovelyInput;
import com.yarolegovich.mp.io.MaterialPreferences;
import java.util.HashMap;
import java.util.Map;
prefs.unregisterOnSharedPreferenceChangeListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.pref_form:
startActivity(new Intent(this, FillTheFormActivity.class));
break;
case R.id.pref_configs:
startActivity(new Intent(this, AppConfigsActivity.class));
break;
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(Prefs.keys().KEY_USE_LOVELY)) {
setUserInputModule(sharedPreferences.getBoolean(key, false));
}
}
private void setUserInputModule(boolean shouldUseLovelyModule) {
if (shouldUseLovelyModule) {
MaterialPreferences.instance().setUserInputModule(createLovelyInputModule());
} else {
MaterialPreferences.instance().setDefault();
}
}
| private LovelyInput createLovelyInputModule() { |
yarolegovich/MaterialPreferences | sample/src/main/java/com/yarolegovich/materialprefsample/AppConfigsActivity.java | // Path: library/src/main/java/com/yarolegovich/mp/MaterialPreferenceScreen.java
// public class MaterialPreferenceScreen extends ScrollView {
//
// private LinearLayout container;
//
// private UserInputModule userInputModule;
// private StorageModule storageModule;
//
// public MaterialPreferenceScreen(Context context) {
// super(context);
// }
//
// public MaterialPreferenceScreen(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public MaterialPreferenceScreen(Context context, AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// }
//
// @TargetApi(Build.VERSION_CODES.LOLLIPOP)
// public MaterialPreferenceScreen(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
// super(context, attrs, defStyleAttr, defStyleRes);
// }
//
// {
// setFillViewport(true);
// LinearLayout container = new LinearLayout(getContext());
// container.setLayoutParams(new ViewGroup.LayoutParams(
// ViewGroup.LayoutParams.MATCH_PARENT,
// ViewGroup.LayoutParams.WRAP_CONTENT));
// container.setOrientation(LinearLayout.VERTICAL);
// addView(container);
// this.container = container;
// }
//
// public void changeViewsVisibility(List<Integer> viewIds, boolean visible) {
// int visibility = visible ? VISIBLE : GONE;
// changeViewsVisibility(container, viewIds, visibility);
// }
//
// public void setVisibilityController(int controllerId, List<Integer> controlledIds, boolean showWhenChecked) {
// setVisibilityController(
// (AbsMaterialCheckablePreference) findViewById(controllerId),
// controlledIds, showWhenChecked
// );
// }
//
// public void setVisibilityController(
// final AbsMaterialCheckablePreference controller,
// final List<Integer> controlledIds,
// final boolean showWhenChecked) {
// boolean shouldShow = showWhenChecked ? controller.getValue() : !controller.getValue();
// int initialVisibility = shouldShow ? View.VISIBLE : View.GONE;
// changeViewsVisibility(this, controlledIds, initialVisibility);
// controller.addPreferenceClickListener(new OnClickListener() {
// @Override
// public void onClick(View v) {
// boolean shouldShow = showWhenChecked ? controller.getValue() : !controller.getValue();
// int visibility = shouldShow ? View.VISIBLE : View.GONE;
// changeViewsVisibility(MaterialPreferenceScreen.this,
// controlledIds,
// visibility);
// }
// });
// }
//
// private void changeViewsVisibility(ViewGroup container, Collection<Integer> viewIds, int visibility) {
// for (int i = 0; i < container.getChildCount(); i++) {
// View child = container.getChildAt(i);
// if (child instanceof ViewGroup) {
// if (viewIds.contains(child.getId())) {
// child.setVisibility(visibility);
// } else if (!(child instanceof AbsMaterialPreference)) {
// changeViewsVisibility((ViewGroup) child, viewIds, visibility);
// }
// }
// if (viewIds.contains(child.getId())) {
// child.setVisibility(visibility);
// }
// }
// }
//
// UserInputModule getUserInputModule() {
// return userInputModule;
// }
//
// StorageModule getStorageModule() {
// return storageModule;
// }
//
// public void setUserInputModule(UserInputModule userInputModule) {
// this.userInputModule = userInputModule;
// setUserInputModuleRecursively(container, userInputModule);
// }
//
// public void setStorageModule(StorageModule storageModule) {
// this.storageModule = storageModule;
// setStorageModuleRecursively(container, storageModule);
// }
//
// private void setUserInputModuleRecursively(ViewGroup container, UserInputModule module) {
// for (int i = 0; i < container.getChildCount(); i++) {
// View child = container.getChildAt(i);
// if (child instanceof AbsMaterialPreference) {
// ((AbsMaterialPreference) child).setUserInputModule(module);
// } else if (child instanceof ViewGroup) {
// setUserInputModuleRecursively((ViewGroup) child, module);
// }
// }
// }
//
// private void setStorageModuleRecursively(ViewGroup container, StorageModule module) {
// for (int i = 0; i < container.getChildCount(); i++) {
// View child = container.getChildAt(i);
// if (child instanceof AbsMaterialPreference) {
// ((AbsMaterialPreference) child).setStorageModule(module);
// } else if (child instanceof ViewGroup) {
// setStorageModuleRecursively((ViewGroup) child, module);
// }
// }
// }
//
// @Override
// public void addView(View child) {
// if (container != null) {
// container.addView(child);
// } else {
// super.addView(child);
// }
// }
//
// @Override
// public void addView(View child, int index) {
// if (container != null) {
// container.addView(child, index);
// } else {
// super.addView(child, index);
// }
// }
//
// @Override
// public void addView(View child, ViewGroup.LayoutParams params) {
// if (container != null) {
// container.addView(child, params);
// } else {
// super.addView(child, params);
// }
// }
//
// @Override
// public void addView(View child, int index, ViewGroup.LayoutParams params) {
// if (container != null) {
// container.addView(child, index, params);
// } else {
// super.addView(child, index, params);
// }
// }
//
// }
| import android.os.Bundle;
import com.yarolegovich.mp.MaterialPreferenceScreen;
import java.util.Collections; | package com.yarolegovich.materialprefsample;
/**
* Created by yarolegovich on 15.05.2016.
*/
public class AppConfigsActivity extends ToolbarActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_config);
setupToolbar();
| // Path: library/src/main/java/com/yarolegovich/mp/MaterialPreferenceScreen.java
// public class MaterialPreferenceScreen extends ScrollView {
//
// private LinearLayout container;
//
// private UserInputModule userInputModule;
// private StorageModule storageModule;
//
// public MaterialPreferenceScreen(Context context) {
// super(context);
// }
//
// public MaterialPreferenceScreen(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public MaterialPreferenceScreen(Context context, AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// }
//
// @TargetApi(Build.VERSION_CODES.LOLLIPOP)
// public MaterialPreferenceScreen(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
// super(context, attrs, defStyleAttr, defStyleRes);
// }
//
// {
// setFillViewport(true);
// LinearLayout container = new LinearLayout(getContext());
// container.setLayoutParams(new ViewGroup.LayoutParams(
// ViewGroup.LayoutParams.MATCH_PARENT,
// ViewGroup.LayoutParams.WRAP_CONTENT));
// container.setOrientation(LinearLayout.VERTICAL);
// addView(container);
// this.container = container;
// }
//
// public void changeViewsVisibility(List<Integer> viewIds, boolean visible) {
// int visibility = visible ? VISIBLE : GONE;
// changeViewsVisibility(container, viewIds, visibility);
// }
//
// public void setVisibilityController(int controllerId, List<Integer> controlledIds, boolean showWhenChecked) {
// setVisibilityController(
// (AbsMaterialCheckablePreference) findViewById(controllerId),
// controlledIds, showWhenChecked
// );
// }
//
// public void setVisibilityController(
// final AbsMaterialCheckablePreference controller,
// final List<Integer> controlledIds,
// final boolean showWhenChecked) {
// boolean shouldShow = showWhenChecked ? controller.getValue() : !controller.getValue();
// int initialVisibility = shouldShow ? View.VISIBLE : View.GONE;
// changeViewsVisibility(this, controlledIds, initialVisibility);
// controller.addPreferenceClickListener(new OnClickListener() {
// @Override
// public void onClick(View v) {
// boolean shouldShow = showWhenChecked ? controller.getValue() : !controller.getValue();
// int visibility = shouldShow ? View.VISIBLE : View.GONE;
// changeViewsVisibility(MaterialPreferenceScreen.this,
// controlledIds,
// visibility);
// }
// });
// }
//
// private void changeViewsVisibility(ViewGroup container, Collection<Integer> viewIds, int visibility) {
// for (int i = 0; i < container.getChildCount(); i++) {
// View child = container.getChildAt(i);
// if (child instanceof ViewGroup) {
// if (viewIds.contains(child.getId())) {
// child.setVisibility(visibility);
// } else if (!(child instanceof AbsMaterialPreference)) {
// changeViewsVisibility((ViewGroup) child, viewIds, visibility);
// }
// }
// if (viewIds.contains(child.getId())) {
// child.setVisibility(visibility);
// }
// }
// }
//
// UserInputModule getUserInputModule() {
// return userInputModule;
// }
//
// StorageModule getStorageModule() {
// return storageModule;
// }
//
// public void setUserInputModule(UserInputModule userInputModule) {
// this.userInputModule = userInputModule;
// setUserInputModuleRecursively(container, userInputModule);
// }
//
// public void setStorageModule(StorageModule storageModule) {
// this.storageModule = storageModule;
// setStorageModuleRecursively(container, storageModule);
// }
//
// private void setUserInputModuleRecursively(ViewGroup container, UserInputModule module) {
// for (int i = 0; i < container.getChildCount(); i++) {
// View child = container.getChildAt(i);
// if (child instanceof AbsMaterialPreference) {
// ((AbsMaterialPreference) child).setUserInputModule(module);
// } else if (child instanceof ViewGroup) {
// setUserInputModuleRecursively((ViewGroup) child, module);
// }
// }
// }
//
// private void setStorageModuleRecursively(ViewGroup container, StorageModule module) {
// for (int i = 0; i < container.getChildCount(); i++) {
// View child = container.getChildAt(i);
// if (child instanceof AbsMaterialPreference) {
// ((AbsMaterialPreference) child).setStorageModule(module);
// } else if (child instanceof ViewGroup) {
// setStorageModuleRecursively((ViewGroup) child, module);
// }
// }
// }
//
// @Override
// public void addView(View child) {
// if (container != null) {
// container.addView(child);
// } else {
// super.addView(child);
// }
// }
//
// @Override
// public void addView(View child, int index) {
// if (container != null) {
// container.addView(child, index);
// } else {
// super.addView(child, index);
// }
// }
//
// @Override
// public void addView(View child, ViewGroup.LayoutParams params) {
// if (container != null) {
// container.addView(child, params);
// } else {
// super.addView(child, params);
// }
// }
//
// @Override
// public void addView(View child, int index, ViewGroup.LayoutParams params) {
// if (container != null) {
// container.addView(child, index, params);
// } else {
// super.addView(child, index, params);
// }
// }
//
// }
// Path: sample/src/main/java/com/yarolegovich/materialprefsample/AppConfigsActivity.java
import android.os.Bundle;
import com.yarolegovich.mp.MaterialPreferenceScreen;
import java.util.Collections;
package com.yarolegovich.materialprefsample;
/**
* Created by yarolegovich on 15.05.2016.
*/
public class AppConfigsActivity extends ToolbarActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_config);
setupToolbar();
| MaterialPreferenceScreen screen = (MaterialPreferenceScreen) findViewById(R.id.preference_screen); |
yarolegovich/MaterialPreferences | library/src/main/java/com/yarolegovich/mp/MaterialChoicePreference.java | // Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
| import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import com.yarolegovich.mp.io.StorageModule; | package com.yarolegovich.mp;
/**
* Created by yarolegovich on 01.05.2016.
*/
public class MaterialChoicePreference extends AbsMaterialListPreference<String> {
public MaterialChoicePreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MaterialChoicePreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MaterialChoicePreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public String getValue() {
return storageModule.getString(key, defaultValue);
}
@Override
public void setValue(String value) {
storageModule.saveString(key, value);
showNewValueIfNeeded(toRepresentation(value));
}
@Override | // Path: library/src/main/java/com/yarolegovich/mp/io/StorageModule.java
// public interface StorageModule {
//
// void saveBoolean(String key, boolean value);
//
// void saveString(String key, String value);
//
// void saveInt(String key, int value);
//
// void saveStringSet(String key, Set<String> value);
//
// boolean getBoolean(String key, boolean defaultVal);
//
// String getString(String key, String defaultVal);
//
// int getInt(String key, int defaultVal);
//
// Set<String> getStringSet(String key, Set<String> defaultVal);
//
// void onSaveInstanceState(Bundle outState);
//
// void onRestoreInstanceState(Bundle savedState);
//
// interface Factory {
// StorageModule create(Context context);
// }
// }
// Path: library/src/main/java/com/yarolegovich/mp/MaterialChoicePreference.java
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import com.yarolegovich.mp.io.StorageModule;
package com.yarolegovich.mp;
/**
* Created by yarolegovich on 01.05.2016.
*/
public class MaterialChoicePreference extends AbsMaterialListPreference<String> {
public MaterialChoicePreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MaterialChoicePreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MaterialChoicePreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public String getValue() {
return storageModule.getString(key, defaultValue);
}
@Override
public void setValue(String value) {
storageModule.saveString(key, value);
showNewValueIfNeeded(toRepresentation(value));
}
@Override | public void setStorageModule(StorageModule storageModule) { |
dmpe/JavaFX | src/james/AvcHmi.java | // Path: src/james/DataSource.java
// public class DataSource {
// Map<String, String> dataMap = new HashMap<>();
//
// public DataSource() {
// dataMap.put("key1", "value1");
// dataMap.put("key2", "value2");
// dataMap.put("key3", "value3");
// }
//
// public Map<String, String> getDataMap() {
// Random generator = new Random();
// int randInt = generator.nextInt();
// dataMap.put("key1", "value" + randInt);
// return dataMap;
// }
// }
| import james.DataSource;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.stage.Stage; | package james;
public class AvcHmi extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
Text t = new Text(10, 50,
"Replace/update this text periodically with data");
Group root = new Group();
root.getChildren().add(t);
primaryStage.setScene(new Scene(root, 400, 300));
primaryStage.show();
new Thread() { | // Path: src/james/DataSource.java
// public class DataSource {
// Map<String, String> dataMap = new HashMap<>();
//
// public DataSource() {
// dataMap.put("key1", "value1");
// dataMap.put("key2", "value2");
// dataMap.put("key3", "value3");
// }
//
// public Map<String, String> getDataMap() {
// Random generator = new Random();
// int randInt = generator.nextInt();
// dataMap.put("key1", "value" + randInt);
// return dataMap;
// }
// }
// Path: src/james/AvcHmi.java
import james.DataSource;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.stage.Stage;
package james;
public class AvcHmi extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
Text t = new Text(10, 50,
"Replace/update this text periodically with data");
Group root = new Group();
root.getChildren().add(t);
primaryStage.setScene(new Scene(root, 400, 300));
primaryStage.show();
new Thread() { | private DataSource dataSource = new DataSource(); |
conveyal/transit-wand | server/app/models/transit/Route.java | // Path: server/app/models/Phone.java
// @Entity
// public class Phone extends Model {
//
// public String imei;
//
// public String unitId;
//
// public String userName;
//
// public Date registeredOn;
//
// public static Phone registerImei(String imei, String userName) {
//
// // check for existing imei record
// Phone phone = Phone.find("imei = ?", imei).first();
// if(phone != null)
// return phone;
//
// // create a new record
//
// phone = new Phone();
//
// // generate "random" six digit unit ID
// Random generator = new Random();
// generator.setSeed(System.currentTimeMillis());
//
// Integer id = 0;
//
// do {
// id = generator.nextInt(899999) + 100000;
// } while(Phone.count("unitId = ?", id.toString()) > 0);
//
// phone.unitId = id.toString();
// phone.imei = imei;
// phone.userName = userName;
// phone.registeredOn = new Date();
//
// phone.save();
//
// return phone.save();
// }
//
// }
| import java.math.BigInteger;
import java.util.Date;
import javax.persistence.EntityManager;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.ManyToOne;
import javax.persistence.Entity;
import javax.persistence.Query;
import models.Phone;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.hibernate.annotations.Type;
import com.vividsolutions.jts.geom.MultiLineString;
import play.db.jpa.Model; | package models.transit;
@JsonIgnoreProperties({"entityId", "persistent"})
@Entity
public class Route extends Model {
public String gtfsRouteId;
public String routeShortName;
public String routeLongName;
public String routeDesc;
public String routeNotes;
@Enumerated(EnumType.STRING)
public RouteType routeType;
public String routeUrl;
public String routeColor;
public String routeTextColor;
public String vehicleCapacity;
public String vehicleType;
public Date captureTime;
// Custom Fields
public Boolean airCon;
public String comments;
public Boolean weekday;
public Boolean saturday;
public Boolean sunday;
@ManyToOne
public Agency agency;
@ManyToOne | // Path: server/app/models/Phone.java
// @Entity
// public class Phone extends Model {
//
// public String imei;
//
// public String unitId;
//
// public String userName;
//
// public Date registeredOn;
//
// public static Phone registerImei(String imei, String userName) {
//
// // check for existing imei record
// Phone phone = Phone.find("imei = ?", imei).first();
// if(phone != null)
// return phone;
//
// // create a new record
//
// phone = new Phone();
//
// // generate "random" six digit unit ID
// Random generator = new Random();
// generator.setSeed(System.currentTimeMillis());
//
// Integer id = 0;
//
// do {
// id = generator.nextInt(899999) + 100000;
// } while(Phone.count("unitId = ?", id.toString()) > 0);
//
// phone.unitId = id.toString();
// phone.imei = imei;
// phone.userName = userName;
// phone.registeredOn = new Date();
//
// phone.save();
//
// return phone.save();
// }
//
// }
// Path: server/app/models/transit/Route.java
import java.math.BigInteger;
import java.util.Date;
import javax.persistence.EntityManager;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.ManyToOne;
import javax.persistence.Entity;
import javax.persistence.Query;
import models.Phone;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.hibernate.annotations.Type;
import com.vividsolutions.jts.geom.MultiLineString;
import play.db.jpa.Model;
package models.transit;
@JsonIgnoreProperties({"entityId", "persistent"})
@Entity
public class Route extends Model {
public String gtfsRouteId;
public String routeShortName;
public String routeLongName;
public String routeDesc;
public String routeNotes;
@Enumerated(EnumType.STRING)
public RouteType routeType;
public String routeUrl;
public String routeColor;
public String routeTextColor;
public String vehicleCapacity;
public String vehicleType;
public Date captureTime;
// Custom Fields
public Boolean airCon;
public String comments;
public Boolean weekday;
public Boolean saturday;
public Boolean sunday;
@ManyToOne
public Agency agency;
@ManyToOne | public Phone phone; |
TreyRuffy/CommandBlocker | Command Blocker Bukkit/src/main/java/me/treyruffy/commandblocker/bukkit/listeners/NewTabCompletionListener.java | // Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/MethodInterface.java
// public interface MethodInterface {
//
// Object getPlugin();
//
// Object getConfig();
// Object getDisabledCommandsConfig();
// Object getMessagesConfig();
// Object getOpBlockConfig();
//
// void saveConfig();
// void saveDisabledCommandsConfig();
// void saveMessagesConfig();
// void saveOpBlockConfig();
//
// File getConfigFile(Object configurationFile);
//
// String getVersion();
//
// String getServerType();
//
// File getDataFolder();
//
// void setupMetrics();
//
// void executeCommand(String cmd);
//
// void sendMessage(Object commandSender, Component message);
//
// List<String> getOldMessages(String category, String message);
// List<String> getOldMessages(String category, String message, Object configurationFile);
//
// Character getChatComponentChar();
//
// String getOldMessage(String category, String message);
// String getOldMessage(String category, String message, Object configurationFile);
//
// void log(String msg);
// }
//
// Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/Universal.java
// public class Universal {
//
// private static Universal instance = null;
// private MethodInterface mi;
//
// public static Universal get() {
// return instance == null ? instance = new Universal() : instance;
// }
//
// public void setup(MethodInterface mi) {
// this.mi = mi;
//
// mi.setupMetrics();
// }
//
// public MethodInterface getMethods() {
// return mi;
// }
//
// }
| import me.treyruffy.commandblocker.MethodInterface;
import me.treyruffy.commandblocker.Universal;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandSendEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects; | package me.treyruffy.commandblocker.bukkit.listeners;
public class NewTabCompletionListener implements Listener {
@EventHandler
public void onTabComplete(PlayerCommandSendEvent e) { | // Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/MethodInterface.java
// public interface MethodInterface {
//
// Object getPlugin();
//
// Object getConfig();
// Object getDisabledCommandsConfig();
// Object getMessagesConfig();
// Object getOpBlockConfig();
//
// void saveConfig();
// void saveDisabledCommandsConfig();
// void saveMessagesConfig();
// void saveOpBlockConfig();
//
// File getConfigFile(Object configurationFile);
//
// String getVersion();
//
// String getServerType();
//
// File getDataFolder();
//
// void setupMetrics();
//
// void executeCommand(String cmd);
//
// void sendMessage(Object commandSender, Component message);
//
// List<String> getOldMessages(String category, String message);
// List<String> getOldMessages(String category, String message, Object configurationFile);
//
// Character getChatComponentChar();
//
// String getOldMessage(String category, String message);
// String getOldMessage(String category, String message, Object configurationFile);
//
// void log(String msg);
// }
//
// Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/Universal.java
// public class Universal {
//
// private static Universal instance = null;
// private MethodInterface mi;
//
// public static Universal get() {
// return instance == null ? instance = new Universal() : instance;
// }
//
// public void setup(MethodInterface mi) {
// this.mi = mi;
//
// mi.setupMetrics();
// }
//
// public MethodInterface getMethods() {
// return mi;
// }
//
// }
// Path: Command Blocker Bukkit/src/main/java/me/treyruffy/commandblocker/bukkit/listeners/NewTabCompletionListener.java
import me.treyruffy.commandblocker.MethodInterface;
import me.treyruffy.commandblocker.Universal;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandSendEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
package me.treyruffy.commandblocker.bukkit.listeners;
public class NewTabCompletionListener implements Listener {
@EventHandler
public void onTabComplete(PlayerCommandSendEvent e) { | MethodInterface mi = Universal.get().getMethods(); |
TreyRuffy/CommandBlocker | Command Blocker Bukkit/src/main/java/me/treyruffy/commandblocker/bukkit/listeners/NewTabCompletionListener.java | // Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/MethodInterface.java
// public interface MethodInterface {
//
// Object getPlugin();
//
// Object getConfig();
// Object getDisabledCommandsConfig();
// Object getMessagesConfig();
// Object getOpBlockConfig();
//
// void saveConfig();
// void saveDisabledCommandsConfig();
// void saveMessagesConfig();
// void saveOpBlockConfig();
//
// File getConfigFile(Object configurationFile);
//
// String getVersion();
//
// String getServerType();
//
// File getDataFolder();
//
// void setupMetrics();
//
// void executeCommand(String cmd);
//
// void sendMessage(Object commandSender, Component message);
//
// List<String> getOldMessages(String category, String message);
// List<String> getOldMessages(String category, String message, Object configurationFile);
//
// Character getChatComponentChar();
//
// String getOldMessage(String category, String message);
// String getOldMessage(String category, String message, Object configurationFile);
//
// void log(String msg);
// }
//
// Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/Universal.java
// public class Universal {
//
// private static Universal instance = null;
// private MethodInterface mi;
//
// public static Universal get() {
// return instance == null ? instance = new Universal() : instance;
// }
//
// public void setup(MethodInterface mi) {
// this.mi = mi;
//
// mi.setupMetrics();
// }
//
// public MethodInterface getMethods() {
// return mi;
// }
//
// }
| import me.treyruffy.commandblocker.MethodInterface;
import me.treyruffy.commandblocker.Universal;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandSendEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects; | package me.treyruffy.commandblocker.bukkit.listeners;
public class NewTabCompletionListener implements Listener {
@EventHandler
public void onTabComplete(PlayerCommandSendEvent e) { | // Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/MethodInterface.java
// public interface MethodInterface {
//
// Object getPlugin();
//
// Object getConfig();
// Object getDisabledCommandsConfig();
// Object getMessagesConfig();
// Object getOpBlockConfig();
//
// void saveConfig();
// void saveDisabledCommandsConfig();
// void saveMessagesConfig();
// void saveOpBlockConfig();
//
// File getConfigFile(Object configurationFile);
//
// String getVersion();
//
// String getServerType();
//
// File getDataFolder();
//
// void setupMetrics();
//
// void executeCommand(String cmd);
//
// void sendMessage(Object commandSender, Component message);
//
// List<String> getOldMessages(String category, String message);
// List<String> getOldMessages(String category, String message, Object configurationFile);
//
// Character getChatComponentChar();
//
// String getOldMessage(String category, String message);
// String getOldMessage(String category, String message, Object configurationFile);
//
// void log(String msg);
// }
//
// Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/Universal.java
// public class Universal {
//
// private static Universal instance = null;
// private MethodInterface mi;
//
// public static Universal get() {
// return instance == null ? instance = new Universal() : instance;
// }
//
// public void setup(MethodInterface mi) {
// this.mi = mi;
//
// mi.setupMetrics();
// }
//
// public MethodInterface getMethods() {
// return mi;
// }
//
// }
// Path: Command Blocker Bukkit/src/main/java/me/treyruffy/commandblocker/bukkit/listeners/NewTabCompletionListener.java
import me.treyruffy.commandblocker.MethodInterface;
import me.treyruffy.commandblocker.Universal;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandSendEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
package me.treyruffy.commandblocker.bukkit.listeners;
public class NewTabCompletionListener implements Listener {
@EventHandler
public void onTabComplete(PlayerCommandSendEvent e) { | MethodInterface mi = Universal.get().getMethods(); |
TreyRuffy/CommandBlocker | Command Blocker Bungee/src/main/java/me/treyruffy/commandblocker/bungeecord/listeners/TabCompletion.java | // Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/MethodInterface.java
// public interface MethodInterface {
//
// Object getPlugin();
//
// Object getConfig();
// Object getDisabledCommandsConfig();
// Object getMessagesConfig();
// Object getOpBlockConfig();
//
// void saveConfig();
// void saveDisabledCommandsConfig();
// void saveMessagesConfig();
// void saveOpBlockConfig();
//
// File getConfigFile(Object configurationFile);
//
// String getVersion();
//
// String getServerType();
//
// File getDataFolder();
//
// void setupMetrics();
//
// void executeCommand(String cmd);
//
// void sendMessage(Object commandSender, Component message);
//
// List<String> getOldMessages(String category, String message);
// List<String> getOldMessages(String category, String message, Object configurationFile);
//
// Character getChatComponentChar();
//
// String getOldMessage(String category, String message);
// String getOldMessage(String category, String message, Object configurationFile);
//
// void log(String msg);
// }
//
// Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/Universal.java
// public class Universal {
//
// private static Universal instance = null;
// private MethodInterface mi;
//
// public static Universal get() {
// return instance == null ? instance = new Universal() : instance;
// }
//
// public void setup(MethodInterface mi) {
// this.mi = mi;
//
// mi.setupMetrics();
// }
//
// public MethodInterface getMethods() {
// return mi;
// }
//
// }
| import me.treyruffy.commandblocker.MethodInterface;
import me.treyruffy.commandblocker.Universal;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.TabCompleteEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.event.EventHandler;
import net.md_5.bungee.event.EventPriority; | package me.treyruffy.commandblocker.bungeecord.listeners;
public class TabCompletion implements Listener {
@EventHandler (priority = EventPriority.HIGHEST)
public void onTabComplete(TabCompleteEvent e) {
if (!(e.getSender() instanceof ProxiedPlayer)) {
return;
} | // Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/MethodInterface.java
// public interface MethodInterface {
//
// Object getPlugin();
//
// Object getConfig();
// Object getDisabledCommandsConfig();
// Object getMessagesConfig();
// Object getOpBlockConfig();
//
// void saveConfig();
// void saveDisabledCommandsConfig();
// void saveMessagesConfig();
// void saveOpBlockConfig();
//
// File getConfigFile(Object configurationFile);
//
// String getVersion();
//
// String getServerType();
//
// File getDataFolder();
//
// void setupMetrics();
//
// void executeCommand(String cmd);
//
// void sendMessage(Object commandSender, Component message);
//
// List<String> getOldMessages(String category, String message);
// List<String> getOldMessages(String category, String message, Object configurationFile);
//
// Character getChatComponentChar();
//
// String getOldMessage(String category, String message);
// String getOldMessage(String category, String message, Object configurationFile);
//
// void log(String msg);
// }
//
// Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/Universal.java
// public class Universal {
//
// private static Universal instance = null;
// private MethodInterface mi;
//
// public static Universal get() {
// return instance == null ? instance = new Universal() : instance;
// }
//
// public void setup(MethodInterface mi) {
// this.mi = mi;
//
// mi.setupMetrics();
// }
//
// public MethodInterface getMethods() {
// return mi;
// }
//
// }
// Path: Command Blocker Bungee/src/main/java/me/treyruffy/commandblocker/bungeecord/listeners/TabCompletion.java
import me.treyruffy.commandblocker.MethodInterface;
import me.treyruffy.commandblocker.Universal;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.TabCompleteEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.event.EventHandler;
import net.md_5.bungee.event.EventPriority;
package me.treyruffy.commandblocker.bungeecord.listeners;
public class TabCompletion implements Listener {
@EventHandler (priority = EventPriority.HIGHEST)
public void onTabComplete(TabCompleteEvent e) {
if (!(e.getSender() instanceof ProxiedPlayer)) {
return;
} | MethodInterface mi = Universal.get().getMethods(); |
TreyRuffy/CommandBlocker | Command Blocker Bungee/src/main/java/me/treyruffy/commandblocker/bungeecord/listeners/TabCompletion.java | // Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/MethodInterface.java
// public interface MethodInterface {
//
// Object getPlugin();
//
// Object getConfig();
// Object getDisabledCommandsConfig();
// Object getMessagesConfig();
// Object getOpBlockConfig();
//
// void saveConfig();
// void saveDisabledCommandsConfig();
// void saveMessagesConfig();
// void saveOpBlockConfig();
//
// File getConfigFile(Object configurationFile);
//
// String getVersion();
//
// String getServerType();
//
// File getDataFolder();
//
// void setupMetrics();
//
// void executeCommand(String cmd);
//
// void sendMessage(Object commandSender, Component message);
//
// List<String> getOldMessages(String category, String message);
// List<String> getOldMessages(String category, String message, Object configurationFile);
//
// Character getChatComponentChar();
//
// String getOldMessage(String category, String message);
// String getOldMessage(String category, String message, Object configurationFile);
//
// void log(String msg);
// }
//
// Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/Universal.java
// public class Universal {
//
// private static Universal instance = null;
// private MethodInterface mi;
//
// public static Universal get() {
// return instance == null ? instance = new Universal() : instance;
// }
//
// public void setup(MethodInterface mi) {
// this.mi = mi;
//
// mi.setupMetrics();
// }
//
// public MethodInterface getMethods() {
// return mi;
// }
//
// }
| import me.treyruffy.commandblocker.MethodInterface;
import me.treyruffy.commandblocker.Universal;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.TabCompleteEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.event.EventHandler;
import net.md_5.bungee.event.EventPriority; | package me.treyruffy.commandblocker.bungeecord.listeners;
public class TabCompletion implements Listener {
@EventHandler (priority = EventPriority.HIGHEST)
public void onTabComplete(TabCompleteEvent e) {
if (!(e.getSender() instanceof ProxiedPlayer)) {
return;
} | // Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/MethodInterface.java
// public interface MethodInterface {
//
// Object getPlugin();
//
// Object getConfig();
// Object getDisabledCommandsConfig();
// Object getMessagesConfig();
// Object getOpBlockConfig();
//
// void saveConfig();
// void saveDisabledCommandsConfig();
// void saveMessagesConfig();
// void saveOpBlockConfig();
//
// File getConfigFile(Object configurationFile);
//
// String getVersion();
//
// String getServerType();
//
// File getDataFolder();
//
// void setupMetrics();
//
// void executeCommand(String cmd);
//
// void sendMessage(Object commandSender, Component message);
//
// List<String> getOldMessages(String category, String message);
// List<String> getOldMessages(String category, String message, Object configurationFile);
//
// Character getChatComponentChar();
//
// String getOldMessage(String category, String message);
// String getOldMessage(String category, String message, Object configurationFile);
//
// void log(String msg);
// }
//
// Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/Universal.java
// public class Universal {
//
// private static Universal instance = null;
// private MethodInterface mi;
//
// public static Universal get() {
// return instance == null ? instance = new Universal() : instance;
// }
//
// public void setup(MethodInterface mi) {
// this.mi = mi;
//
// mi.setupMetrics();
// }
//
// public MethodInterface getMethods() {
// return mi;
// }
//
// }
// Path: Command Blocker Bungee/src/main/java/me/treyruffy/commandblocker/bungeecord/listeners/TabCompletion.java
import me.treyruffy.commandblocker.MethodInterface;
import me.treyruffy.commandblocker.Universal;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.TabCompleteEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.event.EventHandler;
import net.md_5.bungee.event.EventPriority;
package me.treyruffy.commandblocker.bungeecord.listeners;
public class TabCompletion implements Listener {
@EventHandler (priority = EventPriority.HIGHEST)
public void onTabComplete(TabCompleteEvent e) {
if (!(e.getSender() instanceof ProxiedPlayer)) {
return;
} | MethodInterface mi = Universal.get().getMethods(); |
TreyRuffy/CommandBlocker | Command Blocker Bukkit/src/main/java/me/treyruffy/commandblocker/bukkit/config/BukkitUpdateConfig.java | // Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/MethodInterface.java
// public interface MethodInterface {
//
// Object getPlugin();
//
// Object getConfig();
// Object getDisabledCommandsConfig();
// Object getMessagesConfig();
// Object getOpBlockConfig();
//
// void saveConfig();
// void saveDisabledCommandsConfig();
// void saveMessagesConfig();
// void saveOpBlockConfig();
//
// File getConfigFile(Object configurationFile);
//
// String getVersion();
//
// String getServerType();
//
// File getDataFolder();
//
// void setupMetrics();
//
// void executeCommand(String cmd);
//
// void sendMessage(Object commandSender, Component message);
//
// List<String> getOldMessages(String category, String message);
// List<String> getOldMessages(String category, String message, Object configurationFile);
//
// Character getChatComponentChar();
//
// String getOldMessage(String category, String message);
// String getOldMessage(String category, String message, Object configurationFile);
//
// void log(String msg);
// }
//
// Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/Universal.java
// public class Universal {
//
// private static Universal instance = null;
// private MethodInterface mi;
//
// public static Universal get() {
// return instance == null ? instance = new Universal() : instance;
// }
//
// public void setup(MethodInterface mi) {
// this.mi = mi;
//
// mi.setupMetrics();
// }
//
// public MethodInterface getMethods() {
// return mi;
// }
//
// }
| import me.treyruffy.commandblocker.MethodInterface;
import me.treyruffy.commandblocker.Universal;
import org.apache.commons.io.FileUtils;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.util.Objects; | package me.treyruffy.commandblocker.bukkit.config;
public class BukkitUpdateConfig {
// Updates the config
public void setup() { | // Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/MethodInterface.java
// public interface MethodInterface {
//
// Object getPlugin();
//
// Object getConfig();
// Object getDisabledCommandsConfig();
// Object getMessagesConfig();
// Object getOpBlockConfig();
//
// void saveConfig();
// void saveDisabledCommandsConfig();
// void saveMessagesConfig();
// void saveOpBlockConfig();
//
// File getConfigFile(Object configurationFile);
//
// String getVersion();
//
// String getServerType();
//
// File getDataFolder();
//
// void setupMetrics();
//
// void executeCommand(String cmd);
//
// void sendMessage(Object commandSender, Component message);
//
// List<String> getOldMessages(String category, String message);
// List<String> getOldMessages(String category, String message, Object configurationFile);
//
// Character getChatComponentChar();
//
// String getOldMessage(String category, String message);
// String getOldMessage(String category, String message, Object configurationFile);
//
// void log(String msg);
// }
//
// Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/Universal.java
// public class Universal {
//
// private static Universal instance = null;
// private MethodInterface mi;
//
// public static Universal get() {
// return instance == null ? instance = new Universal() : instance;
// }
//
// public void setup(MethodInterface mi) {
// this.mi = mi;
//
// mi.setupMetrics();
// }
//
// public MethodInterface getMethods() {
// return mi;
// }
//
// }
// Path: Command Blocker Bukkit/src/main/java/me/treyruffy/commandblocker/bukkit/config/BukkitUpdateConfig.java
import me.treyruffy.commandblocker.MethodInterface;
import me.treyruffy.commandblocker.Universal;
import org.apache.commons.io.FileUtils;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
package me.treyruffy.commandblocker.bukkit.config;
public class BukkitUpdateConfig {
// Updates the config
public void setup() { | MethodInterface mi = Universal.get().getMethods(); |
TreyRuffy/CommandBlocker | Command Blocker Bukkit/src/main/java/me/treyruffy/commandblocker/bukkit/config/BukkitUpdateConfig.java | // Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/MethodInterface.java
// public interface MethodInterface {
//
// Object getPlugin();
//
// Object getConfig();
// Object getDisabledCommandsConfig();
// Object getMessagesConfig();
// Object getOpBlockConfig();
//
// void saveConfig();
// void saveDisabledCommandsConfig();
// void saveMessagesConfig();
// void saveOpBlockConfig();
//
// File getConfigFile(Object configurationFile);
//
// String getVersion();
//
// String getServerType();
//
// File getDataFolder();
//
// void setupMetrics();
//
// void executeCommand(String cmd);
//
// void sendMessage(Object commandSender, Component message);
//
// List<String> getOldMessages(String category, String message);
// List<String> getOldMessages(String category, String message, Object configurationFile);
//
// Character getChatComponentChar();
//
// String getOldMessage(String category, String message);
// String getOldMessage(String category, String message, Object configurationFile);
//
// void log(String msg);
// }
//
// Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/Universal.java
// public class Universal {
//
// private static Universal instance = null;
// private MethodInterface mi;
//
// public static Universal get() {
// return instance == null ? instance = new Universal() : instance;
// }
//
// public void setup(MethodInterface mi) {
// this.mi = mi;
//
// mi.setupMetrics();
// }
//
// public MethodInterface getMethods() {
// return mi;
// }
//
// }
| import me.treyruffy.commandblocker.MethodInterface;
import me.treyruffy.commandblocker.Universal;
import org.apache.commons.io.FileUtils;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.util.Objects; | package me.treyruffy.commandblocker.bukkit.config;
public class BukkitUpdateConfig {
// Updates the config
public void setup() { | // Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/MethodInterface.java
// public interface MethodInterface {
//
// Object getPlugin();
//
// Object getConfig();
// Object getDisabledCommandsConfig();
// Object getMessagesConfig();
// Object getOpBlockConfig();
//
// void saveConfig();
// void saveDisabledCommandsConfig();
// void saveMessagesConfig();
// void saveOpBlockConfig();
//
// File getConfigFile(Object configurationFile);
//
// String getVersion();
//
// String getServerType();
//
// File getDataFolder();
//
// void setupMetrics();
//
// void executeCommand(String cmd);
//
// void sendMessage(Object commandSender, Component message);
//
// List<String> getOldMessages(String category, String message);
// List<String> getOldMessages(String category, String message, Object configurationFile);
//
// Character getChatComponentChar();
//
// String getOldMessage(String category, String message);
// String getOldMessage(String category, String message, Object configurationFile);
//
// void log(String msg);
// }
//
// Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/Universal.java
// public class Universal {
//
// private static Universal instance = null;
// private MethodInterface mi;
//
// public static Universal get() {
// return instance == null ? instance = new Universal() : instance;
// }
//
// public void setup(MethodInterface mi) {
// this.mi = mi;
//
// mi.setupMetrics();
// }
//
// public MethodInterface getMethods() {
// return mi;
// }
//
// }
// Path: Command Blocker Bukkit/src/main/java/me/treyruffy/commandblocker/bukkit/config/BukkitUpdateConfig.java
import me.treyruffy.commandblocker.MethodInterface;
import me.treyruffy.commandblocker.Universal;
import org.apache.commons.io.FileUtils;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
package me.treyruffy.commandblocker.bukkit.config;
public class BukkitUpdateConfig {
// Updates the config
public void setup() { | MethodInterface mi = Universal.get().getMethods(); |
TreyRuffy/CommandBlocker | Command Blocker Bungee/src/main/java/me/treyruffy/commandblocker/bungeecord/config/BungeeUpdateConfig.java | // Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/MethodInterface.java
// public interface MethodInterface {
//
// Object getPlugin();
//
// Object getConfig();
// Object getDisabledCommandsConfig();
// Object getMessagesConfig();
// Object getOpBlockConfig();
//
// void saveConfig();
// void saveDisabledCommandsConfig();
// void saveMessagesConfig();
// void saveOpBlockConfig();
//
// File getConfigFile(Object configurationFile);
//
// String getVersion();
//
// String getServerType();
//
// File getDataFolder();
//
// void setupMetrics();
//
// void executeCommand(String cmd);
//
// void sendMessage(Object commandSender, Component message);
//
// List<String> getOldMessages(String category, String message);
// List<String> getOldMessages(String category, String message, Object configurationFile);
//
// Character getChatComponentChar();
//
// String getOldMessage(String category, String message);
// String getOldMessage(String category, String message, Object configurationFile);
//
// void log(String msg);
// }
//
// Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/Universal.java
// public class Universal {
//
// private static Universal instance = null;
// private MethodInterface mi;
//
// public static Universal get() {
// return instance == null ? instance = new Universal() : instance;
// }
//
// public void setup(MethodInterface mi) {
// this.mi = mi;
//
// mi.setupMetrics();
// }
//
// public MethodInterface getMethods() {
// return mi;
// }
//
// }
| import me.treyruffy.commandblocker.MethodInterface;
import me.treyruffy.commandblocker.Universal;
import net.md_5.bungee.config.Configuration;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.Objects; | package me.treyruffy.commandblocker.bungeecord.config;
public class BungeeUpdateConfig {
// Updates the config
public void setup() { | // Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/MethodInterface.java
// public interface MethodInterface {
//
// Object getPlugin();
//
// Object getConfig();
// Object getDisabledCommandsConfig();
// Object getMessagesConfig();
// Object getOpBlockConfig();
//
// void saveConfig();
// void saveDisabledCommandsConfig();
// void saveMessagesConfig();
// void saveOpBlockConfig();
//
// File getConfigFile(Object configurationFile);
//
// String getVersion();
//
// String getServerType();
//
// File getDataFolder();
//
// void setupMetrics();
//
// void executeCommand(String cmd);
//
// void sendMessage(Object commandSender, Component message);
//
// List<String> getOldMessages(String category, String message);
// List<String> getOldMessages(String category, String message, Object configurationFile);
//
// Character getChatComponentChar();
//
// String getOldMessage(String category, String message);
// String getOldMessage(String category, String message, Object configurationFile);
//
// void log(String msg);
// }
//
// Path: Command Blocker Shared/src/main/java/me/treyruffy/commandblocker/Universal.java
// public class Universal {
//
// private static Universal instance = null;
// private MethodInterface mi;
//
// public static Universal get() {
// return instance == null ? instance = new Universal() : instance;
// }
//
// public void setup(MethodInterface mi) {
// this.mi = mi;
//
// mi.setupMetrics();
// }
//
// public MethodInterface getMethods() {
// return mi;
// }
//
// }
// Path: Command Blocker Bungee/src/main/java/me/treyruffy/commandblocker/bungeecord/config/BungeeUpdateConfig.java
import me.treyruffy.commandblocker.MethodInterface;
import me.treyruffy.commandblocker.Universal;
import net.md_5.bungee.config.Configuration;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
package me.treyruffy.commandblocker.bungeecord.config;
public class BungeeUpdateConfig {
// Updates the config
public void setup() { | MethodInterface mi = Universal.get().getMethods(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.