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
|
---|---|---|---|---|---|---|
bazelbuild/BUILD_file_generator
|
src/main/java/com/google/devtools/build/bfg/ClassGraphPreprocessor.java
|
// Path: src/main/java/com/google/devtools/build/bfg/ClassNameUtilities.java
// static String getOuterClassName(String className) {
// return className.split("\\$")[0];
// }
|
import static com.google.devtools.build.bfg.ClassNameUtilities.getOuterClassName;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.ImmutableGraph;
import com.google.common.graph.MutableGraph;
import com.google.re2j.Pattern;
|
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.bfg;
/**
* Given a directed graph of class names, processes the graph such that:
*
* <p>all inner class names are collapsed into their top level class name
*
* <p>black listed classes are removed
*
* <p>non white listed classes without a direct edge to a white listed class are removed
*/
public class ClassGraphPreprocessor {
/**
* Produces a class graph that only contains top level class names that either pass the white list
* pattern or have an edge to node that passes the white list. Any class names that pass the black
* list or do not pass our white list criteria are filtered from the graph.
*
* <p>In addition, all inner class names are collapsed into their top level parent class name.
*/
static ImmutableGraph<String> preProcessClassGraph(
ImmutableGraph<String> classGraph, Pattern whiteList, Pattern blackList) {
return collapseInnerClasses(trimClassGraph(classGraph, whiteList, blackList));
}
/** Removes all outgoing edges from classes that are not white listed. */
private static ImmutableGraph<String> trimClassGraph(
ImmutableGraph<String> classGraph, Pattern whiteList, Pattern blackList) {
MutableGraph<String> graph = GraphBuilder.directed().allowsSelfLoops(false).build();
for (String src : classGraph.nodes()) {
if (!whiteList.matcher(src).find() || blackList.matcher(src).find()) {
continue;
}
graph.addNode(src);
for (String dst : classGraph.successors(src)) {
if (blackList.matcher(dst).find()) {
continue;
}
graph.putEdge(src, dst);
}
}
return ImmutableGraph.copyOf(graph);
}
/** Collapses inner classes into their top level parent class */
private static ImmutableGraph<String> collapseInnerClasses(ImmutableGraph<String> classGraph) {
MutableGraph<String> graph = GraphBuilder.directed().allowsSelfLoops(false).build();
for (String src : classGraph.nodes()) {
|
// Path: src/main/java/com/google/devtools/build/bfg/ClassNameUtilities.java
// static String getOuterClassName(String className) {
// return className.split("\\$")[0];
// }
// Path: src/main/java/com/google/devtools/build/bfg/ClassGraphPreprocessor.java
import static com.google.devtools.build.bfg.ClassNameUtilities.getOuterClassName;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.ImmutableGraph;
import com.google.common.graph.MutableGraph;
import com.google.re2j.Pattern;
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.bfg;
/**
* Given a directed graph of class names, processes the graph such that:
*
* <p>all inner class names are collapsed into their top level class name
*
* <p>black listed classes are removed
*
* <p>non white listed classes without a direct edge to a white listed class are removed
*/
public class ClassGraphPreprocessor {
/**
* Produces a class graph that only contains top level class names that either pass the white list
* pattern or have an edge to node that passes the white list. Any class names that pass the black
* list or do not pass our white list criteria are filtered from the graph.
*
* <p>In addition, all inner class names are collapsed into their top level parent class name.
*/
static ImmutableGraph<String> preProcessClassGraph(
ImmutableGraph<String> classGraph, Pattern whiteList, Pattern blackList) {
return collapseInnerClasses(trimClassGraph(classGraph, whiteList, blackList));
}
/** Removes all outgoing edges from classes that are not white listed. */
private static ImmutableGraph<String> trimClassGraph(
ImmutableGraph<String> classGraph, Pattern whiteList, Pattern blackList) {
MutableGraph<String> graph = GraphBuilder.directed().allowsSelfLoops(false).build();
for (String src : classGraph.nodes()) {
if (!whiteList.matcher(src).find() || blackList.matcher(src).find()) {
continue;
}
graph.addNode(src);
for (String dst : classGraph.successors(src)) {
if (blackList.matcher(dst).find()) {
continue;
}
graph.putEdge(src, dst);
}
}
return ImmutableGraph.copyOf(graph);
}
/** Collapses inner classes into their top level parent class */
private static ImmutableGraph<String> collapseInnerClasses(ImmutableGraph<String> classGraph) {
MutableGraph<String> graph = GraphBuilder.directed().allowsSelfLoops(false).build();
for (String src : classGraph.nodes()) {
|
String outerSrc = getOuterClassName(src);
|
bazelbuild/BUILD_file_generator
|
lang/java/src/test/java/com/google/devtools/build/bfg/ReferencedClassesParserTest.java
|
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class ImportDeclaration {
// public abstract QualifiedName name();
//
// public abstract boolean isStatic();
//
// public static ImportDeclaration create(QualifiedName qname, boolean isStatic) {
// return new AutoValue_ReferencedClassesParser_ImportDeclaration(qname, isStatic);
// }
// }
//
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class Metadata {
// static final Metadata EMPTY = create(0, 0, false);
//
// /** Line where a simple/qualified name starts. */
// public abstract int line();
//
// /** Column where a simple/qualified name starts. */
// public abstract int column();
//
// public abstract boolean isMethod();
//
// public static Metadata create(int line, int column, boolean isMethod) {
// return new AutoValue_ReferencedClassesParser_Metadata(line, column, isMethod);
// }
// }
//
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class QualifiedName {
// public static final Pattern CLASS_NAME_PATTERN = Pattern.compile("^[A-Z][a-zA-Z0-9_$]*$");
//
// public static QualifiedName create(String value, Metadata metadata) {
// return new AutoValue_ReferencedClassesParser_QualifiedName(value, metadata);
// }
//
// public abstract String value();
//
// public abstract Metadata metadata();
//
// @Memoized
// public ImmutableList<String> parts() {
// return ImmutableList.copyOf(DOT_SPLITTER.split(value()));
// }
//
// private static int findTopLevelName(List<String> parts) {
// for (int i = 0; i < parts.size(); i++) {
// String part = parts.get(i);
// if (CLASS_NAME_PATTERN.matcher(part).matches()) {
// // if i == 0, 's' starts with a capitalized-camel name,
// // e.g., "MobileLocalDetailsJslayoutProto".
// return i > 0 ? i : -1;
// }
// if (isLowerCase(part)) {
// continue;
// }
// return -1;
// }
// return -1;
// }
//
// /**
// * "java.util.Map" => "java.util.Map" "java.util.Map.Entry" => "java.util.Map"
// * "org.mockito.Mockito.mock" => "org.mockito.Mockito"
// */
// public QualifiedName getTopLevelQualifiedName() {
// return create(DOT_JOINER.join(parts().subList(0, findTopLevelName(parts()) + 1)), metadata());
// }
// }
|
import static com.google.common.collect.Iterables.find;
import static com.google.common.collect.Iterables.transform;
import static com.google.common.truth.Truth.assertThat;
import static java.util.stream.Collectors.toMap;
import static org.junit.Assert.assertTrue;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import com.google.devtools.build.bfg.ReferencedClassesParser.ImportDeclaration;
import com.google.devtools.build.bfg.ReferencedClassesParser.Metadata;
import com.google.devtools.build.bfg.ReferencedClassesParser.QualifiedName;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ParameterizedType;
import org.eclipse.jdt.core.dom.QualifiedType;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
|
"class A {", " void foo() throws IOException, java.io.FileNotFoundException {}", "}");
ReferencedClassesParser parser = parse(source);
assertThat(parser.symbols.keySet())
.containsExactly("IOException", "java.io.FileNotFoundException");
}
@Test
public void allCapsFieldNamesAreNotConsideredClassNames() {
String source =
joiner.join(
"class A {",
" FormattingLogger LOG = null;",
" void foo() {",
" LOG.warning();",
" }",
"}");
ReferencedClassesParser parser = parse(source);
assertThat(parser.symbols.keySet()).containsExactly("FormattingLogger");
}
@Test
public void dontReportJavaLangInnerClasses() {
ReferencedClassesParser parser = parse("class A extends Thread.UncaughtExceptionHandler { }");
assertThat(parser.symbols.keySet()).doesNotContain("Thread");
assertThat(parser.symbols.keySet()).isEmpty();
}
@Test
public void dontReportJavaLangImports() {
ReferencedClassesParser parser = parse("import static java.lang.String.format;");
|
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class ImportDeclaration {
// public abstract QualifiedName name();
//
// public abstract boolean isStatic();
//
// public static ImportDeclaration create(QualifiedName qname, boolean isStatic) {
// return new AutoValue_ReferencedClassesParser_ImportDeclaration(qname, isStatic);
// }
// }
//
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class Metadata {
// static final Metadata EMPTY = create(0, 0, false);
//
// /** Line where a simple/qualified name starts. */
// public abstract int line();
//
// /** Column where a simple/qualified name starts. */
// public abstract int column();
//
// public abstract boolean isMethod();
//
// public static Metadata create(int line, int column, boolean isMethod) {
// return new AutoValue_ReferencedClassesParser_Metadata(line, column, isMethod);
// }
// }
//
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class QualifiedName {
// public static final Pattern CLASS_NAME_PATTERN = Pattern.compile("^[A-Z][a-zA-Z0-9_$]*$");
//
// public static QualifiedName create(String value, Metadata metadata) {
// return new AutoValue_ReferencedClassesParser_QualifiedName(value, metadata);
// }
//
// public abstract String value();
//
// public abstract Metadata metadata();
//
// @Memoized
// public ImmutableList<String> parts() {
// return ImmutableList.copyOf(DOT_SPLITTER.split(value()));
// }
//
// private static int findTopLevelName(List<String> parts) {
// for (int i = 0; i < parts.size(); i++) {
// String part = parts.get(i);
// if (CLASS_NAME_PATTERN.matcher(part).matches()) {
// // if i == 0, 's' starts with a capitalized-camel name,
// // e.g., "MobileLocalDetailsJslayoutProto".
// return i > 0 ? i : -1;
// }
// if (isLowerCase(part)) {
// continue;
// }
// return -1;
// }
// return -1;
// }
//
// /**
// * "java.util.Map" => "java.util.Map" "java.util.Map.Entry" => "java.util.Map"
// * "org.mockito.Mockito.mock" => "org.mockito.Mockito"
// */
// public QualifiedName getTopLevelQualifiedName() {
// return create(DOT_JOINER.join(parts().subList(0, findTopLevelName(parts()) + 1)), metadata());
// }
// }
// Path: lang/java/src/test/java/com/google/devtools/build/bfg/ReferencedClassesParserTest.java
import static com.google.common.collect.Iterables.find;
import static com.google.common.collect.Iterables.transform;
import static com.google.common.truth.Truth.assertThat;
import static java.util.stream.Collectors.toMap;
import static org.junit.Assert.assertTrue;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import com.google.devtools.build.bfg.ReferencedClassesParser.ImportDeclaration;
import com.google.devtools.build.bfg.ReferencedClassesParser.Metadata;
import com.google.devtools.build.bfg.ReferencedClassesParser.QualifiedName;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ParameterizedType;
import org.eclipse.jdt.core.dom.QualifiedType;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
"class A {", " void foo() throws IOException, java.io.FileNotFoundException {}", "}");
ReferencedClassesParser parser = parse(source);
assertThat(parser.symbols.keySet())
.containsExactly("IOException", "java.io.FileNotFoundException");
}
@Test
public void allCapsFieldNamesAreNotConsideredClassNames() {
String source =
joiner.join(
"class A {",
" FormattingLogger LOG = null;",
" void foo() {",
" LOG.warning();",
" }",
"}");
ReferencedClassesParser parser = parse(source);
assertThat(parser.symbols.keySet()).containsExactly("FormattingLogger");
}
@Test
public void dontReportJavaLangInnerClasses() {
ReferencedClassesParser parser = parse("class A extends Thread.UncaughtExceptionHandler { }");
assertThat(parser.symbols.keySet()).doesNotContain("Thread");
assertThat(parser.symbols.keySet()).isEmpty();
}
@Test
public void dontReportJavaLangImports() {
ReferencedClassesParser parser = parse("import static java.lang.String.format;");
|
for (ImportDeclaration decl : parser.importDeclarations) {
|
bazelbuild/BUILD_file_generator
|
lang/java/src/test/java/com/google/devtools/build/bfg/ReferencedClassesParserTest.java
|
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class ImportDeclaration {
// public abstract QualifiedName name();
//
// public abstract boolean isStatic();
//
// public static ImportDeclaration create(QualifiedName qname, boolean isStatic) {
// return new AutoValue_ReferencedClassesParser_ImportDeclaration(qname, isStatic);
// }
// }
//
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class Metadata {
// static final Metadata EMPTY = create(0, 0, false);
//
// /** Line where a simple/qualified name starts. */
// public abstract int line();
//
// /** Column where a simple/qualified name starts. */
// public abstract int column();
//
// public abstract boolean isMethod();
//
// public static Metadata create(int line, int column, boolean isMethod) {
// return new AutoValue_ReferencedClassesParser_Metadata(line, column, isMethod);
// }
// }
//
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class QualifiedName {
// public static final Pattern CLASS_NAME_PATTERN = Pattern.compile("^[A-Z][a-zA-Z0-9_$]*$");
//
// public static QualifiedName create(String value, Metadata metadata) {
// return new AutoValue_ReferencedClassesParser_QualifiedName(value, metadata);
// }
//
// public abstract String value();
//
// public abstract Metadata metadata();
//
// @Memoized
// public ImmutableList<String> parts() {
// return ImmutableList.copyOf(DOT_SPLITTER.split(value()));
// }
//
// private static int findTopLevelName(List<String> parts) {
// for (int i = 0; i < parts.size(); i++) {
// String part = parts.get(i);
// if (CLASS_NAME_PATTERN.matcher(part).matches()) {
// // if i == 0, 's' starts with a capitalized-camel name,
// // e.g., "MobileLocalDetailsJslayoutProto".
// return i > 0 ? i : -1;
// }
// if (isLowerCase(part)) {
// continue;
// }
// return -1;
// }
// return -1;
// }
//
// /**
// * "java.util.Map" => "java.util.Map" "java.util.Map.Entry" => "java.util.Map"
// * "org.mockito.Mockito.mock" => "org.mockito.Mockito"
// */
// public QualifiedName getTopLevelQualifiedName() {
// return create(DOT_JOINER.join(parts().subList(0, findTopLevelName(parts()) + 1)), metadata());
// }
// }
|
import static com.google.common.collect.Iterables.find;
import static com.google.common.collect.Iterables.transform;
import static com.google.common.truth.Truth.assertThat;
import static java.util.stream.Collectors.toMap;
import static org.junit.Assert.assertTrue;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import com.google.devtools.build.bfg.ReferencedClassesParser.ImportDeclaration;
import com.google.devtools.build.bfg.ReferencedClassesParser.Metadata;
import com.google.devtools.build.bfg.ReferencedClassesParser.QualifiedName;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ParameterizedType;
import org.eclipse.jdt.core.dom.QualifiedType;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
|
" void foo() {",
" LOG.warning();",
" }",
"}");
ReferencedClassesParser parser = parse(source);
assertThat(parser.symbols.keySet()).containsExactly("FormattingLogger");
}
@Test
public void dontReportJavaLangInnerClasses() {
ReferencedClassesParser parser = parse("class A extends Thread.UncaughtExceptionHandler { }");
assertThat(parser.symbols.keySet()).doesNotContain("Thread");
assertThat(parser.symbols.keySet()).isEmpty();
}
@Test
public void dontReportJavaLangImports() {
ReferencedClassesParser parser = parse("import static java.lang.String.format;");
for (ImportDeclaration decl : parser.importDeclarations) {
assertThat(decl.name().value()).isNotEqualTo("java.lang.String.format");
}
assertThat(parser.importDeclarations).isEmpty();
}
@Test
public void reportJavaLangSubpackageImports() {
ReferencedClassesParser parser = parse("import java.lang.reflect.Method;");
assertThat(parser.importDeclarations)
.containsExactly(
ImportDeclaration.create(
|
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class ImportDeclaration {
// public abstract QualifiedName name();
//
// public abstract boolean isStatic();
//
// public static ImportDeclaration create(QualifiedName qname, boolean isStatic) {
// return new AutoValue_ReferencedClassesParser_ImportDeclaration(qname, isStatic);
// }
// }
//
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class Metadata {
// static final Metadata EMPTY = create(0, 0, false);
//
// /** Line where a simple/qualified name starts. */
// public abstract int line();
//
// /** Column where a simple/qualified name starts. */
// public abstract int column();
//
// public abstract boolean isMethod();
//
// public static Metadata create(int line, int column, boolean isMethod) {
// return new AutoValue_ReferencedClassesParser_Metadata(line, column, isMethod);
// }
// }
//
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class QualifiedName {
// public static final Pattern CLASS_NAME_PATTERN = Pattern.compile("^[A-Z][a-zA-Z0-9_$]*$");
//
// public static QualifiedName create(String value, Metadata metadata) {
// return new AutoValue_ReferencedClassesParser_QualifiedName(value, metadata);
// }
//
// public abstract String value();
//
// public abstract Metadata metadata();
//
// @Memoized
// public ImmutableList<String> parts() {
// return ImmutableList.copyOf(DOT_SPLITTER.split(value()));
// }
//
// private static int findTopLevelName(List<String> parts) {
// for (int i = 0; i < parts.size(); i++) {
// String part = parts.get(i);
// if (CLASS_NAME_PATTERN.matcher(part).matches()) {
// // if i == 0, 's' starts with a capitalized-camel name,
// // e.g., "MobileLocalDetailsJslayoutProto".
// return i > 0 ? i : -1;
// }
// if (isLowerCase(part)) {
// continue;
// }
// return -1;
// }
// return -1;
// }
//
// /**
// * "java.util.Map" => "java.util.Map" "java.util.Map.Entry" => "java.util.Map"
// * "org.mockito.Mockito.mock" => "org.mockito.Mockito"
// */
// public QualifiedName getTopLevelQualifiedName() {
// return create(DOT_JOINER.join(parts().subList(0, findTopLevelName(parts()) + 1)), metadata());
// }
// }
// Path: lang/java/src/test/java/com/google/devtools/build/bfg/ReferencedClassesParserTest.java
import static com.google.common.collect.Iterables.find;
import static com.google.common.collect.Iterables.transform;
import static com.google.common.truth.Truth.assertThat;
import static java.util.stream.Collectors.toMap;
import static org.junit.Assert.assertTrue;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import com.google.devtools.build.bfg.ReferencedClassesParser.ImportDeclaration;
import com.google.devtools.build.bfg.ReferencedClassesParser.Metadata;
import com.google.devtools.build.bfg.ReferencedClassesParser.QualifiedName;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ParameterizedType;
import org.eclipse.jdt.core.dom.QualifiedType;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
" void foo() {",
" LOG.warning();",
" }",
"}");
ReferencedClassesParser parser = parse(source);
assertThat(parser.symbols.keySet()).containsExactly("FormattingLogger");
}
@Test
public void dontReportJavaLangInnerClasses() {
ReferencedClassesParser parser = parse("class A extends Thread.UncaughtExceptionHandler { }");
assertThat(parser.symbols.keySet()).doesNotContain("Thread");
assertThat(parser.symbols.keySet()).isEmpty();
}
@Test
public void dontReportJavaLangImports() {
ReferencedClassesParser parser = parse("import static java.lang.String.format;");
for (ImportDeclaration decl : parser.importDeclarations) {
assertThat(decl.name().value()).isNotEqualTo("java.lang.String.format");
}
assertThat(parser.importDeclarations).isEmpty();
}
@Test
public void reportJavaLangSubpackageImports() {
ReferencedClassesParser parser = parse("import java.lang.reflect.Method;");
assertThat(parser.importDeclarations)
.containsExactly(
ImportDeclaration.create(
|
QualifiedName.create("java.lang.reflect.Method", Metadata.create(1, 7, false)),
|
bazelbuild/BUILD_file_generator
|
lang/java/src/test/java/com/google/devtools/build/bfg/ReferencedClassesParserTest.java
|
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class ImportDeclaration {
// public abstract QualifiedName name();
//
// public abstract boolean isStatic();
//
// public static ImportDeclaration create(QualifiedName qname, boolean isStatic) {
// return new AutoValue_ReferencedClassesParser_ImportDeclaration(qname, isStatic);
// }
// }
//
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class Metadata {
// static final Metadata EMPTY = create(0, 0, false);
//
// /** Line where a simple/qualified name starts. */
// public abstract int line();
//
// /** Column where a simple/qualified name starts. */
// public abstract int column();
//
// public abstract boolean isMethod();
//
// public static Metadata create(int line, int column, boolean isMethod) {
// return new AutoValue_ReferencedClassesParser_Metadata(line, column, isMethod);
// }
// }
//
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class QualifiedName {
// public static final Pattern CLASS_NAME_PATTERN = Pattern.compile("^[A-Z][a-zA-Z0-9_$]*$");
//
// public static QualifiedName create(String value, Metadata metadata) {
// return new AutoValue_ReferencedClassesParser_QualifiedName(value, metadata);
// }
//
// public abstract String value();
//
// public abstract Metadata metadata();
//
// @Memoized
// public ImmutableList<String> parts() {
// return ImmutableList.copyOf(DOT_SPLITTER.split(value()));
// }
//
// private static int findTopLevelName(List<String> parts) {
// for (int i = 0; i < parts.size(); i++) {
// String part = parts.get(i);
// if (CLASS_NAME_PATTERN.matcher(part).matches()) {
// // if i == 0, 's' starts with a capitalized-camel name,
// // e.g., "MobileLocalDetailsJslayoutProto".
// return i > 0 ? i : -1;
// }
// if (isLowerCase(part)) {
// continue;
// }
// return -1;
// }
// return -1;
// }
//
// /**
// * "java.util.Map" => "java.util.Map" "java.util.Map.Entry" => "java.util.Map"
// * "org.mockito.Mockito.mock" => "org.mockito.Mockito"
// */
// public QualifiedName getTopLevelQualifiedName() {
// return create(DOT_JOINER.join(parts().subList(0, findTopLevelName(parts()) + 1)), metadata());
// }
// }
|
import static com.google.common.collect.Iterables.find;
import static com.google.common.collect.Iterables.transform;
import static com.google.common.truth.Truth.assertThat;
import static java.util.stream.Collectors.toMap;
import static org.junit.Assert.assertTrue;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import com.google.devtools.build.bfg.ReferencedClassesParser.ImportDeclaration;
import com.google.devtools.build.bfg.ReferencedClassesParser.Metadata;
import com.google.devtools.build.bfg.ReferencedClassesParser.QualifiedName;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ParameterizedType;
import org.eclipse.jdt.core.dom.QualifiedType;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
|
" void foo() {",
" LOG.warning();",
" }",
"}");
ReferencedClassesParser parser = parse(source);
assertThat(parser.symbols.keySet()).containsExactly("FormattingLogger");
}
@Test
public void dontReportJavaLangInnerClasses() {
ReferencedClassesParser parser = parse("class A extends Thread.UncaughtExceptionHandler { }");
assertThat(parser.symbols.keySet()).doesNotContain("Thread");
assertThat(parser.symbols.keySet()).isEmpty();
}
@Test
public void dontReportJavaLangImports() {
ReferencedClassesParser parser = parse("import static java.lang.String.format;");
for (ImportDeclaration decl : parser.importDeclarations) {
assertThat(decl.name().value()).isNotEqualTo("java.lang.String.format");
}
assertThat(parser.importDeclarations).isEmpty();
}
@Test
public void reportJavaLangSubpackageImports() {
ReferencedClassesParser parser = parse("import java.lang.reflect.Method;");
assertThat(parser.importDeclarations)
.containsExactly(
ImportDeclaration.create(
|
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class ImportDeclaration {
// public abstract QualifiedName name();
//
// public abstract boolean isStatic();
//
// public static ImportDeclaration create(QualifiedName qname, boolean isStatic) {
// return new AutoValue_ReferencedClassesParser_ImportDeclaration(qname, isStatic);
// }
// }
//
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class Metadata {
// static final Metadata EMPTY = create(0, 0, false);
//
// /** Line where a simple/qualified name starts. */
// public abstract int line();
//
// /** Column where a simple/qualified name starts. */
// public abstract int column();
//
// public abstract boolean isMethod();
//
// public static Metadata create(int line, int column, boolean isMethod) {
// return new AutoValue_ReferencedClassesParser_Metadata(line, column, isMethod);
// }
// }
//
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class QualifiedName {
// public static final Pattern CLASS_NAME_PATTERN = Pattern.compile("^[A-Z][a-zA-Z0-9_$]*$");
//
// public static QualifiedName create(String value, Metadata metadata) {
// return new AutoValue_ReferencedClassesParser_QualifiedName(value, metadata);
// }
//
// public abstract String value();
//
// public abstract Metadata metadata();
//
// @Memoized
// public ImmutableList<String> parts() {
// return ImmutableList.copyOf(DOT_SPLITTER.split(value()));
// }
//
// private static int findTopLevelName(List<String> parts) {
// for (int i = 0; i < parts.size(); i++) {
// String part = parts.get(i);
// if (CLASS_NAME_PATTERN.matcher(part).matches()) {
// // if i == 0, 's' starts with a capitalized-camel name,
// // e.g., "MobileLocalDetailsJslayoutProto".
// return i > 0 ? i : -1;
// }
// if (isLowerCase(part)) {
// continue;
// }
// return -1;
// }
// return -1;
// }
//
// /**
// * "java.util.Map" => "java.util.Map" "java.util.Map.Entry" => "java.util.Map"
// * "org.mockito.Mockito.mock" => "org.mockito.Mockito"
// */
// public QualifiedName getTopLevelQualifiedName() {
// return create(DOT_JOINER.join(parts().subList(0, findTopLevelName(parts()) + 1)), metadata());
// }
// }
// Path: lang/java/src/test/java/com/google/devtools/build/bfg/ReferencedClassesParserTest.java
import static com.google.common.collect.Iterables.find;
import static com.google.common.collect.Iterables.transform;
import static com.google.common.truth.Truth.assertThat;
import static java.util.stream.Collectors.toMap;
import static org.junit.Assert.assertTrue;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import com.google.devtools.build.bfg.ReferencedClassesParser.ImportDeclaration;
import com.google.devtools.build.bfg.ReferencedClassesParser.Metadata;
import com.google.devtools.build.bfg.ReferencedClassesParser.QualifiedName;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ParameterizedType;
import org.eclipse.jdt.core.dom.QualifiedType;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
" void foo() {",
" LOG.warning();",
" }",
"}");
ReferencedClassesParser parser = parse(source);
assertThat(parser.symbols.keySet()).containsExactly("FormattingLogger");
}
@Test
public void dontReportJavaLangInnerClasses() {
ReferencedClassesParser parser = parse("class A extends Thread.UncaughtExceptionHandler { }");
assertThat(parser.symbols.keySet()).doesNotContain("Thread");
assertThat(parser.symbols.keySet()).isEmpty();
}
@Test
public void dontReportJavaLangImports() {
ReferencedClassesParser parser = parse("import static java.lang.String.format;");
for (ImportDeclaration decl : parser.importDeclarations) {
assertThat(decl.name().value()).isNotEqualTo("java.lang.String.format");
}
assertThat(parser.importDeclarations).isEmpty();
}
@Test
public void reportJavaLangSubpackageImports() {
ReferencedClassesParser parser = parse("import java.lang.reflect.Method;");
assertThat(parser.importDeclarations)
.containsExactly(
ImportDeclaration.create(
|
QualifiedName.create("java.lang.reflect.Method", Metadata.create(1, 7, false)),
|
bazelbuild/BUILD_file_generator
|
src/test/java/com/google/devtools/build/bfg/GraphProcessorTest.java
|
// Path: src/main/java/com/google/devtools/build/bfg/GraphProcessor.java
// static class GraphProcessorException extends RuntimeException {
// GraphProcessorException(String message) {
// super(message);
// }
// }
|
import static com.google.common.truth.Truth.assertThat;
import static junit.framework.TestCase.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.graph.EndpointPair;
import com.google.common.graph.Graph;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.ImmutableGraph;
import com.google.common.graph.MutableGraph;
import com.google.devtools.build.bfg.GraphProcessor.GraphProcessorException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
|
* Tests behavior when a class is mapped to multiple build rules. The Graph Processor should
* ignore the mapping of the secondary resolver. This also tests whether the resolvers are called
* in an appropriate fashion. The first resolver should be called on the entire class graph. The
* second resolver should be called on an empty set. If it is called on any other argument, then
* this test will throw either a GraphProcessorException or a NullPointerException.
*/
@Test
public void multipleResolversWithDifferingResolutions() {
MutableGraph<String> classgraph = GraphBuilder.directed().allowsSelfLoops(false).build();
classgraph.putEdge("com.A", "com.B");
GraphProcessor processor = new GraphProcessor(ImmutableGraph.copyOf(classgraph));
String packagePath = "/java/com/";
BuildRule ruleA = newBuildRule(packagePath, "/java/com/A.java");
BuildRule ruleB = newBuildRule(packagePath, "/java/com/B.java");
ClassToRuleResolver resolver1 = mock(ClassToRuleResolver.class);
when(resolver1.resolve(classgraph.nodes()))
.thenReturn(ImmutableMap.of("com.A", ruleA, "com.B", ruleB));
ClassToRuleResolver resolver2 = mock(ClassToRuleResolver.class);
when(resolver2.resolve(classgraph.nodes())).thenReturn(ImmutableMap.of("com.B", ruleA));
when(resolver2.resolve(ImmutableSet.of())).thenReturn(ImmutableMap.of());
try {
Graph<BuildRule> actual =
processor.createBuildRuleDAG(ImmutableList.of(resolver1, resolver2));
MutableGraph<BuildRule> expected = GraphBuilder.directed().allowsSelfLoops(false).build();
expected.putEdge(ruleA, ruleB);
assertThatGraphsEqual(actual, expected);
|
// Path: src/main/java/com/google/devtools/build/bfg/GraphProcessor.java
// static class GraphProcessorException extends RuntimeException {
// GraphProcessorException(String message) {
// super(message);
// }
// }
// Path: src/test/java/com/google/devtools/build/bfg/GraphProcessorTest.java
import static com.google.common.truth.Truth.assertThat;
import static junit.framework.TestCase.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.graph.EndpointPair;
import com.google.common.graph.Graph;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.ImmutableGraph;
import com.google.common.graph.MutableGraph;
import com.google.devtools.build.bfg.GraphProcessor.GraphProcessorException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
* Tests behavior when a class is mapped to multiple build rules. The Graph Processor should
* ignore the mapping of the secondary resolver. This also tests whether the resolvers are called
* in an appropriate fashion. The first resolver should be called on the entire class graph. The
* second resolver should be called on an empty set. If it is called on any other argument, then
* this test will throw either a GraphProcessorException or a NullPointerException.
*/
@Test
public void multipleResolversWithDifferingResolutions() {
MutableGraph<String> classgraph = GraphBuilder.directed().allowsSelfLoops(false).build();
classgraph.putEdge("com.A", "com.B");
GraphProcessor processor = new GraphProcessor(ImmutableGraph.copyOf(classgraph));
String packagePath = "/java/com/";
BuildRule ruleA = newBuildRule(packagePath, "/java/com/A.java");
BuildRule ruleB = newBuildRule(packagePath, "/java/com/B.java");
ClassToRuleResolver resolver1 = mock(ClassToRuleResolver.class);
when(resolver1.resolve(classgraph.nodes()))
.thenReturn(ImmutableMap.of("com.A", ruleA, "com.B", ruleB));
ClassToRuleResolver resolver2 = mock(ClassToRuleResolver.class);
when(resolver2.resolve(classgraph.nodes())).thenReturn(ImmutableMap.of("com.B", ruleA));
when(resolver2.resolve(ImmutableSet.of())).thenReturn(ImmutableMap.of());
try {
Graph<BuildRule> actual =
processor.createBuildRuleDAG(ImmutableList.of(resolver1, resolver2));
MutableGraph<BuildRule> expected = GraphBuilder.directed().allowsSelfLoops(false).build();
expected.putEdge(ruleA, ruleB);
assertThatGraphsEqual(actual, expected);
|
} catch (GraphProcessorException e) {
|
bazelbuild/BUILD_file_generator
|
src/test/java/com/google/devtools/build/bfg/ProjectClassToRuleResolverTest.java
|
// Path: src/main/java/com/google/devtools/build/bfg/ProjectClassToRuleResolver.java
// static final double UNRESOLVED_THRESHOLD = 0.7;
|
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.bfg.ProjectClassToRuleResolver.UNRESOLVED_THRESHOLD;
import static junit.framework.TestCase.fail;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.graph.Graph;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.ImmutableGraph;
import com.google.common.graph.MutableGraph;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import com.google.re2j.Pattern;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Path;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
|
assertThat(actual).doesNotContainKey("com.DoesNotExist");
}
/**
* If a class's source file cannot be found, then that class name should not be in the ensuing
* class. If more than the default threshold are unresolved, then it BFG should error out.
*/
@Test
public void ignoresUnresolvedClass_exceedsThreshold() throws IOException {
MutableGraph<String> classgraph = newGraph(String.class);
classgraph.putEdge("com.A", "com.DoesNotExist");
classgraph.putEdge("com.A", "com.DoesNotExistTwo");
classgraph.putEdge("com.A", "com.DoesNotExistThree");
ProjectClassToRuleResolver resolver =
newResolver(
classgraph,
WHITELIST_DEFAULT,
ImmutableMap.of("com.A", workspace.resolve("java/com/A.java")));
try {
resolver.resolve(classgraph.nodes());
fail("Expected an exception, but nothing was thrown.");
} catch (IllegalStateException e) {
assertThat(e)
.hasMessageThat()
.isEqualTo(
String.format(
"BUILD File Generator failed to map over %.0f percent of class names. "
+ "Check your white list and content roots",
|
// Path: src/main/java/com/google/devtools/build/bfg/ProjectClassToRuleResolver.java
// static final double UNRESOLVED_THRESHOLD = 0.7;
// Path: src/test/java/com/google/devtools/build/bfg/ProjectClassToRuleResolverTest.java
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.bfg.ProjectClassToRuleResolver.UNRESOLVED_THRESHOLD;
import static junit.framework.TestCase.fail;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.graph.Graph;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.ImmutableGraph;
import com.google.common.graph.MutableGraph;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import com.google.re2j.Pattern;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Path;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
assertThat(actual).doesNotContainKey("com.DoesNotExist");
}
/**
* If a class's source file cannot be found, then that class name should not be in the ensuing
* class. If more than the default threshold are unresolved, then it BFG should error out.
*/
@Test
public void ignoresUnresolvedClass_exceedsThreshold() throws IOException {
MutableGraph<String> classgraph = newGraph(String.class);
classgraph.putEdge("com.A", "com.DoesNotExist");
classgraph.putEdge("com.A", "com.DoesNotExistTwo");
classgraph.putEdge("com.A", "com.DoesNotExistThree");
ProjectClassToRuleResolver resolver =
newResolver(
classgraph,
WHITELIST_DEFAULT,
ImmutableMap.of("com.A", workspace.resolve("java/com/A.java")));
try {
resolver.resolve(classgraph.nodes());
fail("Expected an exception, but nothing was thrown.");
} catch (IllegalStateException e) {
assertThat(e)
.hasMessageThat()
.isEqualTo(
String.format(
"BUILD File Generator failed to map over %.0f percent of class names. "
+ "Check your white list and content roots",
|
UNRESOLVED_THRESHOLD * 100));
|
bazelbuild/BUILD_file_generator
|
lang/java/src/main/java/com/google/devtools/build/bfg/JavaSourceFileParser.java
|
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class Metadata {
// static final Metadata EMPTY = create(0, 0, false);
//
// /** Line where a simple/qualified name starts. */
// public abstract int line();
//
// /** Column where a simple/qualified name starts. */
// public abstract int column();
//
// public abstract boolean isMethod();
//
// public static Metadata create(int line, int column, boolean isMethod) {
// return new AutoValue_ReferencedClassesParser_Metadata(line, column, isMethod);
// }
// }
//
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class QualifiedName {
// public static final Pattern CLASS_NAME_PATTERN = Pattern.compile("^[A-Z][a-zA-Z0-9_$]*$");
//
// public static QualifiedName create(String value, Metadata metadata) {
// return new AutoValue_ReferencedClassesParser_QualifiedName(value, metadata);
// }
//
// public abstract String value();
//
// public abstract Metadata metadata();
//
// @Memoized
// public ImmutableList<String> parts() {
// return ImmutableList.copyOf(DOT_SPLITTER.split(value()));
// }
//
// private static int findTopLevelName(List<String> parts) {
// for (int i = 0; i < parts.size(); i++) {
// String part = parts.get(i);
// if (CLASS_NAME_PATTERN.matcher(part).matches()) {
// // if i == 0, 's' starts with a capitalized-camel name,
// // e.g., "MobileLocalDetailsJslayoutProto".
// return i > 0 ? i : -1;
// }
// if (isLowerCase(part)) {
// continue;
// }
// return -1;
// }
// return -1;
// }
//
// /**
// * "java.util.Map" => "java.util.Map" "java.util.Map.Entry" => "java.util.Map"
// * "org.mockito.Mockito.mock" => "org.mockito.Mockito"
// */
// public QualifiedName getTopLevelQualifiedName() {
// return create(DOT_JOINER.join(parts().subList(0, findTopLevelName(parts()) + 1)), metadata());
// }
// }
//
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class SimpleName {
// public abstract String value();
//
// public abstract Metadata metadata();
//
// public static SimpleName create(String value, Metadata metadata) {
// return new AutoValue_ReferencedClassesParser_SimpleName(value, metadata);
// }
// }
|
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Iterables.any;
import static com.google.common.collect.Iterables.getLast;
import static com.google.common.collect.Iterables.getOnlyElement;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.Files.readAllBytes;
import com.google.common.base.Strings;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Ordering;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.ImmutableGraph;
import com.google.common.graph.MutableGraph;
import com.google.devtools.build.bfg.ReferencedClassesParser.Metadata;
import com.google.devtools.build.bfg.ReferencedClassesParser.QualifiedName;
import com.google.devtools.build.bfg.ReferencedClassesParser.SimpleName;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.eclipse.jdt.core.dom.AbstractTypeDeclaration;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.PrimitiveType;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.Type;
|
return filesToRuleKind;
}
/** Given a list of source files, creates a graph of their class level dependencies */
private static void parseFiles(
ImmutableList<Path> absoluteSourceFilePaths,
ImmutableList<Path> contentRoots,
ImmutableSet<Path> oneRulePerPackageRoots,
ImmutableSet.Builder<String> unresolvedClassNames,
MutableGraph<String> classToClass,
ImmutableMap.Builder<String, String> classToFile,
ImmutableMap.Builder<String, String> fileToRuleKind)
throws IOException {
HashMultimap<Path, String> dirToClass = HashMultimap.create();
for (Path srcFilePath : absoluteSourceFilePaths) {
ReferencedClassesParser parser =
new ReferencedClassesParser(
srcFilePath.getFileName().toString(),
new String(readAllBytes(srcFilePath), UTF_8),
contentRoots);
checkState(parser.isSuccessful);
if (Strings.isNullOrEmpty(parser.fullyQualifiedClassName)) {
// The file doesn't contain any classes, skip it. This happens for package-info.java files.
continue;
}
String qualifiedSrc = stripInnerClassFromName(parser.fullyQualifiedClassName);
dirToClass.put(srcFilePath.getParent(), parser.fullyQualifiedClassName);
boolean hasEdges = false;
classToFile.put(qualifiedSrc, srcFilePath.toString());
|
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class Metadata {
// static final Metadata EMPTY = create(0, 0, false);
//
// /** Line where a simple/qualified name starts. */
// public abstract int line();
//
// /** Column where a simple/qualified name starts. */
// public abstract int column();
//
// public abstract boolean isMethod();
//
// public static Metadata create(int line, int column, boolean isMethod) {
// return new AutoValue_ReferencedClassesParser_Metadata(line, column, isMethod);
// }
// }
//
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class QualifiedName {
// public static final Pattern CLASS_NAME_PATTERN = Pattern.compile("^[A-Z][a-zA-Z0-9_$]*$");
//
// public static QualifiedName create(String value, Metadata metadata) {
// return new AutoValue_ReferencedClassesParser_QualifiedName(value, metadata);
// }
//
// public abstract String value();
//
// public abstract Metadata metadata();
//
// @Memoized
// public ImmutableList<String> parts() {
// return ImmutableList.copyOf(DOT_SPLITTER.split(value()));
// }
//
// private static int findTopLevelName(List<String> parts) {
// for (int i = 0; i < parts.size(); i++) {
// String part = parts.get(i);
// if (CLASS_NAME_PATTERN.matcher(part).matches()) {
// // if i == 0, 's' starts with a capitalized-camel name,
// // e.g., "MobileLocalDetailsJslayoutProto".
// return i > 0 ? i : -1;
// }
// if (isLowerCase(part)) {
// continue;
// }
// return -1;
// }
// return -1;
// }
//
// /**
// * "java.util.Map" => "java.util.Map" "java.util.Map.Entry" => "java.util.Map"
// * "org.mockito.Mockito.mock" => "org.mockito.Mockito"
// */
// public QualifiedName getTopLevelQualifiedName() {
// return create(DOT_JOINER.join(parts().subList(0, findTopLevelName(parts()) + 1)), metadata());
// }
// }
//
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class SimpleName {
// public abstract String value();
//
// public abstract Metadata metadata();
//
// public static SimpleName create(String value, Metadata metadata) {
// return new AutoValue_ReferencedClassesParser_SimpleName(value, metadata);
// }
// }
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/JavaSourceFileParser.java
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Iterables.any;
import static com.google.common.collect.Iterables.getLast;
import static com.google.common.collect.Iterables.getOnlyElement;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.Files.readAllBytes;
import com.google.common.base.Strings;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Ordering;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.ImmutableGraph;
import com.google.common.graph.MutableGraph;
import com.google.devtools.build.bfg.ReferencedClassesParser.Metadata;
import com.google.devtools.build.bfg.ReferencedClassesParser.QualifiedName;
import com.google.devtools.build.bfg.ReferencedClassesParser.SimpleName;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.eclipse.jdt.core.dom.AbstractTypeDeclaration;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.PrimitiveType;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.Type;
return filesToRuleKind;
}
/** Given a list of source files, creates a graph of their class level dependencies */
private static void parseFiles(
ImmutableList<Path> absoluteSourceFilePaths,
ImmutableList<Path> contentRoots,
ImmutableSet<Path> oneRulePerPackageRoots,
ImmutableSet.Builder<String> unresolvedClassNames,
MutableGraph<String> classToClass,
ImmutableMap.Builder<String, String> classToFile,
ImmutableMap.Builder<String, String> fileToRuleKind)
throws IOException {
HashMultimap<Path, String> dirToClass = HashMultimap.create();
for (Path srcFilePath : absoluteSourceFilePaths) {
ReferencedClassesParser parser =
new ReferencedClassesParser(
srcFilePath.getFileName().toString(),
new String(readAllBytes(srcFilePath), UTF_8),
contentRoots);
checkState(parser.isSuccessful);
if (Strings.isNullOrEmpty(parser.fullyQualifiedClassName)) {
// The file doesn't contain any classes, skip it. This happens for package-info.java files.
continue;
}
String qualifiedSrc = stripInnerClassFromName(parser.fullyQualifiedClassName);
dirToClass.put(srcFilePath.getParent(), parser.fullyQualifiedClassName);
boolean hasEdges = false;
classToFile.put(qualifiedSrc, srcFilePath.toString());
|
for (QualifiedName qualifiedDst : parser.qualifiedTopLevelNames) {
|
bazelbuild/BUILD_file_generator
|
lang/java/src/main/java/com/google/devtools/build/bfg/JavaSourceFileParser.java
|
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class Metadata {
// static final Metadata EMPTY = create(0, 0, false);
//
// /** Line where a simple/qualified name starts. */
// public abstract int line();
//
// /** Column where a simple/qualified name starts. */
// public abstract int column();
//
// public abstract boolean isMethod();
//
// public static Metadata create(int line, int column, boolean isMethod) {
// return new AutoValue_ReferencedClassesParser_Metadata(line, column, isMethod);
// }
// }
//
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class QualifiedName {
// public static final Pattern CLASS_NAME_PATTERN = Pattern.compile("^[A-Z][a-zA-Z0-9_$]*$");
//
// public static QualifiedName create(String value, Metadata metadata) {
// return new AutoValue_ReferencedClassesParser_QualifiedName(value, metadata);
// }
//
// public abstract String value();
//
// public abstract Metadata metadata();
//
// @Memoized
// public ImmutableList<String> parts() {
// return ImmutableList.copyOf(DOT_SPLITTER.split(value()));
// }
//
// private static int findTopLevelName(List<String> parts) {
// for (int i = 0; i < parts.size(); i++) {
// String part = parts.get(i);
// if (CLASS_NAME_PATTERN.matcher(part).matches()) {
// // if i == 0, 's' starts with a capitalized-camel name,
// // e.g., "MobileLocalDetailsJslayoutProto".
// return i > 0 ? i : -1;
// }
// if (isLowerCase(part)) {
// continue;
// }
// return -1;
// }
// return -1;
// }
//
// /**
// * "java.util.Map" => "java.util.Map" "java.util.Map.Entry" => "java.util.Map"
// * "org.mockito.Mockito.mock" => "org.mockito.Mockito"
// */
// public QualifiedName getTopLevelQualifiedName() {
// return create(DOT_JOINER.join(parts().subList(0, findTopLevelName(parts()) + 1)), metadata());
// }
// }
//
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class SimpleName {
// public abstract String value();
//
// public abstract Metadata metadata();
//
// public static SimpleName create(String value, Metadata metadata) {
// return new AutoValue_ReferencedClassesParser_SimpleName(value, metadata);
// }
// }
|
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Iterables.any;
import static com.google.common.collect.Iterables.getLast;
import static com.google.common.collect.Iterables.getOnlyElement;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.Files.readAllBytes;
import com.google.common.base.Strings;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Ordering;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.ImmutableGraph;
import com.google.common.graph.MutableGraph;
import com.google.devtools.build.bfg.ReferencedClassesParser.Metadata;
import com.google.devtools.build.bfg.ReferencedClassesParser.QualifiedName;
import com.google.devtools.build.bfg.ReferencedClassesParser.SimpleName;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.eclipse.jdt.core.dom.AbstractTypeDeclaration;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.PrimitiveType;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.Type;
|
ImmutableSet<Path> oneRulePerPackageRoots,
ImmutableSet.Builder<String> unresolvedClassNames,
MutableGraph<String> classToClass,
ImmutableMap.Builder<String, String> classToFile,
ImmutableMap.Builder<String, String> fileToRuleKind)
throws IOException {
HashMultimap<Path, String> dirToClass = HashMultimap.create();
for (Path srcFilePath : absoluteSourceFilePaths) {
ReferencedClassesParser parser =
new ReferencedClassesParser(
srcFilePath.getFileName().toString(),
new String(readAllBytes(srcFilePath), UTF_8),
contentRoots);
checkState(parser.isSuccessful);
if (Strings.isNullOrEmpty(parser.fullyQualifiedClassName)) {
// The file doesn't contain any classes, skip it. This happens for package-info.java files.
continue;
}
String qualifiedSrc = stripInnerClassFromName(parser.fullyQualifiedClassName);
dirToClass.put(srcFilePath.getParent(), parser.fullyQualifiedClassName);
boolean hasEdges = false;
classToFile.put(qualifiedSrc, srcFilePath.toString());
for (QualifiedName qualifiedDst : parser.qualifiedTopLevelNames) {
if (!qualifiedSrc.equals(qualifiedDst.value())) {
classToClass.putEdge(qualifiedSrc, qualifiedDst.value());
hasEdges = true;
}
}
|
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class Metadata {
// static final Metadata EMPTY = create(0, 0, false);
//
// /** Line where a simple/qualified name starts. */
// public abstract int line();
//
// /** Column where a simple/qualified name starts. */
// public abstract int column();
//
// public abstract boolean isMethod();
//
// public static Metadata create(int line, int column, boolean isMethod) {
// return new AutoValue_ReferencedClassesParser_Metadata(line, column, isMethod);
// }
// }
//
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class QualifiedName {
// public static final Pattern CLASS_NAME_PATTERN = Pattern.compile("^[A-Z][a-zA-Z0-9_$]*$");
//
// public static QualifiedName create(String value, Metadata metadata) {
// return new AutoValue_ReferencedClassesParser_QualifiedName(value, metadata);
// }
//
// public abstract String value();
//
// public abstract Metadata metadata();
//
// @Memoized
// public ImmutableList<String> parts() {
// return ImmutableList.copyOf(DOT_SPLITTER.split(value()));
// }
//
// private static int findTopLevelName(List<String> parts) {
// for (int i = 0; i < parts.size(); i++) {
// String part = parts.get(i);
// if (CLASS_NAME_PATTERN.matcher(part).matches()) {
// // if i == 0, 's' starts with a capitalized-camel name,
// // e.g., "MobileLocalDetailsJslayoutProto".
// return i > 0 ? i : -1;
// }
// if (isLowerCase(part)) {
// continue;
// }
// return -1;
// }
// return -1;
// }
//
// /**
// * "java.util.Map" => "java.util.Map" "java.util.Map.Entry" => "java.util.Map"
// * "org.mockito.Mockito.mock" => "org.mockito.Mockito"
// */
// public QualifiedName getTopLevelQualifiedName() {
// return create(DOT_JOINER.join(parts().subList(0, findTopLevelName(parts()) + 1)), metadata());
// }
// }
//
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class SimpleName {
// public abstract String value();
//
// public abstract Metadata metadata();
//
// public static SimpleName create(String value, Metadata metadata) {
// return new AutoValue_ReferencedClassesParser_SimpleName(value, metadata);
// }
// }
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/JavaSourceFileParser.java
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Iterables.any;
import static com.google.common.collect.Iterables.getLast;
import static com.google.common.collect.Iterables.getOnlyElement;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.Files.readAllBytes;
import com.google.common.base.Strings;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Ordering;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.ImmutableGraph;
import com.google.common.graph.MutableGraph;
import com.google.devtools.build.bfg.ReferencedClassesParser.Metadata;
import com.google.devtools.build.bfg.ReferencedClassesParser.QualifiedName;
import com.google.devtools.build.bfg.ReferencedClassesParser.SimpleName;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.eclipse.jdt.core.dom.AbstractTypeDeclaration;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.PrimitiveType;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.Type;
ImmutableSet<Path> oneRulePerPackageRoots,
ImmutableSet.Builder<String> unresolvedClassNames,
MutableGraph<String> classToClass,
ImmutableMap.Builder<String, String> classToFile,
ImmutableMap.Builder<String, String> fileToRuleKind)
throws IOException {
HashMultimap<Path, String> dirToClass = HashMultimap.create();
for (Path srcFilePath : absoluteSourceFilePaths) {
ReferencedClassesParser parser =
new ReferencedClassesParser(
srcFilePath.getFileName().toString(),
new String(readAllBytes(srcFilePath), UTF_8),
contentRoots);
checkState(parser.isSuccessful);
if (Strings.isNullOrEmpty(parser.fullyQualifiedClassName)) {
// The file doesn't contain any classes, skip it. This happens for package-info.java files.
continue;
}
String qualifiedSrc = stripInnerClassFromName(parser.fullyQualifiedClassName);
dirToClass.put(srcFilePath.getParent(), parser.fullyQualifiedClassName);
boolean hasEdges = false;
classToFile.put(qualifiedSrc, srcFilePath.toString());
for (QualifiedName qualifiedDst : parser.qualifiedTopLevelNames) {
if (!qualifiedSrc.equals(qualifiedDst.value())) {
classToClass.putEdge(qualifiedSrc, qualifiedDst.value());
hasEdges = true;
}
}
|
for (SimpleName name : parser.unresolvedClassNames) {
|
bazelbuild/BUILD_file_generator
|
lang/java/src/main/java/com/google/devtools/build/bfg/JavaSourceFileParser.java
|
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class Metadata {
// static final Metadata EMPTY = create(0, 0, false);
//
// /** Line where a simple/qualified name starts. */
// public abstract int line();
//
// /** Column where a simple/qualified name starts. */
// public abstract int column();
//
// public abstract boolean isMethod();
//
// public static Metadata create(int line, int column, boolean isMethod) {
// return new AutoValue_ReferencedClassesParser_Metadata(line, column, isMethod);
// }
// }
//
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class QualifiedName {
// public static final Pattern CLASS_NAME_PATTERN = Pattern.compile("^[A-Z][a-zA-Z0-9_$]*$");
//
// public static QualifiedName create(String value, Metadata metadata) {
// return new AutoValue_ReferencedClassesParser_QualifiedName(value, metadata);
// }
//
// public abstract String value();
//
// public abstract Metadata metadata();
//
// @Memoized
// public ImmutableList<String> parts() {
// return ImmutableList.copyOf(DOT_SPLITTER.split(value()));
// }
//
// private static int findTopLevelName(List<String> parts) {
// for (int i = 0; i < parts.size(); i++) {
// String part = parts.get(i);
// if (CLASS_NAME_PATTERN.matcher(part).matches()) {
// // if i == 0, 's' starts with a capitalized-camel name,
// // e.g., "MobileLocalDetailsJslayoutProto".
// return i > 0 ? i : -1;
// }
// if (isLowerCase(part)) {
// continue;
// }
// return -1;
// }
// return -1;
// }
//
// /**
// * "java.util.Map" => "java.util.Map" "java.util.Map.Entry" => "java.util.Map"
// * "org.mockito.Mockito.mock" => "org.mockito.Mockito"
// */
// public QualifiedName getTopLevelQualifiedName() {
// return create(DOT_JOINER.join(parts().subList(0, findTopLevelName(parts()) + 1)), metadata());
// }
// }
//
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class SimpleName {
// public abstract String value();
//
// public abstract Metadata metadata();
//
// public static SimpleName create(String value, Metadata metadata) {
// return new AutoValue_ReferencedClassesParser_SimpleName(value, metadata);
// }
// }
|
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Iterables.any;
import static com.google.common.collect.Iterables.getLast;
import static com.google.common.collect.Iterables.getOnlyElement;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.Files.readAllBytes;
import com.google.common.base.Strings;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Ordering;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.ImmutableGraph;
import com.google.common.graph.MutableGraph;
import com.google.devtools.build.bfg.ReferencedClassesParser.Metadata;
import com.google.devtools.build.bfg.ReferencedClassesParser.QualifiedName;
import com.google.devtools.build.bfg.ReferencedClassesParser.SimpleName;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.eclipse.jdt.core.dom.AbstractTypeDeclaration;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.PrimitiveType;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.Type;
|
getOnlyElement((List<SingleVariableDeclaration>) methodDeclaration.parameters());
IVariableBinding vb = pt.resolveBinding();
if (vb == null) {
return false;
}
ITypeBinding tb = vb.getType();
return tb != null && "java.lang.String[]".equals(tb.getQualifiedName());
}
/** Create a cycle in 'graph' comprised of classes from 'classes'. */
private static void putOnCycle(Collection<String> classes, MutableGraph<String> graph) {
if (classes.size() == 1) {
return;
}
ImmutableList<String> sortedClasses = Ordering.natural().immutableSortedCopy(classes);
for (int i = 1; i < sortedClasses.size(); i++) {
graph.putEdge(sortedClasses.get(i - 1), sortedClasses.get(i));
}
graph.putEdge(getLast(sortedClasses), sortedClasses.get(0));
}
/**
* Given an arbitrary class name, if the class name is fully qualified, then it returns the fully
* qualified name of the top level class. If the fully qualified name has no package, or if it is
* a simple name, then it simply returns the top level class name.
*/
private static String stripInnerClassFromName(String className) {
QualifiedName topLevelQualifiedName =
|
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class Metadata {
// static final Metadata EMPTY = create(0, 0, false);
//
// /** Line where a simple/qualified name starts. */
// public abstract int line();
//
// /** Column where a simple/qualified name starts. */
// public abstract int column();
//
// public abstract boolean isMethod();
//
// public static Metadata create(int line, int column, boolean isMethod) {
// return new AutoValue_ReferencedClassesParser_Metadata(line, column, isMethod);
// }
// }
//
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class QualifiedName {
// public static final Pattern CLASS_NAME_PATTERN = Pattern.compile("^[A-Z][a-zA-Z0-9_$]*$");
//
// public static QualifiedName create(String value, Metadata metadata) {
// return new AutoValue_ReferencedClassesParser_QualifiedName(value, metadata);
// }
//
// public abstract String value();
//
// public abstract Metadata metadata();
//
// @Memoized
// public ImmutableList<String> parts() {
// return ImmutableList.copyOf(DOT_SPLITTER.split(value()));
// }
//
// private static int findTopLevelName(List<String> parts) {
// for (int i = 0; i < parts.size(); i++) {
// String part = parts.get(i);
// if (CLASS_NAME_PATTERN.matcher(part).matches()) {
// // if i == 0, 's' starts with a capitalized-camel name,
// // e.g., "MobileLocalDetailsJslayoutProto".
// return i > 0 ? i : -1;
// }
// if (isLowerCase(part)) {
// continue;
// }
// return -1;
// }
// return -1;
// }
//
// /**
// * "java.util.Map" => "java.util.Map" "java.util.Map.Entry" => "java.util.Map"
// * "org.mockito.Mockito.mock" => "org.mockito.Mockito"
// */
// public QualifiedName getTopLevelQualifiedName() {
// return create(DOT_JOINER.join(parts().subList(0, findTopLevelName(parts()) + 1)), metadata());
// }
// }
//
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/ReferencedClassesParser.java
// @AutoValue
// public abstract static class SimpleName {
// public abstract String value();
//
// public abstract Metadata metadata();
//
// public static SimpleName create(String value, Metadata metadata) {
// return new AutoValue_ReferencedClassesParser_SimpleName(value, metadata);
// }
// }
// Path: lang/java/src/main/java/com/google/devtools/build/bfg/JavaSourceFileParser.java
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Iterables.any;
import static com.google.common.collect.Iterables.getLast;
import static com.google.common.collect.Iterables.getOnlyElement;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.Files.readAllBytes;
import com.google.common.base.Strings;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Ordering;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.ImmutableGraph;
import com.google.common.graph.MutableGraph;
import com.google.devtools.build.bfg.ReferencedClassesParser.Metadata;
import com.google.devtools.build.bfg.ReferencedClassesParser.QualifiedName;
import com.google.devtools.build.bfg.ReferencedClassesParser.SimpleName;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.eclipse.jdt.core.dom.AbstractTypeDeclaration;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.PrimitiveType;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.Type;
getOnlyElement((List<SingleVariableDeclaration>) methodDeclaration.parameters());
IVariableBinding vb = pt.resolveBinding();
if (vb == null) {
return false;
}
ITypeBinding tb = vb.getType();
return tb != null && "java.lang.String[]".equals(tb.getQualifiedName());
}
/** Create a cycle in 'graph' comprised of classes from 'classes'. */
private static void putOnCycle(Collection<String> classes, MutableGraph<String> graph) {
if (classes.size() == 1) {
return;
}
ImmutableList<String> sortedClasses = Ordering.natural().immutableSortedCopy(classes);
for (int i = 1; i < sortedClasses.size(); i++) {
graph.putEdge(sortedClasses.get(i - 1), sortedClasses.get(i));
}
graph.putEdge(getLast(sortedClasses), sortedClasses.get(0));
}
/**
* Given an arbitrary class name, if the class name is fully qualified, then it returns the fully
* qualified name of the top level class. If the fully qualified name has no package, or if it is
* a simple name, then it simply returns the top level class name.
*/
private static String stripInnerClassFromName(String className) {
QualifiedName topLevelQualifiedName =
|
QualifiedName.create(className, Metadata.EMPTY).getTopLevelQualifiedName();
|
bazelbuild/BUILD_file_generator
|
src/main/java/com/google/devtools/build/bfg/ClassToSourceGraphConsolidator.java
|
// Path: src/main/java/com/google/devtools/build/bfg/ClassNameUtilities.java
// static boolean isInnerClass(String className) {
// return className.contains("$");
// }
//
// Path: src/main/java/com/google/devtools/build/bfg/GraphProcessor.java
// static class GraphProcessorException extends RuntimeException {
// GraphProcessorException(String message) {
// super(message);
// }
// }
|
import static com.google.devtools.build.bfg.ClassNameUtilities.isInnerClass;
import com.google.common.graph.Graph;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.ImmutableGraph;
import com.google.common.graph.MutableGraph;
import com.google.devtools.build.bfg.GraphProcessor.GraphProcessorException;
import java.nio.file.Path;
import java.util.Map;
|
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.bfg;
/**
* Utility class to convert a directed graph of class names to a directed graph of source files.
*
* <p>For example, say we had the following mapping
*
* <pre>
* digraph {
* com.A -> com.C
* com.A$inner -> com.B
* com.B -> com.C
* com.C -> com.A
* }
*
* classToSourceFileMap {
* com.A -> com/A.java
* com.B -> com/B.java
* com.C -> com/C.java
* }
* </pre>
*
* Then it would output the following classGraph
*
* <pre>
* digraph {
* com/A.java -> com/C.java
* com/A.java -> com/B.java
* com/B.java -> com/C.java
* com/C.java -> com/A.java
* }
* </pre>
*/
public class ClassToSourceGraphConsolidator {
/**
* Converts the class file dependency graph into the source file dependency graph, by
* consolidating classes from the same source file. Given as input:
*
* <p>ul>
* <li>a directed graph where the nodes are classes (both inner and outer) and edges are
* dependencies between said classes
* <li>a mapping between outer class files and source files.
* </ul>
*
* This function outputs a directed graph where the nodes are source files and the edges are
* dependencies between said source files.
*/
// TODO(bazel-team): Migrate this function into Guava graph library
public static ImmutableGraph<Path> map(
Graph<String> classGraph, Map<String, Path> classToSourceFileMap) {
MutableGraph<Path> graph = GraphBuilder.directed().allowsSelfLoops(false).build();
for (String sourceNode : classGraph.nodes()) {
|
// Path: src/main/java/com/google/devtools/build/bfg/ClassNameUtilities.java
// static boolean isInnerClass(String className) {
// return className.contains("$");
// }
//
// Path: src/main/java/com/google/devtools/build/bfg/GraphProcessor.java
// static class GraphProcessorException extends RuntimeException {
// GraphProcessorException(String message) {
// super(message);
// }
// }
// Path: src/main/java/com/google/devtools/build/bfg/ClassToSourceGraphConsolidator.java
import static com.google.devtools.build.bfg.ClassNameUtilities.isInnerClass;
import com.google.common.graph.Graph;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.ImmutableGraph;
import com.google.common.graph.MutableGraph;
import com.google.devtools.build.bfg.GraphProcessor.GraphProcessorException;
import java.nio.file.Path;
import java.util.Map;
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.bfg;
/**
* Utility class to convert a directed graph of class names to a directed graph of source files.
*
* <p>For example, say we had the following mapping
*
* <pre>
* digraph {
* com.A -> com.C
* com.A$inner -> com.B
* com.B -> com.C
* com.C -> com.A
* }
*
* classToSourceFileMap {
* com.A -> com/A.java
* com.B -> com/B.java
* com.C -> com/C.java
* }
* </pre>
*
* Then it would output the following classGraph
*
* <pre>
* digraph {
* com/A.java -> com/C.java
* com/A.java -> com/B.java
* com/B.java -> com/C.java
* com/C.java -> com/A.java
* }
* </pre>
*/
public class ClassToSourceGraphConsolidator {
/**
* Converts the class file dependency graph into the source file dependency graph, by
* consolidating classes from the same source file. Given as input:
*
* <p>ul>
* <li>a directed graph where the nodes are classes (both inner and outer) and edges are
* dependencies between said classes
* <li>a mapping between outer class files and source files.
* </ul>
*
* This function outputs a directed graph where the nodes are source files and the edges are
* dependencies between said source files.
*/
// TODO(bazel-team): Migrate this function into Guava graph library
public static ImmutableGraph<Path> map(
Graph<String> classGraph, Map<String, Path> classToSourceFileMap) {
MutableGraph<Path> graph = GraphBuilder.directed().allowsSelfLoops(false).build();
for (String sourceNode : classGraph.nodes()) {
|
if (isInnerClass(sourceNode)) {
|
bazelbuild/BUILD_file_generator
|
src/main/java/com/google/devtools/build/bfg/ClassToSourceGraphConsolidator.java
|
// Path: src/main/java/com/google/devtools/build/bfg/ClassNameUtilities.java
// static boolean isInnerClass(String className) {
// return className.contains("$");
// }
//
// Path: src/main/java/com/google/devtools/build/bfg/GraphProcessor.java
// static class GraphProcessorException extends RuntimeException {
// GraphProcessorException(String message) {
// super(message);
// }
// }
|
import static com.google.devtools.build.bfg.ClassNameUtilities.isInnerClass;
import com.google.common.graph.Graph;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.ImmutableGraph;
import com.google.common.graph.MutableGraph;
import com.google.devtools.build.bfg.GraphProcessor.GraphProcessorException;
import java.nio.file.Path;
import java.util.Map;
|
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.bfg;
/**
* Utility class to convert a directed graph of class names to a directed graph of source files.
*
* <p>For example, say we had the following mapping
*
* <pre>
* digraph {
* com.A -> com.C
* com.A$inner -> com.B
* com.B -> com.C
* com.C -> com.A
* }
*
* classToSourceFileMap {
* com.A -> com/A.java
* com.B -> com/B.java
* com.C -> com/C.java
* }
* </pre>
*
* Then it would output the following classGraph
*
* <pre>
* digraph {
* com/A.java -> com/C.java
* com/A.java -> com/B.java
* com/B.java -> com/C.java
* com/C.java -> com/A.java
* }
* </pre>
*/
public class ClassToSourceGraphConsolidator {
/**
* Converts the class file dependency graph into the source file dependency graph, by
* consolidating classes from the same source file. Given as input:
*
* <p>ul>
* <li>a directed graph where the nodes are classes (both inner and outer) and edges are
* dependencies between said classes
* <li>a mapping between outer class files and source files.
* </ul>
*
* This function outputs a directed graph where the nodes are source files and the edges are
* dependencies between said source files.
*/
// TODO(bazel-team): Migrate this function into Guava graph library
public static ImmutableGraph<Path> map(
Graph<String> classGraph, Map<String, Path> classToSourceFileMap) {
MutableGraph<Path> graph = GraphBuilder.directed().allowsSelfLoops(false).build();
for (String sourceNode : classGraph.nodes()) {
if (isInnerClass(sourceNode)) {
|
// Path: src/main/java/com/google/devtools/build/bfg/ClassNameUtilities.java
// static boolean isInnerClass(String className) {
// return className.contains("$");
// }
//
// Path: src/main/java/com/google/devtools/build/bfg/GraphProcessor.java
// static class GraphProcessorException extends RuntimeException {
// GraphProcessorException(String message) {
// super(message);
// }
// }
// Path: src/main/java/com/google/devtools/build/bfg/ClassToSourceGraphConsolidator.java
import static com.google.devtools.build.bfg.ClassNameUtilities.isInnerClass;
import com.google.common.graph.Graph;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.ImmutableGraph;
import com.google.common.graph.MutableGraph;
import com.google.devtools.build.bfg.GraphProcessor.GraphProcessorException;
import java.nio.file.Path;
import java.util.Map;
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.bfg;
/**
* Utility class to convert a directed graph of class names to a directed graph of source files.
*
* <p>For example, say we had the following mapping
*
* <pre>
* digraph {
* com.A -> com.C
* com.A$inner -> com.B
* com.B -> com.C
* com.C -> com.A
* }
*
* classToSourceFileMap {
* com.A -> com/A.java
* com.B -> com/B.java
* com.C -> com/C.java
* }
* </pre>
*
* Then it would output the following classGraph
*
* <pre>
* digraph {
* com/A.java -> com/C.java
* com/A.java -> com/B.java
* com/B.java -> com/C.java
* com/C.java -> com/A.java
* }
* </pre>
*/
public class ClassToSourceGraphConsolidator {
/**
* Converts the class file dependency graph into the source file dependency graph, by
* consolidating classes from the same source file. Given as input:
*
* <p>ul>
* <li>a directed graph where the nodes are classes (both inner and outer) and edges are
* dependencies between said classes
* <li>a mapping between outer class files and source files.
* </ul>
*
* This function outputs a directed graph where the nodes are source files and the edges are
* dependencies between said source files.
*/
// TODO(bazel-team): Migrate this function into Guava graph library
public static ImmutableGraph<Path> map(
Graph<String> classGraph, Map<String, Path> classToSourceFileMap) {
MutableGraph<Path> graph = GraphBuilder.directed().allowsSelfLoops(false).build();
for (String sourceNode : classGraph.nodes()) {
if (isInnerClass(sourceNode)) {
|
throw new GraphProcessorException(
|
bazelbuild/BUILD_file_generator
|
src/test/java/com/google/devtools/build/bfg/BuildozerCommandCreatorTest.java
|
// Path: src/main/java/com/google/devtools/build/bfg/BuildozerCommandCreator.java
// static ImmutableList<String> computeBuildozerCommands(Graph<BuildRule> buildRuleDAG) {
// ImmutableList.Builder<String> commands = ImmutableList.builder();
// for (BuildRule buildRule : buildRuleDAG.nodes()) {
// List<String> initialCommands = buildRule.getCreatingBuildozerCommands();
// commands.addAll(initialCommands);
// List<String> depsList = getDepsForBuildRule(buildRuleDAG, buildRule);
// if (buildRule.shouldAddDeps() && !depsList.isEmpty()) {
// commands.add(BuildozerCommand.addAttribute("deps", depsList, buildRule.label()));
// }
// }
// return commands.build();
// }
//
// Path: src/main/java/com/google/devtools/build/bfg/BuildozerCommandCreator.java
// static Iterable<Path> getBuildFilesForBuildozer(
// Graph<BuildRule> buildRuleGraph, Path workspacePath) {
// Function<BuildRule, Path> relativePathForRule =
// rule -> workspacePath.resolve(rule.label().split("//")[1].split(":")[0]);
//
// return buildRuleGraph
// .nodes()
// .stream()
// .filter(buildRule -> buildRule.shouldAddDeps())
// .map(relativePathForRule)
// .collect(toImmutableSet());
// }
|
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.bfg.BuildozerCommandCreator.computeBuildozerCommands;
import static com.google.devtools.build.bfg.BuildozerCommandCreator.getBuildFilesForBuildozer;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.MutableGraph;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
|
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.bfg;
/** Tests for {@link BuildozerCommandCreator}. */
@RunWith(JUnit4.class)
public class BuildozerCommandCreatorTest {
private static final Path DEFAULT_WORKSPACE = Paths.get("/workspace");
/**
* Tests dependency behavior when a single file depends on another file. This should result in two
* build rules, one with an empty deps field and another with a dependency.
*/
@Test
public void depsForSingleFileComponents() {
MutableGraph<BuildRule> buildRuleGraph = newGraph();
String packagePath = "/workspace/java/package/";
ProjectBuildRule src = newProjectBuildRule(packagePath, "/workspace/java/package/Example.java");
ProjectBuildRule dst = newProjectBuildRule(packagePath, "/workspace/java/package/Other.java");
buildRuleGraph.putEdge(src, dst);
|
// Path: src/main/java/com/google/devtools/build/bfg/BuildozerCommandCreator.java
// static ImmutableList<String> computeBuildozerCommands(Graph<BuildRule> buildRuleDAG) {
// ImmutableList.Builder<String> commands = ImmutableList.builder();
// for (BuildRule buildRule : buildRuleDAG.nodes()) {
// List<String> initialCommands = buildRule.getCreatingBuildozerCommands();
// commands.addAll(initialCommands);
// List<String> depsList = getDepsForBuildRule(buildRuleDAG, buildRule);
// if (buildRule.shouldAddDeps() && !depsList.isEmpty()) {
// commands.add(BuildozerCommand.addAttribute("deps", depsList, buildRule.label()));
// }
// }
// return commands.build();
// }
//
// Path: src/main/java/com/google/devtools/build/bfg/BuildozerCommandCreator.java
// static Iterable<Path> getBuildFilesForBuildozer(
// Graph<BuildRule> buildRuleGraph, Path workspacePath) {
// Function<BuildRule, Path> relativePathForRule =
// rule -> workspacePath.resolve(rule.label().split("//")[1].split(":")[0]);
//
// return buildRuleGraph
// .nodes()
// .stream()
// .filter(buildRule -> buildRule.shouldAddDeps())
// .map(relativePathForRule)
// .collect(toImmutableSet());
// }
// Path: src/test/java/com/google/devtools/build/bfg/BuildozerCommandCreatorTest.java
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.bfg.BuildozerCommandCreator.computeBuildozerCommands;
import static com.google.devtools.build.bfg.BuildozerCommandCreator.getBuildFilesForBuildozer;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.MutableGraph;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.bfg;
/** Tests for {@link BuildozerCommandCreator}. */
@RunWith(JUnit4.class)
public class BuildozerCommandCreatorTest {
private static final Path DEFAULT_WORKSPACE = Paths.get("/workspace");
/**
* Tests dependency behavior when a single file depends on another file. This should result in two
* build rules, one with an empty deps field and another with a dependency.
*/
@Test
public void depsForSingleFileComponents() {
MutableGraph<BuildRule> buildRuleGraph = newGraph();
String packagePath = "/workspace/java/package/";
ProjectBuildRule src = newProjectBuildRule(packagePath, "/workspace/java/package/Example.java");
ProjectBuildRule dst = newProjectBuildRule(packagePath, "/workspace/java/package/Other.java");
buildRuleGraph.putEdge(src, dst);
|
ImmutableList<String> actual = computeBuildozerCommands(buildRuleGraph);
|
bazelbuild/BUILD_file_generator
|
src/test/java/com/google/devtools/build/bfg/BuildozerCommandCreatorTest.java
|
// Path: src/main/java/com/google/devtools/build/bfg/BuildozerCommandCreator.java
// static ImmutableList<String> computeBuildozerCommands(Graph<BuildRule> buildRuleDAG) {
// ImmutableList.Builder<String> commands = ImmutableList.builder();
// for (BuildRule buildRule : buildRuleDAG.nodes()) {
// List<String> initialCommands = buildRule.getCreatingBuildozerCommands();
// commands.addAll(initialCommands);
// List<String> depsList = getDepsForBuildRule(buildRuleDAG, buildRule);
// if (buildRule.shouldAddDeps() && !depsList.isEmpty()) {
// commands.add(BuildozerCommand.addAttribute("deps", depsList, buildRule.label()));
// }
// }
// return commands.build();
// }
//
// Path: src/main/java/com/google/devtools/build/bfg/BuildozerCommandCreator.java
// static Iterable<Path> getBuildFilesForBuildozer(
// Graph<BuildRule> buildRuleGraph, Path workspacePath) {
// Function<BuildRule, Path> relativePathForRule =
// rule -> workspacePath.resolve(rule.label().split("//")[1].split(":")[0]);
//
// return buildRuleGraph
// .nodes()
// .stream()
// .filter(buildRule -> buildRule.shouldAddDeps())
// .map(relativePathForRule)
// .collect(toImmutableSet());
// }
|
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.bfg.BuildozerCommandCreator.computeBuildozerCommands;
import static com.google.devtools.build.bfg.BuildozerCommandCreator.getBuildFilesForBuildozer;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.MutableGraph;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
|
newProjectBuildRule("/workspace/java/package/", "/workspace/java/package/Example.java");
ExternalBuildRule dstA = ExternalBuildRule.create("//java/other:Other");
ExternalBuildRule dstB = ExternalBuildRule.create("//java/something:Something");
buildRuleGraph.putEdge(src, dstA);
buildRuleGraph.putEdge(dstA, dstB);
ImmutableList<String> actual = computeBuildozerCommands(buildRuleGraph);
assertThat(actual)
.containsExactly(
"new java_library Example|//java/package:__pkg__",
"add srcs Example.java|//java/package:Example",
"add deps //java/other:Other|//java/package:Example");
}
private MutableGraph<BuildRule> newGraph() {
return GraphBuilder.directed().allowsSelfLoops(false).build();
}
/**
* Given a DAG containing external and project rules, this test ensures Build files are only
* listed for project rules, and ignored for external rules.
*/
@Test
public void getBuildFilesForBuildozer_returnsProjectRule() {
MutableGraph<BuildRule> buildRuleGraph = newGraph();
buildRuleGraph.putEdge(
newProjectBuildRule("/workspace/java/package/", "Example.java"),
ExternalBuildRule.create("//java/other:Other"));
|
// Path: src/main/java/com/google/devtools/build/bfg/BuildozerCommandCreator.java
// static ImmutableList<String> computeBuildozerCommands(Graph<BuildRule> buildRuleDAG) {
// ImmutableList.Builder<String> commands = ImmutableList.builder();
// for (BuildRule buildRule : buildRuleDAG.nodes()) {
// List<String> initialCommands = buildRule.getCreatingBuildozerCommands();
// commands.addAll(initialCommands);
// List<String> depsList = getDepsForBuildRule(buildRuleDAG, buildRule);
// if (buildRule.shouldAddDeps() && !depsList.isEmpty()) {
// commands.add(BuildozerCommand.addAttribute("deps", depsList, buildRule.label()));
// }
// }
// return commands.build();
// }
//
// Path: src/main/java/com/google/devtools/build/bfg/BuildozerCommandCreator.java
// static Iterable<Path> getBuildFilesForBuildozer(
// Graph<BuildRule> buildRuleGraph, Path workspacePath) {
// Function<BuildRule, Path> relativePathForRule =
// rule -> workspacePath.resolve(rule.label().split("//")[1].split(":")[0]);
//
// return buildRuleGraph
// .nodes()
// .stream()
// .filter(buildRule -> buildRule.shouldAddDeps())
// .map(relativePathForRule)
// .collect(toImmutableSet());
// }
// Path: src/test/java/com/google/devtools/build/bfg/BuildozerCommandCreatorTest.java
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.bfg.BuildozerCommandCreator.computeBuildozerCommands;
import static com.google.devtools.build.bfg.BuildozerCommandCreator.getBuildFilesForBuildozer;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.MutableGraph;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
newProjectBuildRule("/workspace/java/package/", "/workspace/java/package/Example.java");
ExternalBuildRule dstA = ExternalBuildRule.create("//java/other:Other");
ExternalBuildRule dstB = ExternalBuildRule.create("//java/something:Something");
buildRuleGraph.putEdge(src, dstA);
buildRuleGraph.putEdge(dstA, dstB);
ImmutableList<String> actual = computeBuildozerCommands(buildRuleGraph);
assertThat(actual)
.containsExactly(
"new java_library Example|//java/package:__pkg__",
"add srcs Example.java|//java/package:Example",
"add deps //java/other:Other|//java/package:Example");
}
private MutableGraph<BuildRule> newGraph() {
return GraphBuilder.directed().allowsSelfLoops(false).build();
}
/**
* Given a DAG containing external and project rules, this test ensures Build files are only
* listed for project rules, and ignored for external rules.
*/
@Test
public void getBuildFilesForBuildozer_returnsProjectRule() {
MutableGraph<BuildRule> buildRuleGraph = newGraph();
buildRuleGraph.putEdge(
newProjectBuildRule("/workspace/java/package/", "Example.java"),
ExternalBuildRule.create("//java/other:Other"));
|
Iterable<Path> actual = getBuildFilesForBuildozer(buildRuleGraph, DEFAULT_WORKSPACE);
|
bazelbuild/BUILD_file_generator
|
src/test/java/com/google/devtools/build/bfg/ClassToSourceGraphConsolidatorTest.java
|
// Path: src/main/java/com/google/devtools/build/bfg/GraphProcessor.java
// static class GraphProcessorException extends RuntimeException {
// GraphProcessorException(String message) {
// super(message);
// }
// }
|
import static com.google.common.truth.Truth.assertThat;
import static junit.framework.TestCase.fail;
import com.google.common.collect.ImmutableMap;
import com.google.common.graph.Graph;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.MutableGraph;
import com.google.devtools.build.bfg.GraphProcessor.GraphProcessorException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
|
Graph<Path> actual = ClassToSourceGraphConsolidator.map(graph, map);
MutableGraph<Path> expected = newGraph(Path.class);
expected.addNode(Paths.get("A.java"));
assertEquivalent(actual, expected);
}
@Test
public void classGraphWithOnlyOneClassResultingInSingleSourceFile() {
MutableGraph<String> graph = newGraph(String.class);
graph.addNode("com.A");
Map<String, Path> map = ImmutableMap.of("com.A", Paths.get("A.java"));
Graph<Path> actual = ClassToSourceGraphConsolidator.map(graph, map);
MutableGraph<Path> expected = newGraph(Path.class);
expected.addNode(Paths.get("A.java"));
assertEquivalent(actual, expected);
}
@Test
public void classGraphWithInnerClasses_throwsException() {
MutableGraph<String> graph = newGraph(String.class);
graph.putEdge("com.A$inner", "com.E");
Map<String, Path> map =
ImmutableMap.of("com.A", Paths.get("A.java"), "com.E", Paths.get("E.java"));
try {
ClassToSourceGraphConsolidator.map(graph, map);
fail("Expected GraphProcessorException but nothing was thrown.");
|
// Path: src/main/java/com/google/devtools/build/bfg/GraphProcessor.java
// static class GraphProcessorException extends RuntimeException {
// GraphProcessorException(String message) {
// super(message);
// }
// }
// Path: src/test/java/com/google/devtools/build/bfg/ClassToSourceGraphConsolidatorTest.java
import static com.google.common.truth.Truth.assertThat;
import static junit.framework.TestCase.fail;
import com.google.common.collect.ImmutableMap;
import com.google.common.graph.Graph;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.MutableGraph;
import com.google.devtools.build.bfg.GraphProcessor.GraphProcessorException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
Graph<Path> actual = ClassToSourceGraphConsolidator.map(graph, map);
MutableGraph<Path> expected = newGraph(Path.class);
expected.addNode(Paths.get("A.java"));
assertEquivalent(actual, expected);
}
@Test
public void classGraphWithOnlyOneClassResultingInSingleSourceFile() {
MutableGraph<String> graph = newGraph(String.class);
graph.addNode("com.A");
Map<String, Path> map = ImmutableMap.of("com.A", Paths.get("A.java"));
Graph<Path> actual = ClassToSourceGraphConsolidator.map(graph, map);
MutableGraph<Path> expected = newGraph(Path.class);
expected.addNode(Paths.get("A.java"));
assertEquivalent(actual, expected);
}
@Test
public void classGraphWithInnerClasses_throwsException() {
MutableGraph<String> graph = newGraph(String.class);
graph.putEdge("com.A$inner", "com.E");
Map<String, Path> map =
ImmutableMap.of("com.A", Paths.get("A.java"), "com.E", Paths.get("E.java"));
try {
ClassToSourceGraphConsolidator.map(graph, map);
fail("Expected GraphProcessorException but nothing was thrown.");
|
} catch (GraphProcessorException e) {
|
stephenostermiller/ostermillerutils
|
src/test/java/com/Ostermiller/util/DateTimeLexerTest.java
|
// Path: src/main/java/com/Ostermiller/util/DateTimeToken.java
// public enum DateTimeTokenType {
// ERROR,
// NUMBER,
// WORD,
// PUNCTUATION,
// SPACE,
// APOS_YEAR,
// ORDINAL_DAY,
// }
|
import java.io.IOException;
import com.Ostermiller.util.DateTimeToken.DateTimeTokenType;
import java.io.StringReader;
import junit.framework.TestCase;
|
/*
* Copyright (C) 2010 Stephen Ostermiller
* http://ostermiller.org/contact.pl?regarding=Java+Utilities
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* See LICENSE.txt for details.
*/
package com.Ostermiller.util;
/**
*
* @author Stephen Ostermiller http://ostermiller.org/contact.pl?regarding=Java+Utilities
* @since ostermillerutils 1.08.00
*/
public class DateTimeLexerTest extends TestCase {
public void testInt(){
|
// Path: src/main/java/com/Ostermiller/util/DateTimeToken.java
// public enum DateTimeTokenType {
// ERROR,
// NUMBER,
// WORD,
// PUNCTUATION,
// SPACE,
// APOS_YEAR,
// ORDINAL_DAY,
// }
// Path: src/test/java/com/Ostermiller/util/DateTimeLexerTest.java
import java.io.IOException;
import com.Ostermiller.util.DateTimeToken.DateTimeTokenType;
import java.io.StringReader;
import junit.framework.TestCase;
/*
* Copyright (C) 2010 Stephen Ostermiller
* http://ostermiller.org/contact.pl?regarding=Java+Utilities
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* See LICENSE.txt for details.
*/
package com.Ostermiller.util;
/**
*
* @author Stephen Ostermiller http://ostermiller.org/contact.pl?regarding=Java+Utilities
* @since ostermillerutils 1.08.00
*/
public class DateTimeLexerTest extends TestCase {
public void testInt(){
|
assertEquals(DateTimeTokenType.NUMBER, getFirstToken("1").getType());
|
stephenostermiller/ostermillerutils
|
src/test/java/com/Ostermiller/util/DateTimeParseTest.java
|
// Path: src/main/java/com/Ostermiller/util/DateTimeParse.java
// public enum Field {
// YEAR,
// MONTH,
// DAY
// }
|
import java.util.TimeZone;
import java.util.Locale;
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.Date;
import junit.framework.TestCase;
import com.Ostermiller.util.DateTimeParse.Field;
|
}
public void testBc(){
assertJustDateEqualsBc("0200-01-01", parse("200 BC"));
assertJustDateEqualsBc("1431-01-10", parse("Jan 10 1431 BC"));
}
public void testBce(){
assertJustDateEqualsBc("0200-01-01", parse("200 BCE"));
assertJustDateEqualsBc("1431-01-10", parse("Jan 10 1431 BCE"));
}
public void testAd(){
assertJustDateEquals("0200-01-01", parse("200 AD"));
assertJustDateEquals("1431-01-10", parse("Jan 10 1431 AD"));
}
public void testCe(){
assertJustDateEquals("0200-01-01", parse("200 CE"));
assertJustDateEquals("1431-01-10", parse("Jan 10 1431 CE"));
}
public void testAdBcCaseInsensitive(){
assertJustDateEqualsBc("0200-01-01", parse("200 bc"));
assertJustDateEqualsBc("1431-01-10", parse("Jan 10 1431 BcE"));
assertJustDateEquals("0200-01-01", parse("200 aD"));
assertJustDateEquals("1431-01-10", parse("Jan 10 1431 Ce"));
}
public void testFieldOrderMonth(){
|
// Path: src/main/java/com/Ostermiller/util/DateTimeParse.java
// public enum Field {
// YEAR,
// MONTH,
// DAY
// }
// Path: src/test/java/com/Ostermiller/util/DateTimeParseTest.java
import java.util.TimeZone;
import java.util.Locale;
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.Date;
import junit.framework.TestCase;
import com.Ostermiller.util.DateTimeParse.Field;
}
public void testBc(){
assertJustDateEqualsBc("0200-01-01", parse("200 BC"));
assertJustDateEqualsBc("1431-01-10", parse("Jan 10 1431 BC"));
}
public void testBce(){
assertJustDateEqualsBc("0200-01-01", parse("200 BCE"));
assertJustDateEqualsBc("1431-01-10", parse("Jan 10 1431 BCE"));
}
public void testAd(){
assertJustDateEquals("0200-01-01", parse("200 AD"));
assertJustDateEquals("1431-01-10", parse("Jan 10 1431 AD"));
}
public void testCe(){
assertJustDateEquals("0200-01-01", parse("200 CE"));
assertJustDateEquals("1431-01-10", parse("Jan 10 1431 CE"));
}
public void testAdBcCaseInsensitive(){
assertJustDateEqualsBc("0200-01-01", parse("200 bc"));
assertJustDateEqualsBc("1431-01-10", parse("Jan 10 1431 BcE"));
assertJustDateEquals("0200-01-01", parse("200 aD"));
assertJustDateEquals("1431-01-10", parse("Jan 10 1431 Ce"));
}
public void testFieldOrderMonth(){
|
DateTimeParse p = getParser(new Field[]{Field.MONTH});
|
stephenostermiller/ostermillerutils
|
src/main/java/com/Ostermiller/util/DateTimeParse.java
|
// Path: src/main/java/com/Ostermiller/util/DateTimeToken.java
// public enum DateTimeTokenType {
// ERROR,
// NUMBER,
// WORD,
// PUNCTUATION,
// SPACE,
// APOS_YEAR,
// ORDINAL_DAY,
// }
|
import java.util.TimeZone;
import com.Ostermiller.util.DateTimeToken.DateTimeTokenType;
import java.io.*;
import java.util.*;
|
if (!i.hasNext()){
switch(state){
case TIME_STATE_HOUR_SEP:
case TIME_STATE_MINUTE_SEP: {
return false;
}
case TIME_STATE_MINUTE:
case TIME_STATE_SECOND: {
end = tokens.size();
state = TIME_STATE_DONE;
}
default: break;
}
}
}
if (state == TIME_STATE_DONE){
int position = 0;
for(Iterator<DateTimeToken> i = tokens.iterator(); i.hasNext(); position++){
i.next();
if (position >= start && position < end){
i.remove();
}
}
}
return true;
}
private boolean setPreferredDateNumberFields(WorkingDateTime work, LinkedList<DateTimeToken> tokens){
for(Iterator<DateTimeToken> i = tokens.iterator(); i.hasNext();){
DateTimeToken token = i.next();
|
// Path: src/main/java/com/Ostermiller/util/DateTimeToken.java
// public enum DateTimeTokenType {
// ERROR,
// NUMBER,
// WORD,
// PUNCTUATION,
// SPACE,
// APOS_YEAR,
// ORDINAL_DAY,
// }
// Path: src/main/java/com/Ostermiller/util/DateTimeParse.java
import java.util.TimeZone;
import com.Ostermiller.util.DateTimeToken.DateTimeTokenType;
import java.io.*;
import java.util.*;
if (!i.hasNext()){
switch(state){
case TIME_STATE_HOUR_SEP:
case TIME_STATE_MINUTE_SEP: {
return false;
}
case TIME_STATE_MINUTE:
case TIME_STATE_SECOND: {
end = tokens.size();
state = TIME_STATE_DONE;
}
default: break;
}
}
}
if (state == TIME_STATE_DONE){
int position = 0;
for(Iterator<DateTimeToken> i = tokens.iterator(); i.hasNext(); position++){
i.next();
if (position >= start && position < end){
i.remove();
}
}
}
return true;
}
private boolean setPreferredDateNumberFields(WorkingDateTime work, LinkedList<DateTimeToken> tokens){
for(Iterator<DateTimeToken> i = tokens.iterator(); i.hasNext();){
DateTimeToken token = i.next();
|
if (token.getType() == DateTimeTokenType.NUMBER){
|
Metrink/croquet
|
croquet-examples/src/main/java/com/metrink/croquet/examples/crm/CrmModule.java
|
// Path: croquet-examples/src/main/java/com/metrink/croquet/examples/crm/data/CompanyBean.java
// @Entity
// @Table(name = "companies")
// public class CompanyBean implements Identifiable, Serializable {
//
// private static final long serialVersionUID = 6782475394818123635L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// @Column(unique = true, nullable = false)
// private Integer companyId;
//
// @Column(nullable = false) private String name;
// @Column(nullable = false) private String street;
// @Column(nullable = false) private String city;
// @Column(nullable = false) private String state;
// @Column(nullable = false) private String zip;
//
// @Override
// public Integer getId() {
// return companyId;
// }
//
// public Integer getCompanyId() {
// return companyId;
// }
//
// public void setCompanyId(final Integer companyId) {
// this.companyId = companyId;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public String getStreet() {
// return street;
// }
//
// public void setStreet(final String street) {
// this.street = street;
// }
//
// public String getCity() {
// return city;
// }
//
// public void setCity(final String city) {
// this.city = city;
// }
//
// public String getState() {
// return state;
// }
//
// public void setState(final String state) {
// this.state = state;
// }
//
// public String getZip() {
// return zip;
// }
//
// public void setZip(final String zip) {
// this.zip = zip;
// }
//
// }
//
// Path: croquet-examples/src/main/java/com/metrink/croquet/examples/crm/data/GenericDataProvider.java
// public interface GenericDataProviderFactory<T2 extends Serializable> {
// /**
// * Factory method for creating a new {@link GenericDataProvider} given a type.
// * @param type the entity type to associate with this {@link GenericDataProvider}.
// * @return an {@link GenericDataProvider}.
// */
// public GenericDataProvider<T2> create(final Class<T2> type);
// }
//
// Path: croquet-examples/src/main/java/com/metrink/croquet/examples/crm/data/PeopleDataProvider.java
// public interface PeopleDataProviderFactory {
// /**
// * Factory method for creating a new {@link PeopleDataProvider}.
// * @param companyId company to filter on, or null for everything.
// * @return an {@link PeopleDataProvider}.
// */
// public PeopleDataProvider create(final Integer companyId);
// }
|
import com.google.inject.AbstractModule;
import com.google.inject.TypeLiteral;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import com.google.inject.name.Names;
import com.metrink.croquet.examples.crm.data.CompanyBean;
import com.metrink.croquet.examples.crm.data.GenericDataProvider.GenericDataProviderFactory;
import com.metrink.croquet.examples.crm.data.PeopleDataProvider.PeopleDataProviderFactory;
|
package com.metrink.croquet.examples.crm;
/**
* A Guice module that binds dependencies.
*/
public class CrmModule extends AbstractModule {
private final CrmSettings settings;
/**
* Constructor that takes a settings instance.
* @param settings the settings.
*/
public CrmModule(final CrmSettings settings) {
this.settings = settings;
}
@Override
protected void configure() {
bind(String.class).annotatedWith(Names.named("current-user")).toInstance(settings.getCurrentUser());
|
// Path: croquet-examples/src/main/java/com/metrink/croquet/examples/crm/data/CompanyBean.java
// @Entity
// @Table(name = "companies")
// public class CompanyBean implements Identifiable, Serializable {
//
// private static final long serialVersionUID = 6782475394818123635L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// @Column(unique = true, nullable = false)
// private Integer companyId;
//
// @Column(nullable = false) private String name;
// @Column(nullable = false) private String street;
// @Column(nullable = false) private String city;
// @Column(nullable = false) private String state;
// @Column(nullable = false) private String zip;
//
// @Override
// public Integer getId() {
// return companyId;
// }
//
// public Integer getCompanyId() {
// return companyId;
// }
//
// public void setCompanyId(final Integer companyId) {
// this.companyId = companyId;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public String getStreet() {
// return street;
// }
//
// public void setStreet(final String street) {
// this.street = street;
// }
//
// public String getCity() {
// return city;
// }
//
// public void setCity(final String city) {
// this.city = city;
// }
//
// public String getState() {
// return state;
// }
//
// public void setState(final String state) {
// this.state = state;
// }
//
// public String getZip() {
// return zip;
// }
//
// public void setZip(final String zip) {
// this.zip = zip;
// }
//
// }
//
// Path: croquet-examples/src/main/java/com/metrink/croquet/examples/crm/data/GenericDataProvider.java
// public interface GenericDataProviderFactory<T2 extends Serializable> {
// /**
// * Factory method for creating a new {@link GenericDataProvider} given a type.
// * @param type the entity type to associate with this {@link GenericDataProvider}.
// * @return an {@link GenericDataProvider}.
// */
// public GenericDataProvider<T2> create(final Class<T2> type);
// }
//
// Path: croquet-examples/src/main/java/com/metrink/croquet/examples/crm/data/PeopleDataProvider.java
// public interface PeopleDataProviderFactory {
// /**
// * Factory method for creating a new {@link PeopleDataProvider}.
// * @param companyId company to filter on, or null for everything.
// * @return an {@link PeopleDataProvider}.
// */
// public PeopleDataProvider create(final Integer companyId);
// }
// Path: croquet-examples/src/main/java/com/metrink/croquet/examples/crm/CrmModule.java
import com.google.inject.AbstractModule;
import com.google.inject.TypeLiteral;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import com.google.inject.name.Names;
import com.metrink.croquet.examples.crm.data.CompanyBean;
import com.metrink.croquet.examples.crm.data.GenericDataProvider.GenericDataProviderFactory;
import com.metrink.croquet.examples.crm.data.PeopleDataProvider.PeopleDataProviderFactory;
package com.metrink.croquet.examples.crm;
/**
* A Guice module that binds dependencies.
*/
public class CrmModule extends AbstractModule {
private final CrmSettings settings;
/**
* Constructor that takes a settings instance.
* @param settings the settings.
*/
public CrmModule(final CrmSettings settings) {
this.settings = settings;
}
@Override
protected void configure() {
bind(String.class).annotatedWith(Names.named("current-user")).toInstance(settings.getCurrentUser());
|
install(new FactoryModuleBuilder().build(PeopleDataProviderFactory.class));
|
Metrink/croquet
|
croquet-examples/src/main/java/com/metrink/croquet/examples/crm/CrmModule.java
|
// Path: croquet-examples/src/main/java/com/metrink/croquet/examples/crm/data/CompanyBean.java
// @Entity
// @Table(name = "companies")
// public class CompanyBean implements Identifiable, Serializable {
//
// private static final long serialVersionUID = 6782475394818123635L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// @Column(unique = true, nullable = false)
// private Integer companyId;
//
// @Column(nullable = false) private String name;
// @Column(nullable = false) private String street;
// @Column(nullable = false) private String city;
// @Column(nullable = false) private String state;
// @Column(nullable = false) private String zip;
//
// @Override
// public Integer getId() {
// return companyId;
// }
//
// public Integer getCompanyId() {
// return companyId;
// }
//
// public void setCompanyId(final Integer companyId) {
// this.companyId = companyId;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public String getStreet() {
// return street;
// }
//
// public void setStreet(final String street) {
// this.street = street;
// }
//
// public String getCity() {
// return city;
// }
//
// public void setCity(final String city) {
// this.city = city;
// }
//
// public String getState() {
// return state;
// }
//
// public void setState(final String state) {
// this.state = state;
// }
//
// public String getZip() {
// return zip;
// }
//
// public void setZip(final String zip) {
// this.zip = zip;
// }
//
// }
//
// Path: croquet-examples/src/main/java/com/metrink/croquet/examples/crm/data/GenericDataProvider.java
// public interface GenericDataProviderFactory<T2 extends Serializable> {
// /**
// * Factory method for creating a new {@link GenericDataProvider} given a type.
// * @param type the entity type to associate with this {@link GenericDataProvider}.
// * @return an {@link GenericDataProvider}.
// */
// public GenericDataProvider<T2> create(final Class<T2> type);
// }
//
// Path: croquet-examples/src/main/java/com/metrink/croquet/examples/crm/data/PeopleDataProvider.java
// public interface PeopleDataProviderFactory {
// /**
// * Factory method for creating a new {@link PeopleDataProvider}.
// * @param companyId company to filter on, or null for everything.
// * @return an {@link PeopleDataProvider}.
// */
// public PeopleDataProvider create(final Integer companyId);
// }
|
import com.google.inject.AbstractModule;
import com.google.inject.TypeLiteral;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import com.google.inject.name.Names;
import com.metrink.croquet.examples.crm.data.CompanyBean;
import com.metrink.croquet.examples.crm.data.GenericDataProvider.GenericDataProviderFactory;
import com.metrink.croquet.examples.crm.data.PeopleDataProvider.PeopleDataProviderFactory;
|
package com.metrink.croquet.examples.crm;
/**
* A Guice module that binds dependencies.
*/
public class CrmModule extends AbstractModule {
private final CrmSettings settings;
/**
* Constructor that takes a settings instance.
* @param settings the settings.
*/
public CrmModule(final CrmSettings settings) {
this.settings = settings;
}
@Override
protected void configure() {
bind(String.class).annotatedWith(Names.named("current-user")).toInstance(settings.getCurrentUser());
install(new FactoryModuleBuilder().build(PeopleDataProviderFactory.class));
|
// Path: croquet-examples/src/main/java/com/metrink/croquet/examples/crm/data/CompanyBean.java
// @Entity
// @Table(name = "companies")
// public class CompanyBean implements Identifiable, Serializable {
//
// private static final long serialVersionUID = 6782475394818123635L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// @Column(unique = true, nullable = false)
// private Integer companyId;
//
// @Column(nullable = false) private String name;
// @Column(nullable = false) private String street;
// @Column(nullable = false) private String city;
// @Column(nullable = false) private String state;
// @Column(nullable = false) private String zip;
//
// @Override
// public Integer getId() {
// return companyId;
// }
//
// public Integer getCompanyId() {
// return companyId;
// }
//
// public void setCompanyId(final Integer companyId) {
// this.companyId = companyId;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public String getStreet() {
// return street;
// }
//
// public void setStreet(final String street) {
// this.street = street;
// }
//
// public String getCity() {
// return city;
// }
//
// public void setCity(final String city) {
// this.city = city;
// }
//
// public String getState() {
// return state;
// }
//
// public void setState(final String state) {
// this.state = state;
// }
//
// public String getZip() {
// return zip;
// }
//
// public void setZip(final String zip) {
// this.zip = zip;
// }
//
// }
//
// Path: croquet-examples/src/main/java/com/metrink/croquet/examples/crm/data/GenericDataProvider.java
// public interface GenericDataProviderFactory<T2 extends Serializable> {
// /**
// * Factory method for creating a new {@link GenericDataProvider} given a type.
// * @param type the entity type to associate with this {@link GenericDataProvider}.
// * @return an {@link GenericDataProvider}.
// */
// public GenericDataProvider<T2> create(final Class<T2> type);
// }
//
// Path: croquet-examples/src/main/java/com/metrink/croquet/examples/crm/data/PeopleDataProvider.java
// public interface PeopleDataProviderFactory {
// /**
// * Factory method for creating a new {@link PeopleDataProvider}.
// * @param companyId company to filter on, or null for everything.
// * @return an {@link PeopleDataProvider}.
// */
// public PeopleDataProvider create(final Integer companyId);
// }
// Path: croquet-examples/src/main/java/com/metrink/croquet/examples/crm/CrmModule.java
import com.google.inject.AbstractModule;
import com.google.inject.TypeLiteral;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import com.google.inject.name.Names;
import com.metrink.croquet.examples.crm.data.CompanyBean;
import com.metrink.croquet.examples.crm.data.GenericDataProvider.GenericDataProviderFactory;
import com.metrink.croquet.examples.crm.data.PeopleDataProvider.PeopleDataProviderFactory;
package com.metrink.croquet.examples.crm;
/**
* A Guice module that binds dependencies.
*/
public class CrmModule extends AbstractModule {
private final CrmSettings settings;
/**
* Constructor that takes a settings instance.
* @param settings the settings.
*/
public CrmModule(final CrmSettings settings) {
this.settings = settings;
}
@Override
protected void configure() {
bind(String.class).annotatedWith(Names.named("current-user")).toInstance(settings.getCurrentUser());
install(new FactoryModuleBuilder().build(PeopleDataProviderFactory.class));
|
install(new FactoryModuleBuilder().build(new TypeLiteral<GenericDataProviderFactory<CompanyBean>>() { }));
|
Metrink/croquet
|
croquet-examples/src/main/java/com/metrink/croquet/examples/crm/CrmModule.java
|
// Path: croquet-examples/src/main/java/com/metrink/croquet/examples/crm/data/CompanyBean.java
// @Entity
// @Table(name = "companies")
// public class CompanyBean implements Identifiable, Serializable {
//
// private static final long serialVersionUID = 6782475394818123635L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// @Column(unique = true, nullable = false)
// private Integer companyId;
//
// @Column(nullable = false) private String name;
// @Column(nullable = false) private String street;
// @Column(nullable = false) private String city;
// @Column(nullable = false) private String state;
// @Column(nullable = false) private String zip;
//
// @Override
// public Integer getId() {
// return companyId;
// }
//
// public Integer getCompanyId() {
// return companyId;
// }
//
// public void setCompanyId(final Integer companyId) {
// this.companyId = companyId;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public String getStreet() {
// return street;
// }
//
// public void setStreet(final String street) {
// this.street = street;
// }
//
// public String getCity() {
// return city;
// }
//
// public void setCity(final String city) {
// this.city = city;
// }
//
// public String getState() {
// return state;
// }
//
// public void setState(final String state) {
// this.state = state;
// }
//
// public String getZip() {
// return zip;
// }
//
// public void setZip(final String zip) {
// this.zip = zip;
// }
//
// }
//
// Path: croquet-examples/src/main/java/com/metrink/croquet/examples/crm/data/GenericDataProvider.java
// public interface GenericDataProviderFactory<T2 extends Serializable> {
// /**
// * Factory method for creating a new {@link GenericDataProvider} given a type.
// * @param type the entity type to associate with this {@link GenericDataProvider}.
// * @return an {@link GenericDataProvider}.
// */
// public GenericDataProvider<T2> create(final Class<T2> type);
// }
//
// Path: croquet-examples/src/main/java/com/metrink/croquet/examples/crm/data/PeopleDataProvider.java
// public interface PeopleDataProviderFactory {
// /**
// * Factory method for creating a new {@link PeopleDataProvider}.
// * @param companyId company to filter on, or null for everything.
// * @return an {@link PeopleDataProvider}.
// */
// public PeopleDataProvider create(final Integer companyId);
// }
|
import com.google.inject.AbstractModule;
import com.google.inject.TypeLiteral;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import com.google.inject.name.Names;
import com.metrink.croquet.examples.crm.data.CompanyBean;
import com.metrink.croquet.examples.crm.data.GenericDataProvider.GenericDataProviderFactory;
import com.metrink.croquet.examples.crm.data.PeopleDataProvider.PeopleDataProviderFactory;
|
package com.metrink.croquet.examples.crm;
/**
* A Guice module that binds dependencies.
*/
public class CrmModule extends AbstractModule {
private final CrmSettings settings;
/**
* Constructor that takes a settings instance.
* @param settings the settings.
*/
public CrmModule(final CrmSettings settings) {
this.settings = settings;
}
@Override
protected void configure() {
bind(String.class).annotatedWith(Names.named("current-user")).toInstance(settings.getCurrentUser());
install(new FactoryModuleBuilder().build(PeopleDataProviderFactory.class));
|
// Path: croquet-examples/src/main/java/com/metrink/croquet/examples/crm/data/CompanyBean.java
// @Entity
// @Table(name = "companies")
// public class CompanyBean implements Identifiable, Serializable {
//
// private static final long serialVersionUID = 6782475394818123635L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// @Column(unique = true, nullable = false)
// private Integer companyId;
//
// @Column(nullable = false) private String name;
// @Column(nullable = false) private String street;
// @Column(nullable = false) private String city;
// @Column(nullable = false) private String state;
// @Column(nullable = false) private String zip;
//
// @Override
// public Integer getId() {
// return companyId;
// }
//
// public Integer getCompanyId() {
// return companyId;
// }
//
// public void setCompanyId(final Integer companyId) {
// this.companyId = companyId;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public String getStreet() {
// return street;
// }
//
// public void setStreet(final String street) {
// this.street = street;
// }
//
// public String getCity() {
// return city;
// }
//
// public void setCity(final String city) {
// this.city = city;
// }
//
// public String getState() {
// return state;
// }
//
// public void setState(final String state) {
// this.state = state;
// }
//
// public String getZip() {
// return zip;
// }
//
// public void setZip(final String zip) {
// this.zip = zip;
// }
//
// }
//
// Path: croquet-examples/src/main/java/com/metrink/croquet/examples/crm/data/GenericDataProvider.java
// public interface GenericDataProviderFactory<T2 extends Serializable> {
// /**
// * Factory method for creating a new {@link GenericDataProvider} given a type.
// * @param type the entity type to associate with this {@link GenericDataProvider}.
// * @return an {@link GenericDataProvider}.
// */
// public GenericDataProvider<T2> create(final Class<T2> type);
// }
//
// Path: croquet-examples/src/main/java/com/metrink/croquet/examples/crm/data/PeopleDataProvider.java
// public interface PeopleDataProviderFactory {
// /**
// * Factory method for creating a new {@link PeopleDataProvider}.
// * @param companyId company to filter on, or null for everything.
// * @return an {@link PeopleDataProvider}.
// */
// public PeopleDataProvider create(final Integer companyId);
// }
// Path: croquet-examples/src/main/java/com/metrink/croquet/examples/crm/CrmModule.java
import com.google.inject.AbstractModule;
import com.google.inject.TypeLiteral;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import com.google.inject.name.Names;
import com.metrink.croquet.examples.crm.data.CompanyBean;
import com.metrink.croquet.examples.crm.data.GenericDataProvider.GenericDataProviderFactory;
import com.metrink.croquet.examples.crm.data.PeopleDataProvider.PeopleDataProviderFactory;
package com.metrink.croquet.examples.crm;
/**
* A Guice module that binds dependencies.
*/
public class CrmModule extends AbstractModule {
private final CrmSettings settings;
/**
* Constructor that takes a settings instance.
* @param settings the settings.
*/
public CrmModule(final CrmSettings settings) {
this.settings = settings;
}
@Override
protected void configure() {
bind(String.class).annotatedWith(Names.named("current-user")).toInstance(settings.getCurrentUser());
install(new FactoryModuleBuilder().build(PeopleDataProviderFactory.class));
|
install(new FactoryModuleBuilder().build(new TypeLiteral<GenericDataProviderFactory<CompanyBean>>() { }));
|
Metrink/croquet
|
croquet-core/src/main/java/com/metrink/croquet/hibernate/DataSourceHibernateModule.java
|
// Path: croquet-core/src/main/java/com/metrink/croquet/DataSourceFactory.java
// public class DataSourceFactory implements Serializable {
// private static final long serialVersionUID = 1L;
//
// private static final Logger LOG = LoggerFactory.getLogger(DataSourceFactory.class);
//
// private final DatabaseSettings dbSettings;
// private transient DataSource dataSource;
//
// /**
// * Constructor which takes an initialized {@link DataSource}.
// * @param dbSettings the {@link DatabaseSettings} to use to construct {@link DataSource}s.
// */
// public DataSourceFactory(final DatabaseSettings dbSettings) {
// this.dbSettings = dbSettings;
// this.dataSource = getDataSource();
// }
//
// /**
// * Gets a {@link DataSource} constructing a new one if needed.
// * @return a {@link DataSource}.
// */
// public DataSource getDataSource() {
// if(dataSource == null) {
// LOG.info("Having to construct a new DataSource");
//
// dataSource = new DataSource();
//
// dataSource.setDriverClassName(dbSettings.getDriver());
// dataSource.setUrl(dbSettings.getJdbcUrl());
// dataSource.setUsername(dbSettings.getUser());
// dataSource.setPassword(dbSettings.getPass());
//
// dataSource.setMaxActive(dbSettings.getMaxActive());
// dataSource.setMaxIdle(dbSettings.getMaxIdle());
// dataSource.setMinIdle(dbSettings.getMinIdle());
// dataSource.setInitialSize(dbSettings.getInitialSize());
// dataSource.setTestOnBorrow(dbSettings.getTestOnBorrow());
// dataSource.setTestOnReturn(dbSettings.getTestOnReturn());
// dataSource.setTestWhileIdle(dbSettings.getTestWhileIdle());
// dataSource.setValidationQuery(dbSettings.getValidationQuery());
// dataSource.setLogValidationErrors(dbSettings.getLogValidationErrors());
//
// // a catch-all for any other properties that are needed
// dataSource.setDbProperties(dbSettings.getProperties());
// }
//
// return dataSource;
// }
// }
|
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.persist.PersistService;
import com.google.inject.persist.UnitOfWork;
import com.metrink.croquet.DataSourceFactory;
|
package com.metrink.croquet.hibernate;
/**
* A Guice module that takes care of all the Hibernate bindings when using a data source.
*/
public class DataSourceHibernateModule extends AbstractModule {
@SuppressWarnings("unused")
private static final Logger LOG = LoggerFactory.getLogger(DataSourceHibernateModule.class);
|
// Path: croquet-core/src/main/java/com/metrink/croquet/DataSourceFactory.java
// public class DataSourceFactory implements Serializable {
// private static final long serialVersionUID = 1L;
//
// private static final Logger LOG = LoggerFactory.getLogger(DataSourceFactory.class);
//
// private final DatabaseSettings dbSettings;
// private transient DataSource dataSource;
//
// /**
// * Constructor which takes an initialized {@link DataSource}.
// * @param dbSettings the {@link DatabaseSettings} to use to construct {@link DataSource}s.
// */
// public DataSourceFactory(final DatabaseSettings dbSettings) {
// this.dbSettings = dbSettings;
// this.dataSource = getDataSource();
// }
//
// /**
// * Gets a {@link DataSource} constructing a new one if needed.
// * @return a {@link DataSource}.
// */
// public DataSource getDataSource() {
// if(dataSource == null) {
// LOG.info("Having to construct a new DataSource");
//
// dataSource = new DataSource();
//
// dataSource.setDriverClassName(dbSettings.getDriver());
// dataSource.setUrl(dbSettings.getJdbcUrl());
// dataSource.setUsername(dbSettings.getUser());
// dataSource.setPassword(dbSettings.getPass());
//
// dataSource.setMaxActive(dbSettings.getMaxActive());
// dataSource.setMaxIdle(dbSettings.getMaxIdle());
// dataSource.setMinIdle(dbSettings.getMinIdle());
// dataSource.setInitialSize(dbSettings.getInitialSize());
// dataSource.setTestOnBorrow(dbSettings.getTestOnBorrow());
// dataSource.setTestOnReturn(dbSettings.getTestOnReturn());
// dataSource.setTestWhileIdle(dbSettings.getTestWhileIdle());
// dataSource.setValidationQuery(dbSettings.getValidationQuery());
// dataSource.setLogValidationErrors(dbSettings.getLogValidationErrors());
//
// // a catch-all for any other properties that are needed
// dataSource.setDbProperties(dbSettings.getProperties());
// }
//
// return dataSource;
// }
// }
// Path: croquet-core/src/main/java/com/metrink/croquet/hibernate/DataSourceHibernateModule.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.persist.PersistService;
import com.google.inject.persist.UnitOfWork;
import com.metrink.croquet.DataSourceFactory;
package com.metrink.croquet.hibernate;
/**
* A Guice module that takes care of all the Hibernate bindings when using a data source.
*/
public class DataSourceHibernateModule extends AbstractModule {
@SuppressWarnings("unused")
private static final Logger LOG = LoggerFactory.getLogger(DataSourceHibernateModule.class);
|
private final DataSourceFactory dataSourceFactory;
|
Metrink/croquet
|
croquet-core/src/main/java/com/metrink/croquet/hibernate/EntityManagerProxyFactory.java
|
// Path: croquet-core/src/main/java/com/metrink/croquet/inject/IWriteReplace.java
// public interface IWriteReplace {
//
// /**
// * Write replace method.
// * @return the new object.
// * @throws ObjectStreamException .
// */
// Object writeReplace() throws ObjectStreamException;
// }
|
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Arrays;
import javax.persistence.EntityManager;
import net.sf.cglib.core.DefaultNamingPolicy;
import net.sf.cglib.core.Predicate;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.hibernate.jpa.HibernateEntityManagerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.metrink.croquet.inject.IWriteReplace;
|
package com.metrink.croquet.hibernate;
/**
* Factory class that generates a proxy instance for {@link EntityManager}s.
*/
class EntityManagerProxyFactory {
private static final Logger LOG = LoggerFactory.getLogger(EntityManagerProxyFactory.class);
private EntityManagerProxyFactory() { }
/**
* Creates a proxy object that will write-replace with a wrapper around the {@link EntityManager}.
* @param factory a factory to generate EntityManagers.
* @return the proxied instance.
*/
static EntityManager createProxy(final HibernateEntityManagerFactory factory) {
final EntityManagerInterceptor handler = new EntityManagerInterceptor(factory);
final Enhancer e = new Enhancer();
// make sure we're Serializable and have a write replace method
|
// Path: croquet-core/src/main/java/com/metrink/croquet/inject/IWriteReplace.java
// public interface IWriteReplace {
//
// /**
// * Write replace method.
// * @return the new object.
// * @throws ObjectStreamException .
// */
// Object writeReplace() throws ObjectStreamException;
// }
// Path: croquet-core/src/main/java/com/metrink/croquet/hibernate/EntityManagerProxyFactory.java
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Arrays;
import javax.persistence.EntityManager;
import net.sf.cglib.core.DefaultNamingPolicy;
import net.sf.cglib.core.Predicate;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.hibernate.jpa.HibernateEntityManagerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.metrink.croquet.inject.IWriteReplace;
package com.metrink.croquet.hibernate;
/**
* Factory class that generates a proxy instance for {@link EntityManager}s.
*/
class EntityManagerProxyFactory {
private static final Logger LOG = LoggerFactory.getLogger(EntityManagerProxyFactory.class);
private EntityManagerProxyFactory() { }
/**
* Creates a proxy object that will write-replace with a wrapper around the {@link EntityManager}.
* @param factory a factory to generate EntityManagers.
* @return the proxied instance.
*/
static EntityManager createProxy(final HibernateEntityManagerFactory factory) {
final EntityManagerInterceptor handler = new EntityManagerInterceptor(factory);
final Enhancer e = new Enhancer();
// make sure we're Serializable and have a write replace method
|
e.setInterfaces(new Class[] { EntityManager.class, Serializable.class, IWriteReplace.class });
|
Metrink/croquet
|
croquet-core/src/main/java/com/metrink/croquet/hibernate/QueryRunnerProxyFactory.java
|
// Path: croquet-core/src/main/java/com/metrink/croquet/DataSourceFactory.java
// public class DataSourceFactory implements Serializable {
// private static final long serialVersionUID = 1L;
//
// private static final Logger LOG = LoggerFactory.getLogger(DataSourceFactory.class);
//
// private final DatabaseSettings dbSettings;
// private transient DataSource dataSource;
//
// /**
// * Constructor which takes an initialized {@link DataSource}.
// * @param dbSettings the {@link DatabaseSettings} to use to construct {@link DataSource}s.
// */
// public DataSourceFactory(final DatabaseSettings dbSettings) {
// this.dbSettings = dbSettings;
// this.dataSource = getDataSource();
// }
//
// /**
// * Gets a {@link DataSource} constructing a new one if needed.
// * @return a {@link DataSource}.
// */
// public DataSource getDataSource() {
// if(dataSource == null) {
// LOG.info("Having to construct a new DataSource");
//
// dataSource = new DataSource();
//
// dataSource.setDriverClassName(dbSettings.getDriver());
// dataSource.setUrl(dbSettings.getJdbcUrl());
// dataSource.setUsername(dbSettings.getUser());
// dataSource.setPassword(dbSettings.getPass());
//
// dataSource.setMaxActive(dbSettings.getMaxActive());
// dataSource.setMaxIdle(dbSettings.getMaxIdle());
// dataSource.setMinIdle(dbSettings.getMinIdle());
// dataSource.setInitialSize(dbSettings.getInitialSize());
// dataSource.setTestOnBorrow(dbSettings.getTestOnBorrow());
// dataSource.setTestOnReturn(dbSettings.getTestOnReturn());
// dataSource.setTestWhileIdle(dbSettings.getTestWhileIdle());
// dataSource.setValidationQuery(dbSettings.getValidationQuery());
// dataSource.setLogValidationErrors(dbSettings.getLogValidationErrors());
//
// // a catch-all for any other properties that are needed
// dataSource.setDbProperties(dbSettings.getProperties());
// }
//
// return dataSource;
// }
// }
|
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Arrays;
import net.sf.cglib.core.DefaultNamingPolicy;
import net.sf.cglib.core.Predicate;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.apache.wicket.proxy.LazyInitProxyFactory.IWriteReplace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.metrink.croquet.DataSourceFactory;
import com.sop4j.dbutils.QueryRunner;
|
package com.metrink.croquet.hibernate;
/**
* Proxy class for {@link QueryRunner}.
*/
public class QueryRunnerProxyFactory {
private static final Logger LOG = LoggerFactory.getLogger(QueryRunnerProxyFactory.class);
private QueryRunnerProxyFactory() {
}
/**
* Creates a proxy object that will write-replace with a wrapper around a {@link QueryRunner}.
* @param dataSourceFactory a provider to generate DataSources.
* @return the proxied instance.
*/
|
// Path: croquet-core/src/main/java/com/metrink/croquet/DataSourceFactory.java
// public class DataSourceFactory implements Serializable {
// private static final long serialVersionUID = 1L;
//
// private static final Logger LOG = LoggerFactory.getLogger(DataSourceFactory.class);
//
// private final DatabaseSettings dbSettings;
// private transient DataSource dataSource;
//
// /**
// * Constructor which takes an initialized {@link DataSource}.
// * @param dbSettings the {@link DatabaseSettings} to use to construct {@link DataSource}s.
// */
// public DataSourceFactory(final DatabaseSettings dbSettings) {
// this.dbSettings = dbSettings;
// this.dataSource = getDataSource();
// }
//
// /**
// * Gets a {@link DataSource} constructing a new one if needed.
// * @return a {@link DataSource}.
// */
// public DataSource getDataSource() {
// if(dataSource == null) {
// LOG.info("Having to construct a new DataSource");
//
// dataSource = new DataSource();
//
// dataSource.setDriverClassName(dbSettings.getDriver());
// dataSource.setUrl(dbSettings.getJdbcUrl());
// dataSource.setUsername(dbSettings.getUser());
// dataSource.setPassword(dbSettings.getPass());
//
// dataSource.setMaxActive(dbSettings.getMaxActive());
// dataSource.setMaxIdle(dbSettings.getMaxIdle());
// dataSource.setMinIdle(dbSettings.getMinIdle());
// dataSource.setInitialSize(dbSettings.getInitialSize());
// dataSource.setTestOnBorrow(dbSettings.getTestOnBorrow());
// dataSource.setTestOnReturn(dbSettings.getTestOnReturn());
// dataSource.setTestWhileIdle(dbSettings.getTestWhileIdle());
// dataSource.setValidationQuery(dbSettings.getValidationQuery());
// dataSource.setLogValidationErrors(dbSettings.getLogValidationErrors());
//
// // a catch-all for any other properties that are needed
// dataSource.setDbProperties(dbSettings.getProperties());
// }
//
// return dataSource;
// }
// }
// Path: croquet-core/src/main/java/com/metrink/croquet/hibernate/QueryRunnerProxyFactory.java
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Arrays;
import net.sf.cglib.core.DefaultNamingPolicy;
import net.sf.cglib.core.Predicate;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.apache.wicket.proxy.LazyInitProxyFactory.IWriteReplace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.metrink.croquet.DataSourceFactory;
import com.sop4j.dbutils.QueryRunner;
package com.metrink.croquet.hibernate;
/**
* Proxy class for {@link QueryRunner}.
*/
public class QueryRunnerProxyFactory {
private static final Logger LOG = LoggerFactory.getLogger(QueryRunnerProxyFactory.class);
private QueryRunnerProxyFactory() {
}
/**
* Creates a proxy object that will write-replace with a wrapper around a {@link QueryRunner}.
* @param dataSourceFactory a provider to generate DataSources.
* @return the proxied instance.
*/
|
public static QueryRunner createProxy(final DataSourceFactory dataSourceFactory) {
|
Metrink/croquet
|
croquet-core/src/main/java/com/metrink/croquet/CroquetTester.java
|
// Path: croquet-core/src/main/java/com/metrink/croquet/modules/ManagedModule.java
// public interface ManagedModule {
//
// /**
// * Called before Jetty starts.
// */
// public void start();
//
// /**
// * Called after Jetty stops.
// */
// public void stop();
// }
|
import java.util.List;
import org.apache.wicket.guice.GuiceComponentInjector;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.util.tester.WicketTester;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Provider;
import com.google.inject.persist.PersistService;
import com.google.inject.util.Providers;
import com.metrink.croquet.modules.ManagedModule;
|
package com.metrink.croquet;
/**
* A tester for Croquet that creates a {@link WicketTester} instance.
*
* @param <T> The class used when loading the settings YAML
*/
public class CroquetTester<T extends WicketSettings> extends CroquetWicket<T> {
private static final Logger LOG = LoggerFactory.getLogger(CroquetTester.class);
private WicketTester tester;
CroquetTester(final Class<T> clazz, final T settings) {
super(clazz, settings);
}
@Override
public void run() {
LOG.debug("Calling run on CroquetTester does nothing");
}
@Override
protected Provider<String> getPUNameProvider() {
// always set the name to null so it's not recorded in the EntityManagerFactoryRegistry
return Providers.<String>of(null);
}
/**
* Creates a {@link WicketTester} setting the application.
* @return a configured {@link WicketTester}.
*/
public WicketTester getTester() {
if(tester != null) {
return tester;
}
// create the injector and start the modules
createInjector();
|
// Path: croquet-core/src/main/java/com/metrink/croquet/modules/ManagedModule.java
// public interface ManagedModule {
//
// /**
// * Called before Jetty starts.
// */
// public void start();
//
// /**
// * Called after Jetty stops.
// */
// public void stop();
// }
// Path: croquet-core/src/main/java/com/metrink/croquet/CroquetTester.java
import java.util.List;
import org.apache.wicket.guice.GuiceComponentInjector;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.util.tester.WicketTester;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Provider;
import com.google.inject.persist.PersistService;
import com.google.inject.util.Providers;
import com.metrink.croquet.modules.ManagedModule;
package com.metrink.croquet;
/**
* A tester for Croquet that creates a {@link WicketTester} instance.
*
* @param <T> The class used when loading the settings YAML
*/
public class CroquetTester<T extends WicketSettings> extends CroquetWicket<T> {
private static final Logger LOG = LoggerFactory.getLogger(CroquetTester.class);
private WicketTester tester;
CroquetTester(final Class<T> clazz, final T settings) {
super(clazz, settings);
}
@Override
public void run() {
LOG.debug("Calling run on CroquetTester does nothing");
}
@Override
protected Provider<String> getPUNameProvider() {
// always set the name to null so it's not recorded in the EntityManagerFactoryRegistry
return Providers.<String>of(null);
}
/**
* Creates a {@link WicketTester} setting the application.
* @return a configured {@link WicketTester}.
*/
public WicketTester getTester() {
if(tester != null) {
return tester;
}
// create the injector and start the modules
createInjector();
|
final List<ManagedModule> managedModuleInstances = createAndStartModules();
|
Metrink/croquet
|
croquet-core/src/main/java/com/metrink/croquet/CroquetRestTester.java
|
// Path: croquet-core/src/main/java/com/metrink/croquet/modules/ManagedModule.java
// public interface ManagedModule {
//
// /**
// * Called before Jetty starts.
// */
// public void start();
//
// /**
// * Called after Jetty stops.
// */
// public void stop();
// }
|
import java.util.List;
import org.apache.wicket.guice.GuiceComponentInjector;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.util.tester.WicketTester;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Provider;
import com.google.inject.persist.PersistService;
import com.google.inject.util.Providers;
import com.metrink.croquet.modules.ManagedModule;
|
package com.metrink.croquet;
/**
* A tester for Croquet that creates a {@link WicketTester} instance.
*
* @param <T> The class used when loading the settings YAML
*/
public class CroquetRestTester<T extends RestSettings> extends CroquetRest<T> {
private static final Logger LOG = LoggerFactory.getLogger(CroquetRestTester.class);
private WicketTester tester;
CroquetRestTester(final Class<T> clazz, final T settings) {
super(clazz, settings);
}
@Override
public void run() {
LOG.debug("Calling run on CroquetTester does nothing");
}
@Override
protected Provider<String> getPUNameProvider() {
// always set the name to null so it's not recorded in the EntityManagerFactoryRegistry
return Providers.<String>of(null);
}
/**
* Creates a {@link WicketTester} setting the application.
* @return a configured {@link WicketTester}.
*/
public WicketTester getTester() {
if(tester != null) {
return tester;
}
// create the injector and start the modules
createInjector();
|
// Path: croquet-core/src/main/java/com/metrink/croquet/modules/ManagedModule.java
// public interface ManagedModule {
//
// /**
// * Called before Jetty starts.
// */
// public void start();
//
// /**
// * Called after Jetty stops.
// */
// public void stop();
// }
// Path: croquet-core/src/main/java/com/metrink/croquet/CroquetRestTester.java
import java.util.List;
import org.apache.wicket.guice.GuiceComponentInjector;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.util.tester.WicketTester;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Provider;
import com.google.inject.persist.PersistService;
import com.google.inject.util.Providers;
import com.metrink.croquet.modules.ManagedModule;
package com.metrink.croquet;
/**
* A tester for Croquet that creates a {@link WicketTester} instance.
*
* @param <T> The class used when loading the settings YAML
*/
public class CroquetRestTester<T extends RestSettings> extends CroquetRest<T> {
private static final Logger LOG = LoggerFactory.getLogger(CroquetRestTester.class);
private WicketTester tester;
CroquetRestTester(final Class<T> clazz, final T settings) {
super(clazz, settings);
}
@Override
public void run() {
LOG.debug("Calling run on CroquetTester does nothing");
}
@Override
protected Provider<String> getPUNameProvider() {
// always set the name to null so it's not recorded in the EntityManagerFactoryRegistry
return Providers.<String>of(null);
}
/**
* Creates a {@link WicketTester} setting the application.
* @return a configured {@link WicketTester}.
*/
public WicketTester getTester() {
if(tester != null) {
return tester;
}
// create the injector and start the modules
createInjector();
|
final List<ManagedModule> managedModuleInstances = createAndStartModules();
|
Metrink/croquet
|
croquet-core/src/main/java/com/metrink/croquet/inject/CroquetRestModule.java
|
// Path: croquet-core/src/main/java/com/metrink/croquet/AbstractSettings.java
// public abstract class AbstractSettings implements Serializable {
// private static final long serialVersionUID = -2385834291456376380L;
// private static final Logger LOG = LoggerFactory.getLogger(AbstractSettings.class);
//
// private static final int DEFAULT_PORT = 8080;
//
// @JsonProperty("development")
// private Boolean development = false;
//
// @JsonProperty("port")
// private Integer port = DEFAULT_PORT;
//
// @JsonProperty("pid_file")
// private String pidFile;
//
// @JsonProperty("logging")
// private LoggingSettings loggingSettings = new LoggingSettings();
//
// @JsonProperty("db")
// private DatabaseSettings dbSettings;
//
//
// /**
// * Perform post de-serialization modification of the Settings.
// */
// protected final void initialize() {
// // Enabling development mode forces these settings. This is somewhat inelegant, because to configure one of
// // these values differently will require disabling development mode and manually configure the remaining values.
// if (development) {
// loggingSettings.getLoggers().put("org.hibernate.SQL", Level.DEBUG);
// loggingSettings.getLoggers().put("com.metrink.croquet", Level.DEBUG);
// }
//
// // call the class's init method
// init();
// }
//
// /**
// * Perform post de-serialization modification of the Settings.
// */
// protected abstract void init();
//
// /**
// * Helper method used to obtain a class from a fully qualified class name. If the value is null or an exception is
// * thrown, return the default result instead.
// * @param className the fully qualified class name to try
// * @param defaultResult the nullable default result
// * @param <T> the class type
// * @return the class or null
// */
// @SuppressWarnings("unchecked")
// protected <T> Class<T> getClassOrDefault(final String className, final Class<T> defaultResult) {
// try {
// return className == null
// ? defaultResult
// : (Class<T>)Class.forName(className);
// } catch (final ClassNotFoundException e) {
// LOG.error("ClassNotFoundException for {} - defaulting to {}", className, defaultResult);
// return defaultResult;
// }
// }
//
// /**
// * In development mode?
// * Defaults to false to avoid accidental deployment of development mode in production.
// * @return true if in development mode
// */
// public Boolean getDevelopment() {
// return development;
// }
//
// /**
// * Get the TCP port which will be bound to Jetty.
// * @return the port
// */
// public int getPort() {
// return port;
// }
//
//
// /**
// * Get the {@link DatabaseSettings}.
// * @return the {@link DatabaseSettings}.
// */
// public DatabaseSettings getDatabaseSettings() {
// return dbSettings;
// }
//
// /**
// * Get the {@link LoggingSettings}.
// * @return the {@link LoggingSettings}.
// */
// public LoggingSettings getLoggingSettings() {
// return loggingSettings;
// }
//
// /**
// * Get pidFile.
// * @return the pidFile
// */
// public String getPidFile() {
// return pidFile;
// }
//
// /**
// * Set pidFile.
// * @param pidFile the pidFile to set
// */
// public void setPidFile(final String pidFile) {
// this.pidFile = pidFile;
// }
//
// }
//
// Path: croquet-core/src/main/java/com/metrink/croquet/RestSettings.java
// public class RestSettings extends AbstractSettings {
// private static final long serialVersionUID = -4071324712275262138L;
//
// private List<String> providerPackages = new ArrayList<>();
//
// /**
// * Perform post de-serialization modification of the Settings.
// */
// @Override
// protected void init() {
// }
//
// /**
// * Gets the list of provider packages.
// * @return list of provider packages.
// */
// public List<String> getProviderPackages() {
// return Collections.unmodifiableList(providerPackages);
// }
//
// /**
// * Adds a provider package to the list.
// * @param providerPackage the provider package to add.
// */
// public void addProviderPackage(final String providerPackage) {
// providerPackages.add(providerPackage);
// }
//
// }
|
import com.google.inject.AbstractModule;
import com.metrink.croquet.AbstractSettings;
import com.metrink.croquet.RestSettings;
|
package com.metrink.croquet.inject;
/**
* Croquet's Guice module that configures most of the dependencies.
* @param <T> the subclass type of the settings instance
*/
public class CroquetRestModule<T extends RestSettings> extends AbstractModule {
private final T settings;
private Class<T> clazz;
/**
* Constructor for the CroquetModule.
* @param clazz the settings base class.
* @param settings the settings.
*/
public CroquetRestModule(final Class<T> clazz, final T settings) {
this.clazz = clazz;
this.settings = settings;
}
@Override
protected void configure() {
// bind the settings classes
|
// Path: croquet-core/src/main/java/com/metrink/croquet/AbstractSettings.java
// public abstract class AbstractSettings implements Serializable {
// private static final long serialVersionUID = -2385834291456376380L;
// private static final Logger LOG = LoggerFactory.getLogger(AbstractSettings.class);
//
// private static final int DEFAULT_PORT = 8080;
//
// @JsonProperty("development")
// private Boolean development = false;
//
// @JsonProperty("port")
// private Integer port = DEFAULT_PORT;
//
// @JsonProperty("pid_file")
// private String pidFile;
//
// @JsonProperty("logging")
// private LoggingSettings loggingSettings = new LoggingSettings();
//
// @JsonProperty("db")
// private DatabaseSettings dbSettings;
//
//
// /**
// * Perform post de-serialization modification of the Settings.
// */
// protected final void initialize() {
// // Enabling development mode forces these settings. This is somewhat inelegant, because to configure one of
// // these values differently will require disabling development mode and manually configure the remaining values.
// if (development) {
// loggingSettings.getLoggers().put("org.hibernate.SQL", Level.DEBUG);
// loggingSettings.getLoggers().put("com.metrink.croquet", Level.DEBUG);
// }
//
// // call the class's init method
// init();
// }
//
// /**
// * Perform post de-serialization modification of the Settings.
// */
// protected abstract void init();
//
// /**
// * Helper method used to obtain a class from a fully qualified class name. If the value is null or an exception is
// * thrown, return the default result instead.
// * @param className the fully qualified class name to try
// * @param defaultResult the nullable default result
// * @param <T> the class type
// * @return the class or null
// */
// @SuppressWarnings("unchecked")
// protected <T> Class<T> getClassOrDefault(final String className, final Class<T> defaultResult) {
// try {
// return className == null
// ? defaultResult
// : (Class<T>)Class.forName(className);
// } catch (final ClassNotFoundException e) {
// LOG.error("ClassNotFoundException for {} - defaulting to {}", className, defaultResult);
// return defaultResult;
// }
// }
//
// /**
// * In development mode?
// * Defaults to false to avoid accidental deployment of development mode in production.
// * @return true if in development mode
// */
// public Boolean getDevelopment() {
// return development;
// }
//
// /**
// * Get the TCP port which will be bound to Jetty.
// * @return the port
// */
// public int getPort() {
// return port;
// }
//
//
// /**
// * Get the {@link DatabaseSettings}.
// * @return the {@link DatabaseSettings}.
// */
// public DatabaseSettings getDatabaseSettings() {
// return dbSettings;
// }
//
// /**
// * Get the {@link LoggingSettings}.
// * @return the {@link LoggingSettings}.
// */
// public LoggingSettings getLoggingSettings() {
// return loggingSettings;
// }
//
// /**
// * Get pidFile.
// * @return the pidFile
// */
// public String getPidFile() {
// return pidFile;
// }
//
// /**
// * Set pidFile.
// * @param pidFile the pidFile to set
// */
// public void setPidFile(final String pidFile) {
// this.pidFile = pidFile;
// }
//
// }
//
// Path: croquet-core/src/main/java/com/metrink/croquet/RestSettings.java
// public class RestSettings extends AbstractSettings {
// private static final long serialVersionUID = -4071324712275262138L;
//
// private List<String> providerPackages = new ArrayList<>();
//
// /**
// * Perform post de-serialization modification of the Settings.
// */
// @Override
// protected void init() {
// }
//
// /**
// * Gets the list of provider packages.
// * @return list of provider packages.
// */
// public List<String> getProviderPackages() {
// return Collections.unmodifiableList(providerPackages);
// }
//
// /**
// * Adds a provider package to the list.
// * @param providerPackage the provider package to add.
// */
// public void addProviderPackage(final String providerPackage) {
// providerPackages.add(providerPackage);
// }
//
// }
// Path: croquet-core/src/main/java/com/metrink/croquet/inject/CroquetRestModule.java
import com.google.inject.AbstractModule;
import com.metrink.croquet.AbstractSettings;
import com.metrink.croquet.RestSettings;
package com.metrink.croquet.inject;
/**
* Croquet's Guice module that configures most of the dependencies.
* @param <T> the subclass type of the settings instance
*/
public class CroquetRestModule<T extends RestSettings> extends AbstractModule {
private final T settings;
private Class<T> clazz;
/**
* Constructor for the CroquetModule.
* @param clazz the settings base class.
* @param settings the settings.
*/
public CroquetRestModule(final Class<T> clazz, final T settings) {
this.clazz = clazz;
this.settings = settings;
}
@Override
protected void configure() {
// bind the settings classes
|
bind(AbstractSettings.class).toInstance(settings);
|
Metrink/croquet
|
croquet-core/src/main/java/com/metrink/croquet/hibernate/CroquetPersistService.java
|
// Path: croquet-core/src/main/java/com/metrink/croquet/AbstractSettings.java
// public abstract class AbstractSettings implements Serializable {
// private static final long serialVersionUID = -2385834291456376380L;
// private static final Logger LOG = LoggerFactory.getLogger(AbstractSettings.class);
//
// private static final int DEFAULT_PORT = 8080;
//
// @JsonProperty("development")
// private Boolean development = false;
//
// @JsonProperty("port")
// private Integer port = DEFAULT_PORT;
//
// @JsonProperty("pid_file")
// private String pidFile;
//
// @JsonProperty("logging")
// private LoggingSettings loggingSettings = new LoggingSettings();
//
// @JsonProperty("db")
// private DatabaseSettings dbSettings;
//
//
// /**
// * Perform post de-serialization modification of the Settings.
// */
// protected final void initialize() {
// // Enabling development mode forces these settings. This is somewhat inelegant, because to configure one of
// // these values differently will require disabling development mode and manually configure the remaining values.
// if (development) {
// loggingSettings.getLoggers().put("org.hibernate.SQL", Level.DEBUG);
// loggingSettings.getLoggers().put("com.metrink.croquet", Level.DEBUG);
// }
//
// // call the class's init method
// init();
// }
//
// /**
// * Perform post de-serialization modification of the Settings.
// */
// protected abstract void init();
//
// /**
// * Helper method used to obtain a class from a fully qualified class name. If the value is null or an exception is
// * thrown, return the default result instead.
// * @param className the fully qualified class name to try
// * @param defaultResult the nullable default result
// * @param <T> the class type
// * @return the class or null
// */
// @SuppressWarnings("unchecked")
// protected <T> Class<T> getClassOrDefault(final String className, final Class<T> defaultResult) {
// try {
// return className == null
// ? defaultResult
// : (Class<T>)Class.forName(className);
// } catch (final ClassNotFoundException e) {
// LOG.error("ClassNotFoundException for {} - defaulting to {}", className, defaultResult);
// return defaultResult;
// }
// }
//
// /**
// * In development mode?
// * Defaults to false to avoid accidental deployment of development mode in production.
// * @return true if in development mode
// */
// public Boolean getDevelopment() {
// return development;
// }
//
// /**
// * Get the TCP port which will be bound to Jetty.
// * @return the port
// */
// public int getPort() {
// return port;
// }
//
//
// /**
// * Get the {@link DatabaseSettings}.
// * @return the {@link DatabaseSettings}.
// */
// public DatabaseSettings getDatabaseSettings() {
// return dbSettings;
// }
//
// /**
// * Get the {@link LoggingSettings}.
// * @return the {@link LoggingSettings}.
// */
// public LoggingSettings getLoggingSettings() {
// return loggingSettings;
// }
//
// /**
// * Get pidFile.
// * @return the pidFile
// */
// public String getPidFile() {
// return pidFile;
// }
//
// /**
// * Set pidFile.
// * @param pidFile the pidFile to set
// */
// public void setPidFile(final String pidFile) {
// this.pidFile = pidFile;
// }
//
// }
|
import java.io.Serializable;
import javax.annotation.Nullable;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.spi.PersistenceUnitTransactionType;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.jpa.HibernateEntityManagerFactory;
import org.hibernate.jpa.internal.EntityManagerFactoryImpl;
import org.hibernate.service.ServiceRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.google.inject.persist.PersistService;
import com.google.inject.persist.UnitOfWork;
import com.metrink.croquet.AbstractSettings;
|
package com.metrink.croquet.hibernate;
/**
* A PersistService, UnitOfWork, and Provider<EntityManager> implementation that configures Hibernate.
*
* The persist.xml file is NOT used to configure Hibernate. Everything is driven through the DatabaseSettings class.
*/
@Singleton
class CroquetPersistService implements Provider<EntityManager>, UnitOfWork, PersistService {
private static final Logger LOG = LoggerFactory.getLogger(CroquetPersistService.class);
private static final String TRUE_STRING = "true";
private static final String FALSE_STRING = "false";
//CHECKSTYLE:OFF stupid stuff
|
// Path: croquet-core/src/main/java/com/metrink/croquet/AbstractSettings.java
// public abstract class AbstractSettings implements Serializable {
// private static final long serialVersionUID = -2385834291456376380L;
// private static final Logger LOG = LoggerFactory.getLogger(AbstractSettings.class);
//
// private static final int DEFAULT_PORT = 8080;
//
// @JsonProperty("development")
// private Boolean development = false;
//
// @JsonProperty("port")
// private Integer port = DEFAULT_PORT;
//
// @JsonProperty("pid_file")
// private String pidFile;
//
// @JsonProperty("logging")
// private LoggingSettings loggingSettings = new LoggingSettings();
//
// @JsonProperty("db")
// private DatabaseSettings dbSettings;
//
//
// /**
// * Perform post de-serialization modification of the Settings.
// */
// protected final void initialize() {
// // Enabling development mode forces these settings. This is somewhat inelegant, because to configure one of
// // these values differently will require disabling development mode and manually configure the remaining values.
// if (development) {
// loggingSettings.getLoggers().put("org.hibernate.SQL", Level.DEBUG);
// loggingSettings.getLoggers().put("com.metrink.croquet", Level.DEBUG);
// }
//
// // call the class's init method
// init();
// }
//
// /**
// * Perform post de-serialization modification of the Settings.
// */
// protected abstract void init();
//
// /**
// * Helper method used to obtain a class from a fully qualified class name. If the value is null or an exception is
// * thrown, return the default result instead.
// * @param className the fully qualified class name to try
// * @param defaultResult the nullable default result
// * @param <T> the class type
// * @return the class or null
// */
// @SuppressWarnings("unchecked")
// protected <T> Class<T> getClassOrDefault(final String className, final Class<T> defaultResult) {
// try {
// return className == null
// ? defaultResult
// : (Class<T>)Class.forName(className);
// } catch (final ClassNotFoundException e) {
// LOG.error("ClassNotFoundException for {} - defaulting to {}", className, defaultResult);
// return defaultResult;
// }
// }
//
// /**
// * In development mode?
// * Defaults to false to avoid accidental deployment of development mode in production.
// * @return true if in development mode
// */
// public Boolean getDevelopment() {
// return development;
// }
//
// /**
// * Get the TCP port which will be bound to Jetty.
// * @return the port
// */
// public int getPort() {
// return port;
// }
//
//
// /**
// * Get the {@link DatabaseSettings}.
// * @return the {@link DatabaseSettings}.
// */
// public DatabaseSettings getDatabaseSettings() {
// return dbSettings;
// }
//
// /**
// * Get the {@link LoggingSettings}.
// * @return the {@link LoggingSettings}.
// */
// public LoggingSettings getLoggingSettings() {
// return loggingSettings;
// }
//
// /**
// * Get pidFile.
// * @return the pidFile
// */
// public String getPidFile() {
// return pidFile;
// }
//
// /**
// * Set pidFile.
// * @param pidFile the pidFile to set
// */
// public void setPidFile(final String pidFile) {
// this.pidFile = pidFile;
// }
//
// }
// Path: croquet-core/src/main/java/com/metrink/croquet/hibernate/CroquetPersistService.java
import java.io.Serializable;
import javax.annotation.Nullable;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.spi.PersistenceUnitTransactionType;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.jpa.HibernateEntityManagerFactory;
import org.hibernate.jpa.internal.EntityManagerFactoryImpl;
import org.hibernate.service.ServiceRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.google.inject.persist.PersistService;
import com.google.inject.persist.UnitOfWork;
import com.metrink.croquet.AbstractSettings;
package com.metrink.croquet.hibernate;
/**
* A PersistService, UnitOfWork, and Provider<EntityManager> implementation that configures Hibernate.
*
* The persist.xml file is NOT used to configure Hibernate. Everything is driven through the DatabaseSettings class.
*/
@Singleton
class CroquetPersistService implements Provider<EntityManager>, UnitOfWork, PersistService {
private static final Logger LOG = LoggerFactory.getLogger(CroquetPersistService.class);
private static final String TRUE_STRING = "true";
private static final String FALSE_STRING = "false";
//CHECKSTYLE:OFF stupid stuff
|
private final AbstractSettings settings;
|
tomgibara/bits
|
src/main/java/com/tomgibara/bits/ImmutableBits.java
|
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableOne extends ImmutableBit {
//
// static final ImmutableOne INSTANCE = new ImmutableOne();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return true;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// switch (position) {
// case 0:
// switch (length) {
// case 0: return 0;
// case 1: return 1;
// }
// break;
// case 1:
// if (length == 0) return 0;
// break;
// }
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// int p = that.ones().last();
// switch (p) {
// case -1 : return 1;
// case 0 : return 0;
// default : return -1;
// }
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableZero.INSTANCE;
// }
//
// // package scoped methods
//
// @Override
// boolean getBit() {
// return true;
// }
//
// }
//
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableZero extends ImmutableBit {
//
// static final ImmutableZero INSTANCE = new ImmutableZero();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return false;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// if (position == 0 && (length == 0 || length == 1) || position == 0 && length == 0) return 0;
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableOne.INSTANCE;
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// return that.zeros().isAll() ? 0 : -1;
// }
//
// @Override
// boolean getBit() {
// return false;
// }
//
// }
|
import java.util.AbstractSet;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.SortedSet;
import com.tomgibara.bits.ImmutableBit.ImmutableOne;
import com.tomgibara.bits.ImmutableBit.ImmutableZero;
|
}
// mutable methods
@Override
public BitStore mutableCopy() {
return Bits.store(size);
}
}
private class AllMatches implements BitMatches {
@Override
public BitMatches disjoint() {
return this;
}
@Override
public BitMatches overlapping() {
return this;
}
@Override
public BitStore store() {
return ImmutableBits.this;
}
@Override
public BitStore sequence() {
|
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableOne extends ImmutableBit {
//
// static final ImmutableOne INSTANCE = new ImmutableOne();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return true;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// switch (position) {
// case 0:
// switch (length) {
// case 0: return 0;
// case 1: return 1;
// }
// break;
// case 1:
// if (length == 0) return 0;
// break;
// }
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// int p = that.ones().last();
// switch (p) {
// case -1 : return 1;
// case 0 : return 0;
// default : return -1;
// }
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableZero.INSTANCE;
// }
//
// // package scoped methods
//
// @Override
// boolean getBit() {
// return true;
// }
//
// }
//
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableZero extends ImmutableBit {
//
// static final ImmutableZero INSTANCE = new ImmutableZero();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return false;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// if (position == 0 && (length == 0 || length == 1) || position == 0 && length == 0) return 0;
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableOne.INSTANCE;
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// return that.zeros().isAll() ? 0 : -1;
// }
//
// @Override
// boolean getBit() {
// return false;
// }
//
// }
// Path: src/main/java/com/tomgibara/bits/ImmutableBits.java
import java.util.AbstractSet;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.SortedSet;
import com.tomgibara.bits.ImmutableBit.ImmutableOne;
import com.tomgibara.bits.ImmutableBit.ImmutableZero;
}
// mutable methods
@Override
public BitStore mutableCopy() {
return Bits.store(size);
}
}
private class AllMatches implements BitMatches {
@Override
public BitMatches disjoint() {
return this;
}
@Override
public BitMatches overlapping() {
return this;
}
@Override
public BitStore store() {
return ImmutableBits.this;
}
@Override
public BitStore sequence() {
|
return ones ? ImmutableOne.INSTANCE : ImmutableZero.INSTANCE;
|
tomgibara/bits
|
src/main/java/com/tomgibara/bits/ImmutableBits.java
|
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableOne extends ImmutableBit {
//
// static final ImmutableOne INSTANCE = new ImmutableOne();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return true;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// switch (position) {
// case 0:
// switch (length) {
// case 0: return 0;
// case 1: return 1;
// }
// break;
// case 1:
// if (length == 0) return 0;
// break;
// }
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// int p = that.ones().last();
// switch (p) {
// case -1 : return 1;
// case 0 : return 0;
// default : return -1;
// }
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableZero.INSTANCE;
// }
//
// // package scoped methods
//
// @Override
// boolean getBit() {
// return true;
// }
//
// }
//
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableZero extends ImmutableBit {
//
// static final ImmutableZero INSTANCE = new ImmutableZero();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return false;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// if (position == 0 && (length == 0 || length == 1) || position == 0 && length == 0) return 0;
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableOne.INSTANCE;
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// return that.zeros().isAll() ? 0 : -1;
// }
//
// @Override
// boolean getBit() {
// return false;
// }
//
// }
|
import java.util.AbstractSet;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.SortedSet;
import com.tomgibara.bits.ImmutableBit.ImmutableOne;
import com.tomgibara.bits.ImmutableBit.ImmutableZero;
|
}
// mutable methods
@Override
public BitStore mutableCopy() {
return Bits.store(size);
}
}
private class AllMatches implements BitMatches {
@Override
public BitMatches disjoint() {
return this;
}
@Override
public BitMatches overlapping() {
return this;
}
@Override
public BitStore store() {
return ImmutableBits.this;
}
@Override
public BitStore sequence() {
|
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableOne extends ImmutableBit {
//
// static final ImmutableOne INSTANCE = new ImmutableOne();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return true;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// switch (position) {
// case 0:
// switch (length) {
// case 0: return 0;
// case 1: return 1;
// }
// break;
// case 1:
// if (length == 0) return 0;
// break;
// }
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// int p = that.ones().last();
// switch (p) {
// case -1 : return 1;
// case 0 : return 0;
// default : return -1;
// }
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableZero.INSTANCE;
// }
//
// // package scoped methods
//
// @Override
// boolean getBit() {
// return true;
// }
//
// }
//
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableZero extends ImmutableBit {
//
// static final ImmutableZero INSTANCE = new ImmutableZero();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return false;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// if (position == 0 && (length == 0 || length == 1) || position == 0 && length == 0) return 0;
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableOne.INSTANCE;
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// return that.zeros().isAll() ? 0 : -1;
// }
//
// @Override
// boolean getBit() {
// return false;
// }
//
// }
// Path: src/main/java/com/tomgibara/bits/ImmutableBits.java
import java.util.AbstractSet;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.SortedSet;
import com.tomgibara.bits.ImmutableBit.ImmutableOne;
import com.tomgibara.bits.ImmutableBit.ImmutableZero;
}
// mutable methods
@Override
public BitStore mutableCopy() {
return Bits.store(size);
}
}
private class AllMatches implements BitMatches {
@Override
public BitMatches disjoint() {
return this;
}
@Override
public BitMatches overlapping() {
return this;
}
@Override
public BitStore store() {
return ImmutableBits.this;
}
@Override
public BitStore sequence() {
|
return ones ? ImmutableOne.INSTANCE : ImmutableZero.INSTANCE;
|
tomgibara/bits
|
src/test/java/com/tomgibara/bits/InputStreamBitReaderTest.java
|
// Path: src/main/java/com/tomgibara/bits/InputStreamBitReader.java
// class InputStreamBitReader extends ByteBasedBitReader {
//
// private final InputStream in;
//
// InputStreamBitReader(InputStream in) {
// this.in = in;
// }
//
// @Override
// protected int readByte() throws BitStreamException {
// try {
// return in.read();
// } catch (IOException e) {
// throw new BitStreamException(e);
// }
// }
//
// @Override
// protected long skipBytes(long count) throws BitStreamException {
// try {
// return in.skip(count);
// } catch (IOException e) {
// throw new BitStreamException(e);
// }
// }
//
// @Override
// protected long seekByte(long index) throws BitStreamException {
// return -1L;
// }
//
// /**
// * The InputStream from which this {@link BitReader} obtains bits.
// *
// * @return an input stream, never null
// */
//
// public InputStream getInputStream() {
// return in;
// }
//
// }
|
import java.io.ByteArrayInputStream;
import com.tomgibara.bits.InputStreamBitReader;
|
/*
* Copyright 2011 Tom Gibara
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.tomgibara.bits;
public class InputStreamBitReaderTest extends AbstractBitReaderTest {
@Override
|
// Path: src/main/java/com/tomgibara/bits/InputStreamBitReader.java
// class InputStreamBitReader extends ByteBasedBitReader {
//
// private final InputStream in;
//
// InputStreamBitReader(InputStream in) {
// this.in = in;
// }
//
// @Override
// protected int readByte() throws BitStreamException {
// try {
// return in.read();
// } catch (IOException e) {
// throw new BitStreamException(e);
// }
// }
//
// @Override
// protected long skipBytes(long count) throws BitStreamException {
// try {
// return in.skip(count);
// } catch (IOException e) {
// throw new BitStreamException(e);
// }
// }
//
// @Override
// protected long seekByte(long index) throws BitStreamException {
// return -1L;
// }
//
// /**
// * The InputStream from which this {@link BitReader} obtains bits.
// *
// * @return an input stream, never null
// */
//
// public InputStream getInputStream() {
// return in;
// }
//
// }
// Path: src/test/java/com/tomgibara/bits/InputStreamBitReaderTest.java
import java.io.ByteArrayInputStream;
import com.tomgibara.bits.InputStreamBitReader;
/*
* Copyright 2011 Tom Gibara
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.tomgibara.bits;
public class InputStreamBitReaderTest extends AbstractBitReaderTest {
@Override
|
InputStreamBitReader readerFor(BitStore vector) {
|
tomgibara/bits
|
src/main/java/com/tomgibara/bits/LongBitStore.java
|
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableOne extends ImmutableBit {
//
// static final ImmutableOne INSTANCE = new ImmutableOne();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return true;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// switch (position) {
// case 0:
// switch (length) {
// case 0: return 0;
// case 1: return 1;
// }
// break;
// case 1:
// if (length == 0) return 0;
// break;
// }
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// int p = that.ones().last();
// switch (p) {
// case -1 : return 1;
// case 0 : return 0;
// default : return -1;
// }
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableZero.INSTANCE;
// }
//
// // package scoped methods
//
// @Override
// boolean getBit() {
// return true;
// }
//
// }
//
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableZero extends ImmutableBit {
//
// static final ImmutableZero INSTANCE = new ImmutableZero();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return false;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// if (position == 0 && (length == 0 || length == 1) || position == 0 && length == 0) return 0;
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableOne.INSTANCE;
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// return that.zeros().isAll() ? 0 : -1;
// }
//
// @Override
// boolean getBit() {
// return false;
// }
//
// }
|
import java.util.SortedSet;
import com.tomgibara.bits.ImmutableBit.ImmutableOne;
import com.tomgibara.bits.ImmutableBit.ImmutableZero;
import com.tomgibara.streams.ReadStream;
import com.tomgibara.streams.WriteStream;
|
public LongBitStore store() {
return LongBitStore.this;
}
@Override
public Positions positions() {
return new BitStorePositions(this, false, 0);
}
@Override
public Positions positions(int position) {
checkPosition(position);
return new BitStorePositions(this, false, position);
}
@Override
public SortedSet<Integer> asSet() {
return new BitStoreSet(this, 0);
}
}
private final class LongOnes extends LongMatches {
@Override
public boolean bit() {
return true;
}
@Override
|
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableOne extends ImmutableBit {
//
// static final ImmutableOne INSTANCE = new ImmutableOne();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return true;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// switch (position) {
// case 0:
// switch (length) {
// case 0: return 0;
// case 1: return 1;
// }
// break;
// case 1:
// if (length == 0) return 0;
// break;
// }
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// int p = that.ones().last();
// switch (p) {
// case -1 : return 1;
// case 0 : return 0;
// default : return -1;
// }
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableZero.INSTANCE;
// }
//
// // package scoped methods
//
// @Override
// boolean getBit() {
// return true;
// }
//
// }
//
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableZero extends ImmutableBit {
//
// static final ImmutableZero INSTANCE = new ImmutableZero();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return false;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// if (position == 0 && (length == 0 || length == 1) || position == 0 && length == 0) return 0;
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableOne.INSTANCE;
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// return that.zeros().isAll() ? 0 : -1;
// }
//
// @Override
// boolean getBit() {
// return false;
// }
//
// }
// Path: src/main/java/com/tomgibara/bits/LongBitStore.java
import java.util.SortedSet;
import com.tomgibara.bits.ImmutableBit.ImmutableOne;
import com.tomgibara.bits.ImmutableBit.ImmutableZero;
import com.tomgibara.streams.ReadStream;
import com.tomgibara.streams.WriteStream;
public LongBitStore store() {
return LongBitStore.this;
}
@Override
public Positions positions() {
return new BitStorePositions(this, false, 0);
}
@Override
public Positions positions(int position) {
checkPosition(position);
return new BitStorePositions(this, false, position);
}
@Override
public SortedSet<Integer> asSet() {
return new BitStoreSet(this, 0);
}
}
private final class LongOnes extends LongMatches {
@Override
public boolean bit() {
return true;
}
@Override
|
public ImmutableOne sequence() {
|
tomgibara/bits
|
src/main/java/com/tomgibara/bits/LongBitStore.java
|
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableOne extends ImmutableBit {
//
// static final ImmutableOne INSTANCE = new ImmutableOne();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return true;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// switch (position) {
// case 0:
// switch (length) {
// case 0: return 0;
// case 1: return 1;
// }
// break;
// case 1:
// if (length == 0) return 0;
// break;
// }
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// int p = that.ones().last();
// switch (p) {
// case -1 : return 1;
// case 0 : return 0;
// default : return -1;
// }
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableZero.INSTANCE;
// }
//
// // package scoped methods
//
// @Override
// boolean getBit() {
// return true;
// }
//
// }
//
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableZero extends ImmutableBit {
//
// static final ImmutableZero INSTANCE = new ImmutableZero();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return false;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// if (position == 0 && (length == 0 || length == 1) || position == 0 && length == 0) return 0;
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableOne.INSTANCE;
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// return that.zeros().isAll() ? 0 : -1;
// }
//
// @Override
// boolean getBit() {
// return false;
// }
//
// }
|
import java.util.SortedSet;
import com.tomgibara.bits.ImmutableBit.ImmutableOne;
import com.tomgibara.bits.ImmutableBit.ImmutableZero;
import com.tomgibara.streams.ReadStream;
import com.tomgibara.streams.WriteStream;
|
public int last() {
return 63 - Long.numberOfLeadingZeros(bits);
}
@Override
public int next(int position) {
checkPosition(position);
if (position == 64) return 64;
long value = bits >>> position;
return value == 0L ? 64 : position + Long.numberOfTrailingZeros(value);
}
@Override
public int previous(int position) {
checkPosition(position);
if (position == 0) return -1;
long value = bits << 64 - position;
return value == 0L ? -1 : position - 1 - Long.numberOfLeadingZeros(value);
}
}
private final class LongZeros extends LongMatches {
@Override
public boolean bit() {
return false;
}
@Override
|
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableOne extends ImmutableBit {
//
// static final ImmutableOne INSTANCE = new ImmutableOne();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return true;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// switch (position) {
// case 0:
// switch (length) {
// case 0: return 0;
// case 1: return 1;
// }
// break;
// case 1:
// if (length == 0) return 0;
// break;
// }
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// int p = that.ones().last();
// switch (p) {
// case -1 : return 1;
// case 0 : return 0;
// default : return -1;
// }
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableZero.INSTANCE;
// }
//
// // package scoped methods
//
// @Override
// boolean getBit() {
// return true;
// }
//
// }
//
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableZero extends ImmutableBit {
//
// static final ImmutableZero INSTANCE = new ImmutableZero();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return false;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// if (position == 0 && (length == 0 || length == 1) || position == 0 && length == 0) return 0;
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableOne.INSTANCE;
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// return that.zeros().isAll() ? 0 : -1;
// }
//
// @Override
// boolean getBit() {
// return false;
// }
//
// }
// Path: src/main/java/com/tomgibara/bits/LongBitStore.java
import java.util.SortedSet;
import com.tomgibara.bits.ImmutableBit.ImmutableOne;
import com.tomgibara.bits.ImmutableBit.ImmutableZero;
import com.tomgibara.streams.ReadStream;
import com.tomgibara.streams.WriteStream;
public int last() {
return 63 - Long.numberOfLeadingZeros(bits);
}
@Override
public int next(int position) {
checkPosition(position);
if (position == 64) return 64;
long value = bits >>> position;
return value == 0L ? 64 : position + Long.numberOfTrailingZeros(value);
}
@Override
public int previous(int position) {
checkPosition(position);
if (position == 0) return -1;
long value = bits << 64 - position;
return value == 0L ? -1 : position - 1 - Long.numberOfLeadingZeros(value);
}
}
private final class LongZeros extends LongMatches {
@Override
public boolean bit() {
return false;
}
@Override
|
public ImmutableZero sequence() {
|
tomgibara/bits
|
src/test/java/com/tomgibara/bits/ImmutableOnesTest.java
|
// Path: src/main/java/com/tomgibara/bits/BitStore.java
// interface Positions extends ListIterator<Integer> {
//
// /**
// * Indicates whether the iterator moves over pattern sequences such that
// * successive matched ranges do not over overlap.
// *
// * @return true if position matches do not overlap, false otherwise
// */
//
// boolean isDisjoint();
//
// /**
// * <p>
// * The next matched position. This is equivalent to {@link #next()} but
// * may be expected to be slightly more efficient, with the differences
// * being that:
// *
// * <ul>
// * <li>The position is returned as a primitive is returned, not a boxed
// * primitive.
// * <li>If there's no position, the value of {@link BitStore#size()} is
// * returned instead of an exception being raised.
// * </ul>
// *
// * <p>
// * Otherwise, the effect of calling the method is the same.
// *
// * @return the next position, or the first invalid index if there is no
// * further position
// */
//
// int nextPosition();
//
// /**
// * <p>
// * The previous matched position. This is equivalent to
// * {@link #previous()} but may be expected to be slightly more
// * efficient, with the differences being that:
// *
// * <ul>
// * <li>The position is returned as a primitive is returned, not a boxed
// * primitive.
// * <li>If there's no position, the value of {@link BitStore#size()} is
// * returned instead of an exception being raised.
// * </ul>
// *
// * <p>
// * Otherwise, the effect of calling the method is the same.
// *
// * @return the previous position, or -1 if there is no further position
// */
//
// int previousPosition();
//
// /**
// * Replaces the last match returned by the {@link #next()}/
// * {@link #nextPosition()} and {@link #previous()}/
// * {@link #previousPosition()} methods, with the supplied bits.
// *
// * @param replacement
// * the bits to replace the matched sequence
// * @throws IllegalArgumentException
// * if the replacement size does not match the matched
// * sequence size
// * @throws IllegalStateException
// * if the underlying bit store is immutable, or if no call
// * to {@link #previous()} or {@link #next()} has been made
// * @see DisjointMatches#replaceAll(BitStore)
// */
//
// void replace(BitStore replacement);
//
// /**
// * Uniformly replaces the bits of last match returned by the
// * {@link #next()}/ {@link #nextPosition()} and {@link #previous()}/
// * {@link #previousPosition()} methods, with the specified bit value.
// *
// * @param bits
// * the bit value with which to replace the matched bits
// * @throws IllegalStateException
// * if the underlying bit store is immutable, or if no call
// * to {@link #previous()} or {@link #next()} has been made
// * @see DisjointMatches#replaceAll(boolean)
// */
//
// void replace(boolean bits);
// }
|
import com.tomgibara.bits.BitStore.Positions;
|
/*
* Copyright 2015 Tom Gibara
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.tomgibara.bits;
public class ImmutableOnesTest extends ImmutableBitsTest {
@Override
boolean isOnes() { return true; }
public void testPositions() {
BitStore store = Bits.oneBits(50);
|
// Path: src/main/java/com/tomgibara/bits/BitStore.java
// interface Positions extends ListIterator<Integer> {
//
// /**
// * Indicates whether the iterator moves over pattern sequences such that
// * successive matched ranges do not over overlap.
// *
// * @return true if position matches do not overlap, false otherwise
// */
//
// boolean isDisjoint();
//
// /**
// * <p>
// * The next matched position. This is equivalent to {@link #next()} but
// * may be expected to be slightly more efficient, with the differences
// * being that:
// *
// * <ul>
// * <li>The position is returned as a primitive is returned, not a boxed
// * primitive.
// * <li>If there's no position, the value of {@link BitStore#size()} is
// * returned instead of an exception being raised.
// * </ul>
// *
// * <p>
// * Otherwise, the effect of calling the method is the same.
// *
// * @return the next position, or the first invalid index if there is no
// * further position
// */
//
// int nextPosition();
//
// /**
// * <p>
// * The previous matched position. This is equivalent to
// * {@link #previous()} but may be expected to be slightly more
// * efficient, with the differences being that:
// *
// * <ul>
// * <li>The position is returned as a primitive is returned, not a boxed
// * primitive.
// * <li>If there's no position, the value of {@link BitStore#size()} is
// * returned instead of an exception being raised.
// * </ul>
// *
// * <p>
// * Otherwise, the effect of calling the method is the same.
// *
// * @return the previous position, or -1 if there is no further position
// */
//
// int previousPosition();
//
// /**
// * Replaces the last match returned by the {@link #next()}/
// * {@link #nextPosition()} and {@link #previous()}/
// * {@link #previousPosition()} methods, with the supplied bits.
// *
// * @param replacement
// * the bits to replace the matched sequence
// * @throws IllegalArgumentException
// * if the replacement size does not match the matched
// * sequence size
// * @throws IllegalStateException
// * if the underlying bit store is immutable, or if no call
// * to {@link #previous()} or {@link #next()} has been made
// * @see DisjointMatches#replaceAll(BitStore)
// */
//
// void replace(BitStore replacement);
//
// /**
// * Uniformly replaces the bits of last match returned by the
// * {@link #next()}/ {@link #nextPosition()} and {@link #previous()}/
// * {@link #previousPosition()} methods, with the specified bit value.
// *
// * @param bits
// * the bit value with which to replace the matched bits
// * @throws IllegalStateException
// * if the underlying bit store is immutable, or if no call
// * to {@link #previous()} or {@link #next()} has been made
// * @see DisjointMatches#replaceAll(boolean)
// */
//
// void replace(boolean bits);
// }
// Path: src/test/java/com/tomgibara/bits/ImmutableOnesTest.java
import com.tomgibara.bits.BitStore.Positions;
/*
* Copyright 2015 Tom Gibara
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.tomgibara.bits;
public class ImmutableOnesTest extends ImmutableBitsTest {
@Override
boolean isOnes() { return true; }
public void testPositions() {
BitStore store = Bits.oneBits(50);
|
Positions ps = store.ones().positions();
|
tomgibara/bits
|
src/main/java/com/tomgibara/bits/CharsBitStore.java
|
// Path: src/main/java/com/tomgibara/bits/Bits.java
// static void checkBitsLength(int length) {
// if (length < 0) throw new IllegalArgumentException("negative length");
// if (length > 64) throw new IllegalArgumentException("length exceeds 64");
// }
|
import static com.tomgibara.bits.Bits.checkBitsLength;
|
}
@Override
public BitStore immutableCopy() {
return new CharsBitStore(chars.toString(), false);
}
@Override
public BitStore immutableView() {
return new CharsBitStore(chars, false);
}
@Override
public int size() {
return chars.length();
}
@Override
public boolean getBit(int index) {
char c = chars.charAt( adjIndex(index) );
switch (c) {
case '0' : return false;
case '1' : return true;
default : throw new IllegalStateException("non-binary numeral ' + c + ' at index " + index);
}
}
@Override
public long getBits(int position, int length) {
if (position < 0L) throw new IllegalArgumentException("negative position");
|
// Path: src/main/java/com/tomgibara/bits/Bits.java
// static void checkBitsLength(int length) {
// if (length < 0) throw new IllegalArgumentException("negative length");
// if (length > 64) throw new IllegalArgumentException("length exceeds 64");
// }
// Path: src/main/java/com/tomgibara/bits/CharsBitStore.java
import static com.tomgibara.bits.Bits.checkBitsLength;
}
@Override
public BitStore immutableCopy() {
return new CharsBitStore(chars.toString(), false);
}
@Override
public BitStore immutableView() {
return new CharsBitStore(chars, false);
}
@Override
public int size() {
return chars.length();
}
@Override
public boolean getBit(int index) {
char c = chars.charAt( adjIndex(index) );
switch (c) {
case '0' : return false;
case '1' : return true;
default : throw new IllegalStateException("non-binary numeral ' + c + ' at index " + index);
}
}
@Override
public long getBits(int position, int length) {
if (position < 0L) throw new IllegalArgumentException("negative position");
|
checkBitsLength(length);
|
tomgibara/bits
|
src/main/java/com/tomgibara/bits/BitVector.java
|
// Path: src/main/java/com/tomgibara/bits/Bits.java
// static void checkBitsLength(int length) {
// if (length < 0) throw new IllegalArgumentException("negative length");
// if (length > 64) throw new IllegalArgumentException("length exceeds 64");
// }
//
// Path: src/main/java/com/tomgibara/bits/Bits.java
// static void checkIntBitsLength(int length) {
// if (length < 0) throw new IllegalArgumentException("negative length");
// if (length > 32) throw new IllegalArgumentException("length exceeds 32");
// }
//
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableOne extends ImmutableBit {
//
// static final ImmutableOne INSTANCE = new ImmutableOne();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return true;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// switch (position) {
// case 0:
// switch (length) {
// case 0: return 0;
// case 1: return 1;
// }
// break;
// case 1:
// if (length == 0) return 0;
// break;
// }
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// int p = that.ones().last();
// switch (p) {
// case -1 : return 1;
// case 0 : return 0;
// default : return -1;
// }
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableZero.INSTANCE;
// }
//
// // package scoped methods
//
// @Override
// boolean getBit() {
// return true;
// }
//
// }
//
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableZero extends ImmutableBit {
//
// static final ImmutableZero INSTANCE = new ImmutableZero();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return false;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// if (position == 0 && (length == 0 || length == 1) || position == 0 && length == 0) return 0;
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableOne.INSTANCE;
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// return that.zeros().isAll() ? 0 : -1;
// }
//
// @Override
// boolean getBit() {
// return false;
// }
//
// }
|
import static com.tomgibara.bits.Bits.checkBitsLength;
import static com.tomgibara.bits.Bits.checkIntBitsLength;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectStreamException;
import java.io.OutputStream;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.PrivilegedAction;
import java.util.AbstractList;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.SortedSet;
import com.tomgibara.bits.ImmutableBit.ImmutableOne;
import com.tomgibara.bits.ImmutableBit.ImmutableZero;
import com.tomgibara.fundament.Alignable;
import com.tomgibara.streams.ReadStream;
import com.tomgibara.streams.WriteStream;
|
@Override
public int size() {
return finish - start;
}
@Override
public boolean getBit(int index) {
index = adjIndex(index);
final int i = index >> ADDRESS_BITS;
final long m = 1L << (index & ADDRESS_MASK);
return (bits[i] & m) != 0;
}
@Override
public void setBit(int index, boolean value) {
index = adjIndex(index);
checkMutable();
final int i = index >> ADDRESS_BITS;
final long m = 1L << (index & ADDRESS_MASK);
if (value) {
bits[i] |= m;
} else {
bits[i] &= ~m;
}
}
// accelerating methods
@Override
public long getBits(int position, int length) {
|
// Path: src/main/java/com/tomgibara/bits/Bits.java
// static void checkBitsLength(int length) {
// if (length < 0) throw new IllegalArgumentException("negative length");
// if (length > 64) throw new IllegalArgumentException("length exceeds 64");
// }
//
// Path: src/main/java/com/tomgibara/bits/Bits.java
// static void checkIntBitsLength(int length) {
// if (length < 0) throw new IllegalArgumentException("negative length");
// if (length > 32) throw new IllegalArgumentException("length exceeds 32");
// }
//
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableOne extends ImmutableBit {
//
// static final ImmutableOne INSTANCE = new ImmutableOne();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return true;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// switch (position) {
// case 0:
// switch (length) {
// case 0: return 0;
// case 1: return 1;
// }
// break;
// case 1:
// if (length == 0) return 0;
// break;
// }
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// int p = that.ones().last();
// switch (p) {
// case -1 : return 1;
// case 0 : return 0;
// default : return -1;
// }
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableZero.INSTANCE;
// }
//
// // package scoped methods
//
// @Override
// boolean getBit() {
// return true;
// }
//
// }
//
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableZero extends ImmutableBit {
//
// static final ImmutableZero INSTANCE = new ImmutableZero();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return false;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// if (position == 0 && (length == 0 || length == 1) || position == 0 && length == 0) return 0;
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableOne.INSTANCE;
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// return that.zeros().isAll() ? 0 : -1;
// }
//
// @Override
// boolean getBit() {
// return false;
// }
//
// }
// Path: src/main/java/com/tomgibara/bits/BitVector.java
import static com.tomgibara.bits.Bits.checkBitsLength;
import static com.tomgibara.bits.Bits.checkIntBitsLength;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectStreamException;
import java.io.OutputStream;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.PrivilegedAction;
import java.util.AbstractList;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.SortedSet;
import com.tomgibara.bits.ImmutableBit.ImmutableOne;
import com.tomgibara.bits.ImmutableBit.ImmutableZero;
import com.tomgibara.fundament.Alignable;
import com.tomgibara.streams.ReadStream;
import com.tomgibara.streams.WriteStream;
@Override
public int size() {
return finish - start;
}
@Override
public boolean getBit(int index) {
index = adjIndex(index);
final int i = index >> ADDRESS_BITS;
final long m = 1L << (index & ADDRESS_MASK);
return (bits[i] & m) != 0;
}
@Override
public void setBit(int index, boolean value) {
index = adjIndex(index);
checkMutable();
final int i = index >> ADDRESS_BITS;
final long m = 1L << (index & ADDRESS_MASK);
if (value) {
bits[i] |= m;
} else {
bits[i] &= ~m;
}
}
// accelerating methods
@Override
public long getBits(int position, int length) {
|
checkBitsLength(length);
|
tomgibara/bits
|
src/main/java/com/tomgibara/bits/BitVector.java
|
// Path: src/main/java/com/tomgibara/bits/Bits.java
// static void checkBitsLength(int length) {
// if (length < 0) throw new IllegalArgumentException("negative length");
// if (length > 64) throw new IllegalArgumentException("length exceeds 64");
// }
//
// Path: src/main/java/com/tomgibara/bits/Bits.java
// static void checkIntBitsLength(int length) {
// if (length < 0) throw new IllegalArgumentException("negative length");
// if (length > 32) throw new IllegalArgumentException("length exceeds 32");
// }
//
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableOne extends ImmutableBit {
//
// static final ImmutableOne INSTANCE = new ImmutableOne();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return true;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// switch (position) {
// case 0:
// switch (length) {
// case 0: return 0;
// case 1: return 1;
// }
// break;
// case 1:
// if (length == 0) return 0;
// break;
// }
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// int p = that.ones().last();
// switch (p) {
// case -1 : return 1;
// case 0 : return 0;
// default : return -1;
// }
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableZero.INSTANCE;
// }
//
// // package scoped methods
//
// @Override
// boolean getBit() {
// return true;
// }
//
// }
//
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableZero extends ImmutableBit {
//
// static final ImmutableZero INSTANCE = new ImmutableZero();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return false;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// if (position == 0 && (length == 0 || length == 1) || position == 0 && length == 0) return 0;
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableOne.INSTANCE;
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// return that.zeros().isAll() ? 0 : -1;
// }
//
// @Override
// boolean getBit() {
// return false;
// }
//
// }
|
import static com.tomgibara.bits.Bits.checkBitsLength;
import static com.tomgibara.bits.Bits.checkIntBitsLength;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectStreamException;
import java.io.OutputStream;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.PrivilegedAction;
import java.util.AbstractList;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.SortedSet;
import com.tomgibara.bits.ImmutableBit.ImmutableOne;
import com.tomgibara.bits.ImmutableBit.ImmutableZero;
import com.tomgibara.fundament.Alignable;
import com.tomgibara.streams.ReadStream;
import com.tomgibara.streams.WriteStream;
|
public boolean getBit(int index) {
index = adjIndex(index);
final int i = index >> ADDRESS_BITS;
final long m = 1L << (index & ADDRESS_MASK);
return (bits[i] & m) != 0;
}
@Override
public void setBit(int index, boolean value) {
index = adjIndex(index);
checkMutable();
final int i = index >> ADDRESS_BITS;
final long m = 1L << (index & ADDRESS_MASK);
if (value) {
bits[i] |= m;
} else {
bits[i] &= ~m;
}
}
// accelerating methods
@Override
public long getBits(int position, int length) {
checkBitsLength(length);
return getBitsAdj(adjPosition(position, length), length);
}
@Override
public int getBitsAsInt(int position, int length) {
|
// Path: src/main/java/com/tomgibara/bits/Bits.java
// static void checkBitsLength(int length) {
// if (length < 0) throw new IllegalArgumentException("negative length");
// if (length > 64) throw new IllegalArgumentException("length exceeds 64");
// }
//
// Path: src/main/java/com/tomgibara/bits/Bits.java
// static void checkIntBitsLength(int length) {
// if (length < 0) throw new IllegalArgumentException("negative length");
// if (length > 32) throw new IllegalArgumentException("length exceeds 32");
// }
//
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableOne extends ImmutableBit {
//
// static final ImmutableOne INSTANCE = new ImmutableOne();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return true;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// switch (position) {
// case 0:
// switch (length) {
// case 0: return 0;
// case 1: return 1;
// }
// break;
// case 1:
// if (length == 0) return 0;
// break;
// }
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// int p = that.ones().last();
// switch (p) {
// case -1 : return 1;
// case 0 : return 0;
// default : return -1;
// }
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableZero.INSTANCE;
// }
//
// // package scoped methods
//
// @Override
// boolean getBit() {
// return true;
// }
//
// }
//
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableZero extends ImmutableBit {
//
// static final ImmutableZero INSTANCE = new ImmutableZero();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return false;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// if (position == 0 && (length == 0 || length == 1) || position == 0 && length == 0) return 0;
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableOne.INSTANCE;
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// return that.zeros().isAll() ? 0 : -1;
// }
//
// @Override
// boolean getBit() {
// return false;
// }
//
// }
// Path: src/main/java/com/tomgibara/bits/BitVector.java
import static com.tomgibara.bits.Bits.checkBitsLength;
import static com.tomgibara.bits.Bits.checkIntBitsLength;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectStreamException;
import java.io.OutputStream;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.PrivilegedAction;
import java.util.AbstractList;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.SortedSet;
import com.tomgibara.bits.ImmutableBit.ImmutableOne;
import com.tomgibara.bits.ImmutableBit.ImmutableZero;
import com.tomgibara.fundament.Alignable;
import com.tomgibara.streams.ReadStream;
import com.tomgibara.streams.WriteStream;
public boolean getBit(int index) {
index = adjIndex(index);
final int i = index >> ADDRESS_BITS;
final long m = 1L << (index & ADDRESS_MASK);
return (bits[i] & m) != 0;
}
@Override
public void setBit(int index, boolean value) {
index = adjIndex(index);
checkMutable();
final int i = index >> ADDRESS_BITS;
final long m = 1L << (index & ADDRESS_MASK);
if (value) {
bits[i] |= m;
} else {
bits[i] &= ~m;
}
}
// accelerating methods
@Override
public long getBits(int position, int length) {
checkBitsLength(length);
return getBitsAdj(adjPosition(position, length), length);
}
@Override
public int getBitsAsInt(int position, int length) {
|
checkIntBitsLength(length);
|
tomgibara/bits
|
src/main/java/com/tomgibara/bits/BitVector.java
|
// Path: src/main/java/com/tomgibara/bits/Bits.java
// static void checkBitsLength(int length) {
// if (length < 0) throw new IllegalArgumentException("negative length");
// if (length > 64) throw new IllegalArgumentException("length exceeds 64");
// }
//
// Path: src/main/java/com/tomgibara/bits/Bits.java
// static void checkIntBitsLength(int length) {
// if (length < 0) throw new IllegalArgumentException("negative length");
// if (length > 32) throw new IllegalArgumentException("length exceeds 32");
// }
//
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableOne extends ImmutableBit {
//
// static final ImmutableOne INSTANCE = new ImmutableOne();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return true;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// switch (position) {
// case 0:
// switch (length) {
// case 0: return 0;
// case 1: return 1;
// }
// break;
// case 1:
// if (length == 0) return 0;
// break;
// }
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// int p = that.ones().last();
// switch (p) {
// case -1 : return 1;
// case 0 : return 0;
// default : return -1;
// }
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableZero.INSTANCE;
// }
//
// // package scoped methods
//
// @Override
// boolean getBit() {
// return true;
// }
//
// }
//
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableZero extends ImmutableBit {
//
// static final ImmutableZero INSTANCE = new ImmutableZero();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return false;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// if (position == 0 && (length == 0 || length == 1) || position == 0 && length == 0) return 0;
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableOne.INSTANCE;
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// return that.zeros().isAll() ? 0 : -1;
// }
//
// @Override
// boolean getBit() {
// return false;
// }
//
// }
|
import static com.tomgibara.bits.Bits.checkBitsLength;
import static com.tomgibara.bits.Bits.checkIntBitsLength;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectStreamException;
import java.io.OutputStream;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.PrivilegedAction;
import java.util.AbstractList;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.SortedSet;
import com.tomgibara.bits.ImmutableBit.ImmutableOne;
import com.tomgibara.bits.ImmutableBit.ImmutableZero;
import com.tomgibara.fundament.Alignable;
import com.tomgibara.streams.ReadStream;
import com.tomgibara.streams.WriteStream;
|
@Override
public void withStore(BitStore store) {
perform(XOR, store);
}
@Override
public void withStore(int position, BitStore store) {
perform(XOR, position, store);
}
@Override
public void withBytes(int position, byte[] bytes, int offset, int length) {
perform(XOR, position, bytes, offset, length);
}
@Override
public BitWriter openWriter(int finalPos, int initialPos) {
return BitVector.this.openWriter(XOR, finalPos, initialPos);
}
}
private final class MatchesOnes extends AbstractBitMatches {
@Override
public boolean bit() {
return true;
}
@Override
|
// Path: src/main/java/com/tomgibara/bits/Bits.java
// static void checkBitsLength(int length) {
// if (length < 0) throw new IllegalArgumentException("negative length");
// if (length > 64) throw new IllegalArgumentException("length exceeds 64");
// }
//
// Path: src/main/java/com/tomgibara/bits/Bits.java
// static void checkIntBitsLength(int length) {
// if (length < 0) throw new IllegalArgumentException("negative length");
// if (length > 32) throw new IllegalArgumentException("length exceeds 32");
// }
//
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableOne extends ImmutableBit {
//
// static final ImmutableOne INSTANCE = new ImmutableOne();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return true;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// switch (position) {
// case 0:
// switch (length) {
// case 0: return 0;
// case 1: return 1;
// }
// break;
// case 1:
// if (length == 0) return 0;
// break;
// }
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// int p = that.ones().last();
// switch (p) {
// case -1 : return 1;
// case 0 : return 0;
// default : return -1;
// }
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableZero.INSTANCE;
// }
//
// // package scoped methods
//
// @Override
// boolean getBit() {
// return true;
// }
//
// }
//
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableZero extends ImmutableBit {
//
// static final ImmutableZero INSTANCE = new ImmutableZero();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return false;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// if (position == 0 && (length == 0 || length == 1) || position == 0 && length == 0) return 0;
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableOne.INSTANCE;
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// return that.zeros().isAll() ? 0 : -1;
// }
//
// @Override
// boolean getBit() {
// return false;
// }
//
// }
// Path: src/main/java/com/tomgibara/bits/BitVector.java
import static com.tomgibara.bits.Bits.checkBitsLength;
import static com.tomgibara.bits.Bits.checkIntBitsLength;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectStreamException;
import java.io.OutputStream;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.PrivilegedAction;
import java.util.AbstractList;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.SortedSet;
import com.tomgibara.bits.ImmutableBit.ImmutableOne;
import com.tomgibara.bits.ImmutableBit.ImmutableZero;
import com.tomgibara.fundament.Alignable;
import com.tomgibara.streams.ReadStream;
import com.tomgibara.streams.WriteStream;
@Override
public void withStore(BitStore store) {
perform(XOR, store);
}
@Override
public void withStore(int position, BitStore store) {
perform(XOR, position, store);
}
@Override
public void withBytes(int position, byte[] bytes, int offset, int length) {
perform(XOR, position, bytes, offset, length);
}
@Override
public BitWriter openWriter(int finalPos, int initialPos) {
return BitVector.this.openWriter(XOR, finalPos, initialPos);
}
}
private final class MatchesOnes extends AbstractBitMatches {
@Override
public boolean bit() {
return true;
}
@Override
|
public ImmutableOne sequence() {
|
tomgibara/bits
|
src/main/java/com/tomgibara/bits/BitVector.java
|
// Path: src/main/java/com/tomgibara/bits/Bits.java
// static void checkBitsLength(int length) {
// if (length < 0) throw new IllegalArgumentException("negative length");
// if (length > 64) throw new IllegalArgumentException("length exceeds 64");
// }
//
// Path: src/main/java/com/tomgibara/bits/Bits.java
// static void checkIntBitsLength(int length) {
// if (length < 0) throw new IllegalArgumentException("negative length");
// if (length > 32) throw new IllegalArgumentException("length exceeds 32");
// }
//
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableOne extends ImmutableBit {
//
// static final ImmutableOne INSTANCE = new ImmutableOne();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return true;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// switch (position) {
// case 0:
// switch (length) {
// case 0: return 0;
// case 1: return 1;
// }
// break;
// case 1:
// if (length == 0) return 0;
// break;
// }
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// int p = that.ones().last();
// switch (p) {
// case -1 : return 1;
// case 0 : return 0;
// default : return -1;
// }
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableZero.INSTANCE;
// }
//
// // package scoped methods
//
// @Override
// boolean getBit() {
// return true;
// }
//
// }
//
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableZero extends ImmutableBit {
//
// static final ImmutableZero INSTANCE = new ImmutableZero();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return false;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// if (position == 0 && (length == 0 || length == 1) || position == 0 && length == 0) return 0;
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableOne.INSTANCE;
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// return that.zeros().isAll() ? 0 : -1;
// }
//
// @Override
// boolean getBit() {
// return false;
// }
//
// }
|
import static com.tomgibara.bits.Bits.checkBitsLength;
import static com.tomgibara.bits.Bits.checkIntBitsLength;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectStreamException;
import java.io.OutputStream;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.PrivilegedAction;
import java.util.AbstractList;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.SortedSet;
import com.tomgibara.bits.ImmutableBit.ImmutableOne;
import com.tomgibara.bits.ImmutableBit.ImmutableZero;
import com.tomgibara.fundament.Alignable;
import com.tomgibara.streams.ReadStream;
import com.tomgibara.streams.WriteStream;
|
position += start;
if (position - 1 > finish) throw new IllegalArgumentException();
return lastOneInRangeAdj(start, position) - start;
}
public Positions positions() {
return new PositionIterator(true);
}
public Positions positions(int position) {
if (position < 0) throw new IllegalArgumentException();
position += start;
if (position > finish) throw new IllegalArgumentException();
return new PositionIterator(true, position);
}
@Override
public SortedSet<Integer> asSet() {
return new IntSet(true, start);
}
}
private final class MatchesZeros extends AbstractBitMatches {
@Override
public boolean bit() {
return false;
}
@Override
|
// Path: src/main/java/com/tomgibara/bits/Bits.java
// static void checkBitsLength(int length) {
// if (length < 0) throw new IllegalArgumentException("negative length");
// if (length > 64) throw new IllegalArgumentException("length exceeds 64");
// }
//
// Path: src/main/java/com/tomgibara/bits/Bits.java
// static void checkIntBitsLength(int length) {
// if (length < 0) throw new IllegalArgumentException("negative length");
// if (length > 32) throw new IllegalArgumentException("length exceeds 32");
// }
//
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableOne extends ImmutableBit {
//
// static final ImmutableOne INSTANCE = new ImmutableOne();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return true;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// switch (position) {
// case 0:
// switch (length) {
// case 0: return 0;
// case 1: return 1;
// }
// break;
// case 1:
// if (length == 0) return 0;
// break;
// }
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// int p = that.ones().last();
// switch (p) {
// case -1 : return 1;
// case 0 : return 0;
// default : return -1;
// }
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableZero.INSTANCE;
// }
//
// // package scoped methods
//
// @Override
// boolean getBit() {
// return true;
// }
//
// }
//
// Path: src/main/java/com/tomgibara/bits/ImmutableBit.java
// static final class ImmutableZero extends ImmutableBit {
//
// static final ImmutableZero INSTANCE = new ImmutableZero();
//
// // fundamental methods
//
// @Override
// public boolean getBit(int index) {
// checkIndex(index);
// return false;
// }
//
// // accelerating methods
//
// @Override
// public long getBits(int position, int length) {
// return getBitsAsInt(position, length);
// }
//
// @Override
// public int getBitsAsInt(int position, int length) {
// if (position == 0 && (length == 0 || length == 1) || position == 0 && length == 0) return 0;
// throw new IllegalArgumentException("invalid position and/or length");
// }
//
// // view methods
//
// @Override
// public BitStore flipped() {
// return ImmutableOne.INSTANCE;
// }
//
// // comparable methods
//
// @Override
// public int compareNumericallyTo(BitStore that) {
// return that.zeros().isAll() ? 0 : -1;
// }
//
// @Override
// boolean getBit() {
// return false;
// }
//
// }
// Path: src/main/java/com/tomgibara/bits/BitVector.java
import static com.tomgibara.bits.Bits.checkBitsLength;
import static com.tomgibara.bits.Bits.checkIntBitsLength;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectStreamException;
import java.io.OutputStream;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.PrivilegedAction;
import java.util.AbstractList;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.SortedSet;
import com.tomgibara.bits.ImmutableBit.ImmutableOne;
import com.tomgibara.bits.ImmutableBit.ImmutableZero;
import com.tomgibara.fundament.Alignable;
import com.tomgibara.streams.ReadStream;
import com.tomgibara.streams.WriteStream;
position += start;
if (position - 1 > finish) throw new IllegalArgumentException();
return lastOneInRangeAdj(start, position) - start;
}
public Positions positions() {
return new PositionIterator(true);
}
public Positions positions(int position) {
if (position < 0) throw new IllegalArgumentException();
position += start;
if (position > finish) throw new IllegalArgumentException();
return new PositionIterator(true, position);
}
@Override
public SortedSet<Integer> asSet() {
return new IntSet(true, start);
}
}
private final class MatchesZeros extends AbstractBitMatches {
@Override
public boolean bit() {
return false;
}
@Override
|
public ImmutableZero sequence() {
|
tomgibara/bits
|
src/main/java/com/tomgibara/bits/BitStoreTests.java
|
// Path: src/main/java/com/tomgibara/bits/BitStore.java
// enum Test {
//
// /**
// * Whether two {@link BitStore} have the same pattern of true/false-bits.
// */
//
// EQUALS,
//
// /**
// * Whether there is no position at which both {@link BitStore}s have
// * a true-bit.
// */
//
// EXCLUDES,
//
// /**
// * Whether one {@link BitStore} has true-bits at every position that
// * another does.
// */
//
// CONTAINS,
//
// /**
// * Whether one {@link BitStore} is has zero bits at exactly every
// * position that another has one bits.
// */
//
// COMPLEMENTS;
//
// static final Test[] values = values();
// }
//
// Path: src/main/java/com/tomgibara/bits/BitStore.java
// interface Tests {
//
// /**
// * The type of tests performed by this object.
// *
// * @return the type of test
// */
//
// Test getTest();
//
// /**
// * Tests a {@link BitStore} against the source.
// *
// * @param store
// * the bits tested against
// * @return whether the test succeeds
// * @throws IllegalArgumentException
// * if the store size does not match the size of the source
// */
//
// boolean store(BitStore store);
//
// /**
// * Tests the bits of a long against the source {@link BitStore}. In
// * cases where the size of the source is less than the full 64 bits of
// * the long, the least-significant bits are used.
// *
// * @param bits
// * the bits tested against
// * @return whether the test succeeds
// * @throws IllegalArgumentException
// * if the size of the source exceeds 64 bits.
// */
//
// boolean bits(long bits);
//
// }
|
import com.tomgibara.bits.BitStore.Test;
import com.tomgibara.bits.BitStore.Tests;
|
checkThatSize(size);
int limit = size & ~63;
for (int i = 0; i < limit; i += 64) {
boolean result = testBits(s.getBits(i, 64), store.getBits(i, 64));
if (!result) return false;
}
int rem = size - limit;
return rem == 0 ? true : testBits(s.getBits(limit, rem), store.getBits(limit, rem), rem);
}
abstract boolean testBits(long ourBits, long theirBits);
abstract boolean testBits(long ourBits, long theirBits, int size);
private void checkThisSize(int size) {
if (size > 64) throw new IllegalArgumentException("store size greater than 64 bits");
}
private void checkThatSize(int size) {
if (s.size() != size) throw new IllegalArgumentException("mismatched size");
}
static final class Equals extends BitStoreTests {
Equals(BitStore store) {
super(store);
}
@Override
|
// Path: src/main/java/com/tomgibara/bits/BitStore.java
// enum Test {
//
// /**
// * Whether two {@link BitStore} have the same pattern of true/false-bits.
// */
//
// EQUALS,
//
// /**
// * Whether there is no position at which both {@link BitStore}s have
// * a true-bit.
// */
//
// EXCLUDES,
//
// /**
// * Whether one {@link BitStore} has true-bits at every position that
// * another does.
// */
//
// CONTAINS,
//
// /**
// * Whether one {@link BitStore} is has zero bits at exactly every
// * position that another has one bits.
// */
//
// COMPLEMENTS;
//
// static final Test[] values = values();
// }
//
// Path: src/main/java/com/tomgibara/bits/BitStore.java
// interface Tests {
//
// /**
// * The type of tests performed by this object.
// *
// * @return the type of test
// */
//
// Test getTest();
//
// /**
// * Tests a {@link BitStore} against the source.
// *
// * @param store
// * the bits tested against
// * @return whether the test succeeds
// * @throws IllegalArgumentException
// * if the store size does not match the size of the source
// */
//
// boolean store(BitStore store);
//
// /**
// * Tests the bits of a long against the source {@link BitStore}. In
// * cases where the size of the source is less than the full 64 bits of
// * the long, the least-significant bits are used.
// *
// * @param bits
// * the bits tested against
// * @return whether the test succeeds
// * @throws IllegalArgumentException
// * if the size of the source exceeds 64 bits.
// */
//
// boolean bits(long bits);
//
// }
// Path: src/main/java/com/tomgibara/bits/BitStoreTests.java
import com.tomgibara.bits.BitStore.Test;
import com.tomgibara.bits.BitStore.Tests;
checkThatSize(size);
int limit = size & ~63;
for (int i = 0; i < limit; i += 64) {
boolean result = testBits(s.getBits(i, 64), store.getBits(i, 64));
if (!result) return false;
}
int rem = size - limit;
return rem == 0 ? true : testBits(s.getBits(limit, rem), store.getBits(limit, rem), rem);
}
abstract boolean testBits(long ourBits, long theirBits);
abstract boolean testBits(long ourBits, long theirBits, int size);
private void checkThisSize(int size) {
if (size > 64) throw new IllegalArgumentException("store size greater than 64 bits");
}
private void checkThatSize(int size) {
if (s.size() != size) throw new IllegalArgumentException("mismatched size");
}
static final class Equals extends BitStoreTests {
Equals(BitStore store) {
super(store);
}
@Override
|
public Test getTest() {
|
tomgibara/bits
|
src/main/java/com/tomgibara/bits/ImmutableMatches.java
|
// Path: src/main/java/com/tomgibara/bits/BitStore.java
// interface BitMatches extends OverlappingMatches, DisjointMatches {
//
// @Override
// BitMatches overlapping();
//
// @Override
// BitMatches disjoint();
//
// @Override
// BitMatches range(int from, int to);
//
// /**
// * Whether the {@link BitStore} consists entirely
// * of the matched bit value.
// *
// * @return true if and only if all bits in the store have the value of
// * {@link #bit()}
// */
//
// @Override
// boolean isAll();
//
// /**
// * Whether none of the bits in the {@link BitStore} have the matched bit
// * value.
// *
// * @return true if and only if none of the bits in the store have the
// * value of {@link #bit()}
// */
//
// @Override
// boolean isNone();
//
// /**
// * Whether 1s are being matched.
// *
// * @return bit value being matched
// */
//
// boolean bit();
//
// /**
// * The matched bit positions as a sorted set. The returned set is a live
// * view over the {@link BitStore} with mutations of the store being
// * reflected in the set and vice versa. Attempting to add integers to
// * the set that lie outside the range of valid bit indexes in the store
// * will fail.
// *
// * @return a set view of the matched bit positions
// */
//
// SortedSet<Integer> asSet();
//
// }
//
// Path: src/main/java/com/tomgibara/bits/BitStore.java
// interface Positions extends ListIterator<Integer> {
//
// /**
// * Indicates whether the iterator moves over pattern sequences such that
// * successive matched ranges do not over overlap.
// *
// * @return true if position matches do not overlap, false otherwise
// */
//
// boolean isDisjoint();
//
// /**
// * <p>
// * The next matched position. This is equivalent to {@link #next()} but
// * may be expected to be slightly more efficient, with the differences
// * being that:
// *
// * <ul>
// * <li>The position is returned as a primitive is returned, not a boxed
// * primitive.
// * <li>If there's no position, the value of {@link BitStore#size()} is
// * returned instead of an exception being raised.
// * </ul>
// *
// * <p>
// * Otherwise, the effect of calling the method is the same.
// *
// * @return the next position, or the first invalid index if there is no
// * further position
// */
//
// int nextPosition();
//
// /**
// * <p>
// * The previous matched position. This is equivalent to
// * {@link #previous()} but may be expected to be slightly more
// * efficient, with the differences being that:
// *
// * <ul>
// * <li>The position is returned as a primitive is returned, not a boxed
// * primitive.
// * <li>If there's no position, the value of {@link BitStore#size()} is
// * returned instead of an exception being raised.
// * </ul>
// *
// * <p>
// * Otherwise, the effect of calling the method is the same.
// *
// * @return the previous position, or -1 if there is no further position
// */
//
// int previousPosition();
//
// /**
// * Replaces the last match returned by the {@link #next()}/
// * {@link #nextPosition()} and {@link #previous()}/
// * {@link #previousPosition()} methods, with the supplied bits.
// *
// * @param replacement
// * the bits to replace the matched sequence
// * @throws IllegalArgumentException
// * if the replacement size does not match the matched
// * sequence size
// * @throws IllegalStateException
// * if the underlying bit store is immutable, or if no call
// * to {@link #previous()} or {@link #next()} has been made
// * @see DisjointMatches#replaceAll(BitStore)
// */
//
// void replace(BitStore replacement);
//
// /**
// * Uniformly replaces the bits of last match returned by the
// * {@link #next()}/ {@link #nextPosition()} and {@link #previous()}/
// * {@link #previousPosition()} methods, with the specified bit value.
// *
// * @param bits
// * the bit value with which to replace the matched bits
// * @throws IllegalStateException
// * if the underlying bit store is immutable, or if no call
// * to {@link #previous()} or {@link #next()} has been made
// * @see DisjointMatches#replaceAll(boolean)
// */
//
// void replace(boolean bits);
// }
|
import java.util.Collections;
import java.util.SortedSet;
import com.tomgibara.bits.BitStore.BitMatches;
import com.tomgibara.bits.BitStore.Positions;
|
}
@Override
public boolean isAll() {
return matches.isAll();
}
@Override
public boolean isNone() {
return matches.isNone();
}
@Override
public int count() {
return matches.count();
}
@Override
public int first() {
return matches.first();
}
@Override
public int last() {
return matches.last();
}
@Override
public int next(int position) {
return matches.next(position);
}
@Override
public int previous(int position) {
return matches.previous(position);
}
@Override
|
// Path: src/main/java/com/tomgibara/bits/BitStore.java
// interface BitMatches extends OverlappingMatches, DisjointMatches {
//
// @Override
// BitMatches overlapping();
//
// @Override
// BitMatches disjoint();
//
// @Override
// BitMatches range(int from, int to);
//
// /**
// * Whether the {@link BitStore} consists entirely
// * of the matched bit value.
// *
// * @return true if and only if all bits in the store have the value of
// * {@link #bit()}
// */
//
// @Override
// boolean isAll();
//
// /**
// * Whether none of the bits in the {@link BitStore} have the matched bit
// * value.
// *
// * @return true if and only if none of the bits in the store have the
// * value of {@link #bit()}
// */
//
// @Override
// boolean isNone();
//
// /**
// * Whether 1s are being matched.
// *
// * @return bit value being matched
// */
//
// boolean bit();
//
// /**
// * The matched bit positions as a sorted set. The returned set is a live
// * view over the {@link BitStore} with mutations of the store being
// * reflected in the set and vice versa. Attempting to add integers to
// * the set that lie outside the range of valid bit indexes in the store
// * will fail.
// *
// * @return a set view of the matched bit positions
// */
//
// SortedSet<Integer> asSet();
//
// }
//
// Path: src/main/java/com/tomgibara/bits/BitStore.java
// interface Positions extends ListIterator<Integer> {
//
// /**
// * Indicates whether the iterator moves over pattern sequences such that
// * successive matched ranges do not over overlap.
// *
// * @return true if position matches do not overlap, false otherwise
// */
//
// boolean isDisjoint();
//
// /**
// * <p>
// * The next matched position. This is equivalent to {@link #next()} but
// * may be expected to be slightly more efficient, with the differences
// * being that:
// *
// * <ul>
// * <li>The position is returned as a primitive is returned, not a boxed
// * primitive.
// * <li>If there's no position, the value of {@link BitStore#size()} is
// * returned instead of an exception being raised.
// * </ul>
// *
// * <p>
// * Otherwise, the effect of calling the method is the same.
// *
// * @return the next position, or the first invalid index if there is no
// * further position
// */
//
// int nextPosition();
//
// /**
// * <p>
// * The previous matched position. This is equivalent to
// * {@link #previous()} but may be expected to be slightly more
// * efficient, with the differences being that:
// *
// * <ul>
// * <li>The position is returned as a primitive is returned, not a boxed
// * primitive.
// * <li>If there's no position, the value of {@link BitStore#size()} is
// * returned instead of an exception being raised.
// * </ul>
// *
// * <p>
// * Otherwise, the effect of calling the method is the same.
// *
// * @return the previous position, or -1 if there is no further position
// */
//
// int previousPosition();
//
// /**
// * Replaces the last match returned by the {@link #next()}/
// * {@link #nextPosition()} and {@link #previous()}/
// * {@link #previousPosition()} methods, with the supplied bits.
// *
// * @param replacement
// * the bits to replace the matched sequence
// * @throws IllegalArgumentException
// * if the replacement size does not match the matched
// * sequence size
// * @throws IllegalStateException
// * if the underlying bit store is immutable, or if no call
// * to {@link #previous()} or {@link #next()} has been made
// * @see DisjointMatches#replaceAll(BitStore)
// */
//
// void replace(BitStore replacement);
//
// /**
// * Uniformly replaces the bits of last match returned by the
// * {@link #next()}/ {@link #nextPosition()} and {@link #previous()}/
// * {@link #previousPosition()} methods, with the specified bit value.
// *
// * @param bits
// * the bit value with which to replace the matched bits
// * @throws IllegalStateException
// * if the underlying bit store is immutable, or if no call
// * to {@link #previous()} or {@link #next()} has been made
// * @see DisjointMatches#replaceAll(boolean)
// */
//
// void replace(boolean bits);
// }
// Path: src/main/java/com/tomgibara/bits/ImmutableMatches.java
import java.util.Collections;
import java.util.SortedSet;
import com.tomgibara.bits.BitStore.BitMatches;
import com.tomgibara.bits.BitStore.Positions;
}
@Override
public boolean isAll() {
return matches.isAll();
}
@Override
public boolean isNone() {
return matches.isNone();
}
@Override
public int count() {
return matches.count();
}
@Override
public int first() {
return matches.first();
}
@Override
public int last() {
return matches.last();
}
@Override
public int next(int position) {
return matches.next(position);
}
@Override
public int previous(int position) {
return matches.previous(position);
}
@Override
|
public Positions positions() {
|
tomgibara/bits
|
src/main/java/com/tomgibara/bits/BitStoreDisjointMatches.java
|
// Path: src/main/java/com/tomgibara/bits/BitStore.java
// interface DisjointMatches extends Matches {
//
// /**
// * Overlapping matches of the same bit sequence over the same
// * {@link BitStore}.
// *
// * @return overlapping matches
// */
//
// OverlappingMatches overlapping();
//
// @Override
// DisjointMatches range(int from, int to);
//
// /**
// * Whether every bit in the {@link BitStore} is accommodated within a
// * match of the bit sequence.
// *
// * @return whether the matches cover every bit in the {@link BitStore}
// */
//
// boolean isAll();
//
// /**
// * Whether there are no matched bits.
// *
// * @return whether there are no matches over the {@link BitStore}
// */
//
// boolean isNone();
//
// /**
// * Replaces all non-overlapping matches of the sequence with a new
// * sequence of the same size.
// *
// * @param replacement
// * a replacement bit sequence
// * @throws IllegalArgumentException
// * if the replacement size does not match the sequence size.
// * @throws IllegalStateException
// * if the underlying store is immutable
// */
//
// void replaceAll(BitStore replacement);
//
// /**
// * Replaces all the bits of every non-overlapping match with the
// * specified bit.
// *
// * @param bits
// * the replacement for matched bits
// * @throws IllegalStateException
// * if the underlying store is immutable
// */
//
// void replaceAll(boolean bits);
//
// }
//
// Path: src/main/java/com/tomgibara/bits/BitStore.java
// interface OverlappingMatches extends Matches {
//
// /**
// * Disjoint matches of the same bit sequence over the same
// * {@link BitStore}.
// *
// * @return disjoint matches
// */
//
// DisjointMatches disjoint();
//
// @Override
// OverlappingMatches range(int from, int to);
//
// }
|
import com.tomgibara.bits.BitStore.DisjointMatches;
import com.tomgibara.bits.BitStore.OverlappingMatches;
|
package com.tomgibara.bits;
class BitStoreDisjointMatches extends AbstractDisjointMatches {
private final OverlappingMatches matches;
BitStoreDisjointMatches(OverlappingMatches matches) {
super(matches);
this.matches = matches;
}
BitStoreDisjointMatches(BitStoreOverlappingMatches matches) {
super(matches);
this.matches = matches;
}
@Override
public OverlappingMatches overlapping() {
return matches;
}
@Override
|
// Path: src/main/java/com/tomgibara/bits/BitStore.java
// interface DisjointMatches extends Matches {
//
// /**
// * Overlapping matches of the same bit sequence over the same
// * {@link BitStore}.
// *
// * @return overlapping matches
// */
//
// OverlappingMatches overlapping();
//
// @Override
// DisjointMatches range(int from, int to);
//
// /**
// * Whether every bit in the {@link BitStore} is accommodated within a
// * match of the bit sequence.
// *
// * @return whether the matches cover every bit in the {@link BitStore}
// */
//
// boolean isAll();
//
// /**
// * Whether there are no matched bits.
// *
// * @return whether there are no matches over the {@link BitStore}
// */
//
// boolean isNone();
//
// /**
// * Replaces all non-overlapping matches of the sequence with a new
// * sequence of the same size.
// *
// * @param replacement
// * a replacement bit sequence
// * @throws IllegalArgumentException
// * if the replacement size does not match the sequence size.
// * @throws IllegalStateException
// * if the underlying store is immutable
// */
//
// void replaceAll(BitStore replacement);
//
// /**
// * Replaces all the bits of every non-overlapping match with the
// * specified bit.
// *
// * @param bits
// * the replacement for matched bits
// * @throws IllegalStateException
// * if the underlying store is immutable
// */
//
// void replaceAll(boolean bits);
//
// }
//
// Path: src/main/java/com/tomgibara/bits/BitStore.java
// interface OverlappingMatches extends Matches {
//
// /**
// * Disjoint matches of the same bit sequence over the same
// * {@link BitStore}.
// *
// * @return disjoint matches
// */
//
// DisjointMatches disjoint();
//
// @Override
// OverlappingMatches range(int from, int to);
//
// }
// Path: src/main/java/com/tomgibara/bits/BitStoreDisjointMatches.java
import com.tomgibara.bits.BitStore.DisjointMatches;
import com.tomgibara.bits.BitStore.OverlappingMatches;
package com.tomgibara.bits;
class BitStoreDisjointMatches extends AbstractDisjointMatches {
private final OverlappingMatches matches;
BitStoreDisjointMatches(OverlappingMatches matches) {
super(matches);
this.matches = matches;
}
BitStoreDisjointMatches(BitStoreOverlappingMatches matches) {
super(matches);
this.matches = matches;
}
@Override
public OverlappingMatches overlapping() {
return matches;
}
@Override
|
public DisjointMatches range(int from, int to) {
|
jachness/blockcalls
|
app/src/main/java/com/jachness/blockcalls/entities/LogEntity.java
|
// Path: app/src/main/java/com/jachness/blockcalls/db/LogTable.java
// public class LogTable {
//
// public static final String RELATIVE_PATH = "log";
// public static final String TABLE = "log";
//
// public static final String UID = "_id";
// public static final String CALLER_ID = "caller_id";
// public static final String DISPLAY_NUMBER = "display_number";
// public static final String DISPLAY_NAME = "display_name";
// public static final String DATE = "date";
// public static final String BLOCK_ORIGIN = "block_origin";
//
// public static final Uri CONTENT_URI = Uri.parse("content://" + LogProvider.AUTHORITY + "/" +
// RELATIVE_PATH);
//
// public static final String CONTENT_TYPE = "vnd.android.cursor.dir/" + RELATIVE_PATH;
// public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/" + RELATIVE_PATH;
//
// public static final int SSID_PATH_POSITION = 1;
//
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/stuff/BlockOrigin.java
// public enum BlockOrigin {
// PRIVATE, CONTACTS, BLACK_LIST
// }
|
import android.content.ContentValues;
import android.database.Cursor;
import android.support.annotation.NonNull;
import com.jachness.blockcalls.db.LogTable;
import com.jachness.blockcalls.stuff.BlockOrigin;
|
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.entities;
public class LogEntity {
private Long uid;
private String callerID;
private String displayNumber;
private String displayName;
private long time;
|
// Path: app/src/main/java/com/jachness/blockcalls/db/LogTable.java
// public class LogTable {
//
// public static final String RELATIVE_PATH = "log";
// public static final String TABLE = "log";
//
// public static final String UID = "_id";
// public static final String CALLER_ID = "caller_id";
// public static final String DISPLAY_NUMBER = "display_number";
// public static final String DISPLAY_NAME = "display_name";
// public static final String DATE = "date";
// public static final String BLOCK_ORIGIN = "block_origin";
//
// public static final Uri CONTENT_URI = Uri.parse("content://" + LogProvider.AUTHORITY + "/" +
// RELATIVE_PATH);
//
// public static final String CONTENT_TYPE = "vnd.android.cursor.dir/" + RELATIVE_PATH;
// public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/" + RELATIVE_PATH;
//
// public static final int SSID_PATH_POSITION = 1;
//
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/stuff/BlockOrigin.java
// public enum BlockOrigin {
// PRIVATE, CONTACTS, BLACK_LIST
// }
// Path: app/src/main/java/com/jachness/blockcalls/entities/LogEntity.java
import android.content.ContentValues;
import android.database.Cursor;
import android.support.annotation.NonNull;
import com.jachness.blockcalls.db.LogTable;
import com.jachness.blockcalls.stuff.BlockOrigin;
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.entities;
public class LogEntity {
private Long uid;
private String callerID;
private String displayNumber;
private String displayName;
private long time;
|
private BlockOrigin blockOrigin;
|
jachness/blockcalls
|
app/src/main/java/com/jachness/blockcalls/entities/LogEntity.java
|
// Path: app/src/main/java/com/jachness/blockcalls/db/LogTable.java
// public class LogTable {
//
// public static final String RELATIVE_PATH = "log";
// public static final String TABLE = "log";
//
// public static final String UID = "_id";
// public static final String CALLER_ID = "caller_id";
// public static final String DISPLAY_NUMBER = "display_number";
// public static final String DISPLAY_NAME = "display_name";
// public static final String DATE = "date";
// public static final String BLOCK_ORIGIN = "block_origin";
//
// public static final Uri CONTENT_URI = Uri.parse("content://" + LogProvider.AUTHORITY + "/" +
// RELATIVE_PATH);
//
// public static final String CONTENT_TYPE = "vnd.android.cursor.dir/" + RELATIVE_PATH;
// public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/" + RELATIVE_PATH;
//
// public static final int SSID_PATH_POSITION = 1;
//
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/stuff/BlockOrigin.java
// public enum BlockOrigin {
// PRIVATE, CONTACTS, BLACK_LIST
// }
|
import android.content.ContentValues;
import android.database.Cursor;
import android.support.annotation.NonNull;
import com.jachness.blockcalls.db.LogTable;
import com.jachness.blockcalls.stuff.BlockOrigin;
|
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.entities;
public class LogEntity {
private Long uid;
private String callerID;
private String displayNumber;
private String displayName;
private long time;
private BlockOrigin blockOrigin;
public LogEntity() {
}
public LogEntity(Cursor cur) {
for (String colName : cur.getColumnNames()) {
int colIndex = cur.getColumnIndexOrThrow(colName);
switch (colName) {
|
// Path: app/src/main/java/com/jachness/blockcalls/db/LogTable.java
// public class LogTable {
//
// public static final String RELATIVE_PATH = "log";
// public static final String TABLE = "log";
//
// public static final String UID = "_id";
// public static final String CALLER_ID = "caller_id";
// public static final String DISPLAY_NUMBER = "display_number";
// public static final String DISPLAY_NAME = "display_name";
// public static final String DATE = "date";
// public static final String BLOCK_ORIGIN = "block_origin";
//
// public static final Uri CONTENT_URI = Uri.parse("content://" + LogProvider.AUTHORITY + "/" +
// RELATIVE_PATH);
//
// public static final String CONTENT_TYPE = "vnd.android.cursor.dir/" + RELATIVE_PATH;
// public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/" + RELATIVE_PATH;
//
// public static final int SSID_PATH_POSITION = 1;
//
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/stuff/BlockOrigin.java
// public enum BlockOrigin {
// PRIVATE, CONTACTS, BLACK_LIST
// }
// Path: app/src/main/java/com/jachness/blockcalls/entities/LogEntity.java
import android.content.ContentValues;
import android.database.Cursor;
import android.support.annotation.NonNull;
import com.jachness.blockcalls.db.LogTable;
import com.jachness.blockcalls.stuff.BlockOrigin;
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.entities;
public class LogEntity {
private Long uid;
private String callerID;
private String displayNumber;
private String displayName;
private long time;
private BlockOrigin blockOrigin;
public LogEntity() {
}
public LogEntity(Cursor cur) {
for (String colName : cur.getColumnNames()) {
int colIndex = cur.getColumnIndexOrThrow(colName);
switch (colName) {
|
case LogTable.CALLER_ID:
|
jachness/blockcalls
|
app/src/main/java/com/jachness/blockcalls/activities/AddContactFragment.java
|
// Path: app/src/main/java/com/jachness/blockcalls/stuff/AppContext.java
// public class AppContext extends Application {
// private AllComponent dagger;
// @Inject
// AppPreferences appPreferences;
// @Inject
// Lazy<ImportExportWrapper> importExportWrapper;
// @Inject
// Lazy<BlackListWrapper> blackListWrapper;
//
// @Override
// public void onCreate() {
// super.onCreate();
// //If DaggerAllComponent gives an error, just rebuild the project
// dagger = DaggerAllComponent.builder().blockModule(new BlockModule(this)).appModule(new
// AppModule(this)).dAOModule(new DAOModule(this)).build();
// dagger.inject(this);
//
// }
//
// public AppPreferences getAppPreferences() {
// return appPreferences;
// }
//
// public ImportExportWrapper getImportExportWrapper() {
// return importExportWrapper.get();
// }
//
// public BlackListWrapper getBlackListWrapper() {
// return blackListWrapper.get();
// }
//
// public AllComponent getDagger() {
// return dagger;
// }
//
//
// }
|
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import com.jachness.blockcalls.R;
import com.jachness.blockcalls.stuff.AppContext;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
|
itemClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckBox cb = (CheckBox) view.findViewById(R.id.contactCbSelected);
cb.setChecked(!cb.isChecked());
}
};
checkedChangeListener = new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
CheckBox cb = (CheckBox) buttonView;
int id = (int) cb.getTag(R.string.tag_id);
if (numbersSelected.containsKey(id)) {
numbersSelected.remove(id);
cb.setChecked(false);
} else {
numbersSelected.put(id, (String[]) cb.getTag(R.string.tag_data));
cb.setChecked(true);
}
updateOkButton();
}
};
okButtonListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
|
// Path: app/src/main/java/com/jachness/blockcalls/stuff/AppContext.java
// public class AppContext extends Application {
// private AllComponent dagger;
// @Inject
// AppPreferences appPreferences;
// @Inject
// Lazy<ImportExportWrapper> importExportWrapper;
// @Inject
// Lazy<BlackListWrapper> blackListWrapper;
//
// @Override
// public void onCreate() {
// super.onCreate();
// //If DaggerAllComponent gives an error, just rebuild the project
// dagger = DaggerAllComponent.builder().blockModule(new BlockModule(this)).appModule(new
// AppModule(this)).dAOModule(new DAOModule(this)).build();
// dagger.inject(this);
//
// }
//
// public AppPreferences getAppPreferences() {
// return appPreferences;
// }
//
// public ImportExportWrapper getImportExportWrapper() {
// return importExportWrapper.get();
// }
//
// public BlackListWrapper getBlackListWrapper() {
// return blackListWrapper.get();
// }
//
// public AllComponent getDagger() {
// return dagger;
// }
//
//
// }
// Path: app/src/main/java/com/jachness/blockcalls/activities/AddContactFragment.java
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import com.jachness.blockcalls.R;
import com.jachness.blockcalls.stuff.AppContext;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
itemClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckBox cb = (CheckBox) view.findViewById(R.id.contactCbSelected);
cb.setChecked(!cb.isChecked());
}
};
checkedChangeListener = new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
CheckBox cb = (CheckBox) buttonView;
int id = (int) cb.getTag(R.string.tag_id);
if (numbersSelected.containsKey(id)) {
numbersSelected.remove(id);
cb.setChecked(false);
} else {
numbersSelected.put(id, (String[]) cb.getTag(R.string.tag_data));
cb.setChecked(true);
}
updateOkButton();
}
};
okButtonListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
|
AppContext appContext = (AppContext) getActivity().getApplicationContext();
|
jachness/blockcalls
|
app/src/main/java/com/jachness/blockcalls/stuff/Util.java
|
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/FileException.java
// @SuppressWarnings("SameParameterValue")
// public class FileException extends Exception {
// public static final int MEDIA_ERROR = 0;
// public static final int READ_FILE_ERROR = 1;
// public static final int WRITE_FILE_ERROR = 2;
// private final int errorCode;
//
// public FileException(int errorCode) {
// this.errorCode = errorCode;
// }
//
// public FileException(int errorCode, String message) {
// super(message);
// this.errorCode = errorCode;
// }
//
// public FileException(int errorCode, String message, Throwable cause) {
// super(message, cause);
// this.errorCode = errorCode;
// }
//
// public int getErrorCode() {
// return errorCode;
// }
// }
|
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Build;
import android.support.annotation.NonNull;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import com.jachness.blockcalls.R;
import com.jachness.blockcalls.exceptions.FileException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Locale;
import hugo.weaving.DebugLog;
|
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.stuff;
/**
* Created by jachness on 28/9/2016.
*/
public class Util {
private static final String TAG = Util.class.getSimpleName();
@SuppressWarnings("deprecation")
@DebugLog
public static Locale getDefaultLocale() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return Resources.getSystem().getConfiguration().getLocales().get(0);
} else {
return Resources.getSystem().getConfiguration().locale;
}
}
@DebugLog
|
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/FileException.java
// @SuppressWarnings("SameParameterValue")
// public class FileException extends Exception {
// public static final int MEDIA_ERROR = 0;
// public static final int READ_FILE_ERROR = 1;
// public static final int WRITE_FILE_ERROR = 2;
// private final int errorCode;
//
// public FileException(int errorCode) {
// this.errorCode = errorCode;
// }
//
// public FileException(int errorCode, String message) {
// super(message);
// this.errorCode = errorCode;
// }
//
// public FileException(int errorCode, String message, Throwable cause) {
// super(message, cause);
// this.errorCode = errorCode;
// }
//
// public int getErrorCode() {
// return errorCode;
// }
// }
// Path: app/src/main/java/com/jachness/blockcalls/stuff/Util.java
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Build;
import android.support.annotation.NonNull;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import com.jachness.blockcalls.R;
import com.jachness.blockcalls.exceptions.FileException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Locale;
import hugo.weaving.DebugLog;
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.stuff;
/**
* Created by jachness on 28/9/2016.
*/
public class Util {
private static final String TAG = Util.class.getSimpleName();
@SuppressWarnings("deprecation")
@DebugLog
public static Locale getDefaultLocale() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return Resources.getSystem().getConfiguration().getLocales().get(0);
} else {
return Resources.getSystem().getConfiguration().locale;
}
}
@DebugLog
|
public static int getStringId(@NonNull FileException e) {
|
jachness/blockcalls
|
app/src/main/java/com/jachness/blockcalls/services/IChecker.java
|
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/PhoneNumberException.java
// public class PhoneNumberException extends Exception {
//
// public PhoneNumberException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/TooShortNumberException.java
// public class TooShortNumberException extends Exception {
// public static final int MINIMUM_LENGTH = 3;
//
// public TooShortNumberException(String message) {
// super(message);
// }
// }
|
import com.jachness.blockcalls.exceptions.PhoneNumberException;
import com.jachness.blockcalls.exceptions.TooShortNumberException;
|
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.services;
/**
* Created by jachness on 11/11/2016.
*/
public interface IChecker {
int YES = 0;
int NO = 1;
int NONE = 2;
|
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/PhoneNumberException.java
// public class PhoneNumberException extends Exception {
//
// public PhoneNumberException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/TooShortNumberException.java
// public class TooShortNumberException extends Exception {
// public static final int MINIMUM_LENGTH = 3;
//
// public TooShortNumberException(String message) {
// super(message);
// }
// }
// Path: app/src/main/java/com/jachness/blockcalls/services/IChecker.java
import com.jachness.blockcalls.exceptions.PhoneNumberException;
import com.jachness.blockcalls.exceptions.TooShortNumberException;
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.services;
/**
* Created by jachness on 11/11/2016.
*/
public interface IChecker {
int YES = 0;
int NO = 1;
int NONE = 2;
|
int isBlockable(Call call) throws TooShortNumberException, PhoneNumberException;
|
jachness/blockcalls
|
app/src/main/java/com/jachness/blockcalls/services/IChecker.java
|
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/PhoneNumberException.java
// public class PhoneNumberException extends Exception {
//
// public PhoneNumberException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/TooShortNumberException.java
// public class TooShortNumberException extends Exception {
// public static final int MINIMUM_LENGTH = 3;
//
// public TooShortNumberException(String message) {
// super(message);
// }
// }
|
import com.jachness.blockcalls.exceptions.PhoneNumberException;
import com.jachness.blockcalls.exceptions.TooShortNumberException;
|
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.services;
/**
* Created by jachness on 11/11/2016.
*/
public interface IChecker {
int YES = 0;
int NO = 1;
int NONE = 2;
|
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/PhoneNumberException.java
// public class PhoneNumberException extends Exception {
//
// public PhoneNumberException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/TooShortNumberException.java
// public class TooShortNumberException extends Exception {
// public static final int MINIMUM_LENGTH = 3;
//
// public TooShortNumberException(String message) {
// super(message);
// }
// }
// Path: app/src/main/java/com/jachness/blockcalls/services/IChecker.java
import com.jachness.blockcalls.exceptions.PhoneNumberException;
import com.jachness.blockcalls.exceptions.TooShortNumberException;
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.services;
/**
* Created by jachness on 11/11/2016.
*/
public interface IChecker {
int YES = 0;
int NO = 1;
int NONE = 2;
|
int isBlockable(Call call) throws TooShortNumberException, PhoneNumberException;
|
jachness/blockcalls
|
app/src/main/java/com/jachness/blockcalls/modules/DAOModule.java
|
// Path: app/src/main/java/com/jachness/blockcalls/db/dao/BlackListDAO.java
// public class BlackListDAO {
// private static final String TAG = BlackListDAO.class.getSimpleName();
// private final Context context;
//
// public BlackListDAO(Context context) {
// this.context = context;
// }
//
// @DebugLog
// public List<BlackListNumberEntity> findForBlock(Call call) {
//
// String nationalNumber = Long.toString(call.getNormalizedNumber().getNationalNumber());
// String rawNumber = call.getNormalizedNumber().getRawInput();
// int beginIndex = nationalNumber.length() - TooShortNumberException.MINIMUM_LENGTH;
// String lastDigits = nationalNumber.substring(beginIndex, nationalNumber.length());
//
// String selectFormalNumber = BlackListTable.NORMALIZED_NUMBER + " LIKE ? AND " +
// BlackListTable.NORMALIZED_NUMBER + " LIKE ? AND " + BlackListTable.BEGIN_WITH +
// "=0";
// String selectBeginWith = BlackListTable.BEGIN_WITH + "=1 AND " + BlackListTable
// .NORMALIZED_NUMBER + " = substr(?,0, " +
// "length(" + BlackListTable.NORMALIZED_NUMBER + ")+1)";
//
// if (BuildConfig.DEBUG) {
// Log.d(TAG, "Parameter 1:" + "+" + call.getNormalizedNumber().getCountryCode() + "%");
// Log.d(TAG, "Parameter 2:" + "%" + lastDigits);
// Log.d(TAG, "Parameter 3:" + rawNumber);
// }
// Cursor cursor = context.getContentResolver().query(
// BlackListTable.CONTENT_URI, null,
// BlackListTable.ENABLED + "=1 AND ((" + selectFormalNumber + ") OR (" +
// selectBeginWith + "))",
// new String[]{"+" + call.getNormalizedNumber().getCountryCode() + "%", "%" +
// lastDigits, rawNumber},
// BlackListTable.BEGIN_WITH + " DESC");
//
// try {
// if (cursor != null) {
// List<BlackListNumberEntity> list = new ArrayList<>(cursor.getCount());
// while (cursor.moveToNext()) {
// list.add(new BlackListNumberEntity(cursor));
// }
// return list;
// }
// return new ArrayList<>(0);
// } finally {
// Util.close(cursor);
// }
// }
//
// @DebugLog
// public boolean existByNormalizedNumber(String number) {
// Cursor cursor = null;
// try {
// cursor = context.getContentResolver().query(BlackListTable.CONTENT_URI, new
// String[]{BlackListTable.UID},
// BlackListTable.NORMALIZED_NUMBER + " = '" + number + "'", null, null);
// return cursor != null && cursor.getCount() > 0;
// } finally {
// Util.close(cursor);
// }
// }
//
// @DebugLog
// public void delete(BlackListNumberEntity entity) {
// int rows = context.getContentResolver().delete(entity.getUniqueUri(), null, null);
// if (rows != 1) {
// String error = "Could not delete row in " + BlackListTable.TABLE + " table: ";
// Log.e(TAG, error + entity.toString());
// throw new RuntimeException(error + entity.toString());
// }
// }
//
// public void updateEnabled(BlackListNumberEntity entity, boolean enabled) {
// ContentValues cv = new ContentValues();
// cv.put(BlackListTable.ENABLED, enabled ? 1 : 0);
// int rows = context.getContentResolver().update(entity.getUniqueUri(), cv, null, null);
// if (rows != 1) {
// String error = "Could not update row in " + BlackListTable.TABLE + " table: ";
// Log.e(TAG, error + entity.toString());
// throw new RuntimeException(error + entity.toString());
// }
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/db/dao/ContactDAO.java
// public class ContactDAO {
// private final Context context;
//
// public ContactDAO(Context context) {
// this.context = context;
// }
//
// @DebugLog
// public String[] findContact(String number) {
// Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri
// .encode(number));
// Cursor cursor = context.getContentResolver().query(uri,
// new String[]{ContactsContract.PhoneLookup.NUMBER, ContactsContract.PhoneLookup
// .DISPLAY_NAME},
// null, null, null);
//
// try {
// String contact[] = null;
// if (cursor != null && cursor.moveToNext()) {
// int displayNameIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup
// .DISPLAY_NAME);
// int numberIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.NUMBER);
// contact = new String[]{cursor.getString(numberIndex), cursor.getString
// (displayNameIndex)};
// }
// return contact;
// } finally {
// Util.close(cursor);
// }
// }
// }
|
import android.content.Context;
import com.jachness.blockcalls.db.dao.BlackListDAO;
import com.jachness.blockcalls.db.dao.ContactDAO;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
|
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.modules;
/**
* Created by jachness on 26/12/2016.
*/
@Module
public class DAOModule {
private final Context context;
public DAOModule(Context context) {
this.context = context;
}
@Provides
@Singleton
|
// Path: app/src/main/java/com/jachness/blockcalls/db/dao/BlackListDAO.java
// public class BlackListDAO {
// private static final String TAG = BlackListDAO.class.getSimpleName();
// private final Context context;
//
// public BlackListDAO(Context context) {
// this.context = context;
// }
//
// @DebugLog
// public List<BlackListNumberEntity> findForBlock(Call call) {
//
// String nationalNumber = Long.toString(call.getNormalizedNumber().getNationalNumber());
// String rawNumber = call.getNormalizedNumber().getRawInput();
// int beginIndex = nationalNumber.length() - TooShortNumberException.MINIMUM_LENGTH;
// String lastDigits = nationalNumber.substring(beginIndex, nationalNumber.length());
//
// String selectFormalNumber = BlackListTable.NORMALIZED_NUMBER + " LIKE ? AND " +
// BlackListTable.NORMALIZED_NUMBER + " LIKE ? AND " + BlackListTable.BEGIN_WITH +
// "=0";
// String selectBeginWith = BlackListTable.BEGIN_WITH + "=1 AND " + BlackListTable
// .NORMALIZED_NUMBER + " = substr(?,0, " +
// "length(" + BlackListTable.NORMALIZED_NUMBER + ")+1)";
//
// if (BuildConfig.DEBUG) {
// Log.d(TAG, "Parameter 1:" + "+" + call.getNormalizedNumber().getCountryCode() + "%");
// Log.d(TAG, "Parameter 2:" + "%" + lastDigits);
// Log.d(TAG, "Parameter 3:" + rawNumber);
// }
// Cursor cursor = context.getContentResolver().query(
// BlackListTable.CONTENT_URI, null,
// BlackListTable.ENABLED + "=1 AND ((" + selectFormalNumber + ") OR (" +
// selectBeginWith + "))",
// new String[]{"+" + call.getNormalizedNumber().getCountryCode() + "%", "%" +
// lastDigits, rawNumber},
// BlackListTable.BEGIN_WITH + " DESC");
//
// try {
// if (cursor != null) {
// List<BlackListNumberEntity> list = new ArrayList<>(cursor.getCount());
// while (cursor.moveToNext()) {
// list.add(new BlackListNumberEntity(cursor));
// }
// return list;
// }
// return new ArrayList<>(0);
// } finally {
// Util.close(cursor);
// }
// }
//
// @DebugLog
// public boolean existByNormalizedNumber(String number) {
// Cursor cursor = null;
// try {
// cursor = context.getContentResolver().query(BlackListTable.CONTENT_URI, new
// String[]{BlackListTable.UID},
// BlackListTable.NORMALIZED_NUMBER + " = '" + number + "'", null, null);
// return cursor != null && cursor.getCount() > 0;
// } finally {
// Util.close(cursor);
// }
// }
//
// @DebugLog
// public void delete(BlackListNumberEntity entity) {
// int rows = context.getContentResolver().delete(entity.getUniqueUri(), null, null);
// if (rows != 1) {
// String error = "Could not delete row in " + BlackListTable.TABLE + " table: ";
// Log.e(TAG, error + entity.toString());
// throw new RuntimeException(error + entity.toString());
// }
// }
//
// public void updateEnabled(BlackListNumberEntity entity, boolean enabled) {
// ContentValues cv = new ContentValues();
// cv.put(BlackListTable.ENABLED, enabled ? 1 : 0);
// int rows = context.getContentResolver().update(entity.getUniqueUri(), cv, null, null);
// if (rows != 1) {
// String error = "Could not update row in " + BlackListTable.TABLE + " table: ";
// Log.e(TAG, error + entity.toString());
// throw new RuntimeException(error + entity.toString());
// }
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/db/dao/ContactDAO.java
// public class ContactDAO {
// private final Context context;
//
// public ContactDAO(Context context) {
// this.context = context;
// }
//
// @DebugLog
// public String[] findContact(String number) {
// Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri
// .encode(number));
// Cursor cursor = context.getContentResolver().query(uri,
// new String[]{ContactsContract.PhoneLookup.NUMBER, ContactsContract.PhoneLookup
// .DISPLAY_NAME},
// null, null, null);
//
// try {
// String contact[] = null;
// if (cursor != null && cursor.moveToNext()) {
// int displayNameIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup
// .DISPLAY_NAME);
// int numberIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.NUMBER);
// contact = new String[]{cursor.getString(numberIndex), cursor.getString
// (displayNameIndex)};
// }
// return contact;
// } finally {
// Util.close(cursor);
// }
// }
// }
// Path: app/src/main/java/com/jachness/blockcalls/modules/DAOModule.java
import android.content.Context;
import com.jachness.blockcalls.db.dao.BlackListDAO;
import com.jachness.blockcalls.db.dao.ContactDAO;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.modules;
/**
* Created by jachness on 26/12/2016.
*/
@Module
public class DAOModule {
private final Context context;
public DAOModule(Context context) {
this.context = context;
}
@Provides
@Singleton
|
ContactDAO providesContactDAO() {
|
jachness/blockcalls
|
app/src/main/java/com/jachness/blockcalls/modules/DAOModule.java
|
// Path: app/src/main/java/com/jachness/blockcalls/db/dao/BlackListDAO.java
// public class BlackListDAO {
// private static final String TAG = BlackListDAO.class.getSimpleName();
// private final Context context;
//
// public BlackListDAO(Context context) {
// this.context = context;
// }
//
// @DebugLog
// public List<BlackListNumberEntity> findForBlock(Call call) {
//
// String nationalNumber = Long.toString(call.getNormalizedNumber().getNationalNumber());
// String rawNumber = call.getNormalizedNumber().getRawInput();
// int beginIndex = nationalNumber.length() - TooShortNumberException.MINIMUM_LENGTH;
// String lastDigits = nationalNumber.substring(beginIndex, nationalNumber.length());
//
// String selectFormalNumber = BlackListTable.NORMALIZED_NUMBER + " LIKE ? AND " +
// BlackListTable.NORMALIZED_NUMBER + " LIKE ? AND " + BlackListTable.BEGIN_WITH +
// "=0";
// String selectBeginWith = BlackListTable.BEGIN_WITH + "=1 AND " + BlackListTable
// .NORMALIZED_NUMBER + " = substr(?,0, " +
// "length(" + BlackListTable.NORMALIZED_NUMBER + ")+1)";
//
// if (BuildConfig.DEBUG) {
// Log.d(TAG, "Parameter 1:" + "+" + call.getNormalizedNumber().getCountryCode() + "%");
// Log.d(TAG, "Parameter 2:" + "%" + lastDigits);
// Log.d(TAG, "Parameter 3:" + rawNumber);
// }
// Cursor cursor = context.getContentResolver().query(
// BlackListTable.CONTENT_URI, null,
// BlackListTable.ENABLED + "=1 AND ((" + selectFormalNumber + ") OR (" +
// selectBeginWith + "))",
// new String[]{"+" + call.getNormalizedNumber().getCountryCode() + "%", "%" +
// lastDigits, rawNumber},
// BlackListTable.BEGIN_WITH + " DESC");
//
// try {
// if (cursor != null) {
// List<BlackListNumberEntity> list = new ArrayList<>(cursor.getCount());
// while (cursor.moveToNext()) {
// list.add(new BlackListNumberEntity(cursor));
// }
// return list;
// }
// return new ArrayList<>(0);
// } finally {
// Util.close(cursor);
// }
// }
//
// @DebugLog
// public boolean existByNormalizedNumber(String number) {
// Cursor cursor = null;
// try {
// cursor = context.getContentResolver().query(BlackListTable.CONTENT_URI, new
// String[]{BlackListTable.UID},
// BlackListTable.NORMALIZED_NUMBER + " = '" + number + "'", null, null);
// return cursor != null && cursor.getCount() > 0;
// } finally {
// Util.close(cursor);
// }
// }
//
// @DebugLog
// public void delete(BlackListNumberEntity entity) {
// int rows = context.getContentResolver().delete(entity.getUniqueUri(), null, null);
// if (rows != 1) {
// String error = "Could not delete row in " + BlackListTable.TABLE + " table: ";
// Log.e(TAG, error + entity.toString());
// throw new RuntimeException(error + entity.toString());
// }
// }
//
// public void updateEnabled(BlackListNumberEntity entity, boolean enabled) {
// ContentValues cv = new ContentValues();
// cv.put(BlackListTable.ENABLED, enabled ? 1 : 0);
// int rows = context.getContentResolver().update(entity.getUniqueUri(), cv, null, null);
// if (rows != 1) {
// String error = "Could not update row in " + BlackListTable.TABLE + " table: ";
// Log.e(TAG, error + entity.toString());
// throw new RuntimeException(error + entity.toString());
// }
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/db/dao/ContactDAO.java
// public class ContactDAO {
// private final Context context;
//
// public ContactDAO(Context context) {
// this.context = context;
// }
//
// @DebugLog
// public String[] findContact(String number) {
// Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri
// .encode(number));
// Cursor cursor = context.getContentResolver().query(uri,
// new String[]{ContactsContract.PhoneLookup.NUMBER, ContactsContract.PhoneLookup
// .DISPLAY_NAME},
// null, null, null);
//
// try {
// String contact[] = null;
// if (cursor != null && cursor.moveToNext()) {
// int displayNameIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup
// .DISPLAY_NAME);
// int numberIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.NUMBER);
// contact = new String[]{cursor.getString(numberIndex), cursor.getString
// (displayNameIndex)};
// }
// return contact;
// } finally {
// Util.close(cursor);
// }
// }
// }
|
import android.content.Context;
import com.jachness.blockcalls.db.dao.BlackListDAO;
import com.jachness.blockcalls.db.dao.ContactDAO;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
|
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.modules;
/**
* Created by jachness on 26/12/2016.
*/
@Module
public class DAOModule {
private final Context context;
public DAOModule(Context context) {
this.context = context;
}
@Provides
@Singleton
ContactDAO providesContactDAO() {
return new ContactDAO(context);
}
@Provides
@Singleton
|
// Path: app/src/main/java/com/jachness/blockcalls/db/dao/BlackListDAO.java
// public class BlackListDAO {
// private static final String TAG = BlackListDAO.class.getSimpleName();
// private final Context context;
//
// public BlackListDAO(Context context) {
// this.context = context;
// }
//
// @DebugLog
// public List<BlackListNumberEntity> findForBlock(Call call) {
//
// String nationalNumber = Long.toString(call.getNormalizedNumber().getNationalNumber());
// String rawNumber = call.getNormalizedNumber().getRawInput();
// int beginIndex = nationalNumber.length() - TooShortNumberException.MINIMUM_LENGTH;
// String lastDigits = nationalNumber.substring(beginIndex, nationalNumber.length());
//
// String selectFormalNumber = BlackListTable.NORMALIZED_NUMBER + " LIKE ? AND " +
// BlackListTable.NORMALIZED_NUMBER + " LIKE ? AND " + BlackListTable.BEGIN_WITH +
// "=0";
// String selectBeginWith = BlackListTable.BEGIN_WITH + "=1 AND " + BlackListTable
// .NORMALIZED_NUMBER + " = substr(?,0, " +
// "length(" + BlackListTable.NORMALIZED_NUMBER + ")+1)";
//
// if (BuildConfig.DEBUG) {
// Log.d(TAG, "Parameter 1:" + "+" + call.getNormalizedNumber().getCountryCode() + "%");
// Log.d(TAG, "Parameter 2:" + "%" + lastDigits);
// Log.d(TAG, "Parameter 3:" + rawNumber);
// }
// Cursor cursor = context.getContentResolver().query(
// BlackListTable.CONTENT_URI, null,
// BlackListTable.ENABLED + "=1 AND ((" + selectFormalNumber + ") OR (" +
// selectBeginWith + "))",
// new String[]{"+" + call.getNormalizedNumber().getCountryCode() + "%", "%" +
// lastDigits, rawNumber},
// BlackListTable.BEGIN_WITH + " DESC");
//
// try {
// if (cursor != null) {
// List<BlackListNumberEntity> list = new ArrayList<>(cursor.getCount());
// while (cursor.moveToNext()) {
// list.add(new BlackListNumberEntity(cursor));
// }
// return list;
// }
// return new ArrayList<>(0);
// } finally {
// Util.close(cursor);
// }
// }
//
// @DebugLog
// public boolean existByNormalizedNumber(String number) {
// Cursor cursor = null;
// try {
// cursor = context.getContentResolver().query(BlackListTable.CONTENT_URI, new
// String[]{BlackListTable.UID},
// BlackListTable.NORMALIZED_NUMBER + " = '" + number + "'", null, null);
// return cursor != null && cursor.getCount() > 0;
// } finally {
// Util.close(cursor);
// }
// }
//
// @DebugLog
// public void delete(BlackListNumberEntity entity) {
// int rows = context.getContentResolver().delete(entity.getUniqueUri(), null, null);
// if (rows != 1) {
// String error = "Could not delete row in " + BlackListTable.TABLE + " table: ";
// Log.e(TAG, error + entity.toString());
// throw new RuntimeException(error + entity.toString());
// }
// }
//
// public void updateEnabled(BlackListNumberEntity entity, boolean enabled) {
// ContentValues cv = new ContentValues();
// cv.put(BlackListTable.ENABLED, enabled ? 1 : 0);
// int rows = context.getContentResolver().update(entity.getUniqueUri(), cv, null, null);
// if (rows != 1) {
// String error = "Could not update row in " + BlackListTable.TABLE + " table: ";
// Log.e(TAG, error + entity.toString());
// throw new RuntimeException(error + entity.toString());
// }
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/db/dao/ContactDAO.java
// public class ContactDAO {
// private final Context context;
//
// public ContactDAO(Context context) {
// this.context = context;
// }
//
// @DebugLog
// public String[] findContact(String number) {
// Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri
// .encode(number));
// Cursor cursor = context.getContentResolver().query(uri,
// new String[]{ContactsContract.PhoneLookup.NUMBER, ContactsContract.PhoneLookup
// .DISPLAY_NAME},
// null, null, null);
//
// try {
// String contact[] = null;
// if (cursor != null && cursor.moveToNext()) {
// int displayNameIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup
// .DISPLAY_NAME);
// int numberIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.NUMBER);
// contact = new String[]{cursor.getString(numberIndex), cursor.getString
// (displayNameIndex)};
// }
// return contact;
// } finally {
// Util.close(cursor);
// }
// }
// }
// Path: app/src/main/java/com/jachness/blockcalls/modules/DAOModule.java
import android.content.Context;
import com.jachness.blockcalls.db.dao.BlackListDAO;
import com.jachness.blockcalls.db.dao.ContactDAO;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.modules;
/**
* Created by jachness on 26/12/2016.
*/
@Module
public class DAOModule {
private final Context context;
public DAOModule(Context context) {
this.context = context;
}
@Provides
@Singleton
ContactDAO providesContactDAO() {
return new ContactDAO(context);
}
@Provides
@Singleton
|
BlackListDAO providesBlackListDAO() {
|
jachness/blockcalls
|
app/src/main/java/com/jachness/blockcalls/services/EndCallService.java
|
// Path: app/src/main/java/com/jachness/blockcalls/stuff/ManagerUtil.java
// public class ManagerUtil {
// @DebugLog
// public static TelephonyManager getTelephonyManager(Context context) {
// return (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
// }
//
// @DebugLog
// public static AudioManager getAudioManager(Context context) {
// return (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
// }
//
// @DebugLog
// public static NotificationManager getNotificationManager(Context context) {
// return (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// }
// }
|
import hugo.weaving.DebugLog;
import android.content.Context;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.util.Log;
import com.android.internal.telephony.ITelephony;
import com.jachness.blockcalls.stuff.ManagerUtil;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
|
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.services;
/**
* Created by jachness on 13/11/2016.
*/
@SuppressWarnings("TryWithIdenticalCatches")
public class EndCallService {
private static final String GET_I_TELEPHONY = "getITelephony";
private static final String TAG = EndCallService.class.getSimpleName();
private final Context context;
private final Method method;
@SuppressWarnings("unchecked")
public EndCallService(Context context) {
this.context = context;
try {
Class clazz = Class.forName(TelephonyManager.class.getName());
method = clazz.getDeclaredMethod(GET_I_TELEPHONY);
method.setAccessible(true);
} catch (ClassNotFoundException e) {
Log.e(TAG, e.getMessage(), e);
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
Log.e(TAG, e.getMessage(), e);
throw new RuntimeException(e);
}
}
@DebugLog
public boolean endCall() {
try {
|
// Path: app/src/main/java/com/jachness/blockcalls/stuff/ManagerUtil.java
// public class ManagerUtil {
// @DebugLog
// public static TelephonyManager getTelephonyManager(Context context) {
// return (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
// }
//
// @DebugLog
// public static AudioManager getAudioManager(Context context) {
// return (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
// }
//
// @DebugLog
// public static NotificationManager getNotificationManager(Context context) {
// return (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// }
// }
// Path: app/src/main/java/com/jachness/blockcalls/services/EndCallService.java
import hugo.weaving.DebugLog;
import android.content.Context;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.util.Log;
import com.android.internal.telephony.ITelephony;
import com.jachness.blockcalls.stuff.ManagerUtil;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.services;
/**
* Created by jachness on 13/11/2016.
*/
@SuppressWarnings("TryWithIdenticalCatches")
public class EndCallService {
private static final String GET_I_TELEPHONY = "getITelephony";
private static final String TAG = EndCallService.class.getSimpleName();
private final Context context;
private final Method method;
@SuppressWarnings("unchecked")
public EndCallService(Context context) {
this.context = context;
try {
Class clazz = Class.forName(TelephonyManager.class.getName());
method = clazz.getDeclaredMethod(GET_I_TELEPHONY);
method.setAccessible(true);
} catch (ClassNotFoundException e) {
Log.e(TAG, e.getMessage(), e);
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
Log.e(TAG, e.getMessage(), e);
throw new RuntimeException(e);
}
}
@DebugLog
public boolean endCall() {
try {
|
TelephonyManager tm = ManagerUtil.getTelephonyManager(context);
|
jachness/blockcalls
|
app/src/main/java/com/jachness/blockcalls/services/MasterChecker.java
|
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/PhoneNumberException.java
// public class PhoneNumberException extends Exception {
//
// public PhoneNumberException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/TooShortNumberException.java
// public class TooShortNumberException extends Exception {
// public static final int MINIMUM_LENGTH = 3;
//
// public TooShortNumberException(String message) {
// super(message);
// }
// }
|
import hugo.weaving.DebugLog;
import com.jachness.blockcalls.exceptions.PhoneNumberException;
import com.jachness.blockcalls.exceptions.TooShortNumberException;
|
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.services;
/**
* Created by jachness on 11/11/2016.
*/
public class MasterChecker {
private final IChecker[] checkers;
public MasterChecker(PrivateNumberChecker privateNumberChecker, QuickBlackListChecker
quickBlackListChecker, BlackListChecker blackListChecker, ContactChecker
contactChecker) {
this.checkers = new IChecker[]{privateNumberChecker, quickBlackListChecker,
blackListChecker, contactChecker};
}
@DebugLog
|
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/PhoneNumberException.java
// public class PhoneNumberException extends Exception {
//
// public PhoneNumberException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/TooShortNumberException.java
// public class TooShortNumberException extends Exception {
// public static final int MINIMUM_LENGTH = 3;
//
// public TooShortNumberException(String message) {
// super(message);
// }
// }
// Path: app/src/main/java/com/jachness/blockcalls/services/MasterChecker.java
import hugo.weaving.DebugLog;
import com.jachness.blockcalls.exceptions.PhoneNumberException;
import com.jachness.blockcalls.exceptions.TooShortNumberException;
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.services;
/**
* Created by jachness on 11/11/2016.
*/
public class MasterChecker {
private final IChecker[] checkers;
public MasterChecker(PrivateNumberChecker privateNumberChecker, QuickBlackListChecker
quickBlackListChecker, BlackListChecker blackListChecker, ContactChecker
contactChecker) {
this.checkers = new IChecker[]{privateNumberChecker, quickBlackListChecker,
blackListChecker, contactChecker};
}
@DebugLog
|
public boolean isBlockable(Call call) throws TooShortNumberException, PhoneNumberException {
|
jachness/blockcalls
|
app/src/main/java/com/jachness/blockcalls/services/MasterChecker.java
|
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/PhoneNumberException.java
// public class PhoneNumberException extends Exception {
//
// public PhoneNumberException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/TooShortNumberException.java
// public class TooShortNumberException extends Exception {
// public static final int MINIMUM_LENGTH = 3;
//
// public TooShortNumberException(String message) {
// super(message);
// }
// }
|
import hugo.weaving.DebugLog;
import com.jachness.blockcalls.exceptions.PhoneNumberException;
import com.jachness.blockcalls.exceptions.TooShortNumberException;
|
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.services;
/**
* Created by jachness on 11/11/2016.
*/
public class MasterChecker {
private final IChecker[] checkers;
public MasterChecker(PrivateNumberChecker privateNumberChecker, QuickBlackListChecker
quickBlackListChecker, BlackListChecker blackListChecker, ContactChecker
contactChecker) {
this.checkers = new IChecker[]{privateNumberChecker, quickBlackListChecker,
blackListChecker, contactChecker};
}
@DebugLog
|
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/PhoneNumberException.java
// public class PhoneNumberException extends Exception {
//
// public PhoneNumberException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/TooShortNumberException.java
// public class TooShortNumberException extends Exception {
// public static final int MINIMUM_LENGTH = 3;
//
// public TooShortNumberException(String message) {
// super(message);
// }
// }
// Path: app/src/main/java/com/jachness/blockcalls/services/MasterChecker.java
import hugo.weaving.DebugLog;
import com.jachness.blockcalls.exceptions.PhoneNumberException;
import com.jachness.blockcalls.exceptions.TooShortNumberException;
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.services;
/**
* Created by jachness on 11/11/2016.
*/
public class MasterChecker {
private final IChecker[] checkers;
public MasterChecker(PrivateNumberChecker privateNumberChecker, QuickBlackListChecker
quickBlackListChecker, BlackListChecker blackListChecker, ContactChecker
contactChecker) {
this.checkers = new IChecker[]{privateNumberChecker, quickBlackListChecker,
blackListChecker, contactChecker};
}
@DebugLog
|
public boolean isBlockable(Call call) throws TooShortNumberException, PhoneNumberException {
|
jachness/blockcalls
|
app/src/main/java/com/jachness/blockcalls/services/MatcherService.java
|
// Path: app/src/main/java/com/jachness/blockcalls/entities/BlackListNumberEntity.java
// public class BlackListNumberEntity {
// private Long uid;
// private String normalizedNumber = "";
// private String displayNumber = "";
// private String displayName = "";
// private boolean beginWith = false;
// private boolean enabled = true;
//
// public BlackListNumberEntity() {
// }
//
// public BlackListNumberEntity(Cursor cur) {
// for (String colName : cur.getColumnNames()) {
// int colIndex = cur.getColumnIndex(colName);
//
// switch (colName) {
// case BlackListTable.NORMALIZED_NUMBER:
// this.normalizedNumber = (cur.getString(colIndex));
// continue;
// case BlackListTable.DISPLAY_NUMBER:
// this.displayNumber = (cur.getString(colIndex));
// continue;
// case BlackListTable.BEGIN_WITH:
// this.beginWith = (cur.getInt(colIndex) != 0);
// continue;
// case BlackListTable.ENABLED:
// this.enabled = (cur.getInt(colIndex) != 0);
// continue;
// case BlackListTable.UID:
// this.uid = cur.getLong(colIndex);
// continue;
// case BlackListTable.DISPLAY_NAME:
// this.displayName = cur.getString(colIndex);
// }
// }
// }
//
// public boolean isBeginWith() {
// return beginWith;
// }
//
// public void setBeginWith(boolean beginWith) {
// this.beginWith = beginWith;
// }
//
// public String getNormalizedNumber() {
// return normalizedNumber;
// }
//
// public void setNormalizedNumber(String normalizedNumber) {
// this.normalizedNumber = normalizedNumber;
// }
//
// public String getDisplayNumber() {
// return displayNumber;
// }
//
// public void setDisplayNumber(String displayNumber) {
// this.displayNumber = displayNumber;
// }
//
// @SuppressWarnings("unused")
// public Long getUid() {
// return uid;
// }
//
// @SuppressWarnings("unused")
// public void setUid(Long uid) {
// this.uid = uid;
// }
//
// public boolean isEnabled() {
// return enabled;
// }
//
// public void setEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public void toContentValues(@NonNull ContentValues contentValue) {
// if (uid != null) contentValue.put(BlackListTable.UID, uid);
// contentValue.put(BlackListTable.BEGIN_WITH, beginWith ? "1" : "0");
// contentValue.put(BlackListTable.ENABLED, enabled ? "1" : "0");
// contentValue.put(BlackListTable.DISPLAY_NUMBER, displayNumber);
// contentValue.put(BlackListTable.DISPLAY_NAME, displayName);
// contentValue.put(BlackListTable.NORMALIZED_NUMBER, normalizedNumber);
// }
//
// public Uri getUniqueUri() {
// if (uid == null) {
// throw new IllegalStateException("uid is null");
// }
// return ContentUris.withAppendedId(BlackListTable.CONTENT_URI, uid);
// }
//
// @Override
// public String toString() {
// return "BlackListNumberEntity{" +
// "beginWith=" + beginWith +
// ", uid=" + uid +
// ", normalizedNumber='" + normalizedNumber + '\'' +
// ", displayNumber='" + displayNumber + '\'' +
// ", displayName='" + displayName + '\'' +
// ", enabled=" + enabled +
// '}';
// }
// }
|
import com.jachness.blockcalls.entities.BlackListNumberEntity;
import hugo.weaving.DebugLog;
import android.support.annotation.NonNull;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.services;
/**
* Created by jachness on 12/11/2016.
*/
public class MatcherService {
private static final int NO_MATCH = 0;
private static final int SOFT_MATCH = 1;
private static final int STRICT_MATCH = 2;
@DebugLog
@SuppressWarnings("SimplifiableIfStatement")
|
// Path: app/src/main/java/com/jachness/blockcalls/entities/BlackListNumberEntity.java
// public class BlackListNumberEntity {
// private Long uid;
// private String normalizedNumber = "";
// private String displayNumber = "";
// private String displayName = "";
// private boolean beginWith = false;
// private boolean enabled = true;
//
// public BlackListNumberEntity() {
// }
//
// public BlackListNumberEntity(Cursor cur) {
// for (String colName : cur.getColumnNames()) {
// int colIndex = cur.getColumnIndex(colName);
//
// switch (colName) {
// case BlackListTable.NORMALIZED_NUMBER:
// this.normalizedNumber = (cur.getString(colIndex));
// continue;
// case BlackListTable.DISPLAY_NUMBER:
// this.displayNumber = (cur.getString(colIndex));
// continue;
// case BlackListTable.BEGIN_WITH:
// this.beginWith = (cur.getInt(colIndex) != 0);
// continue;
// case BlackListTable.ENABLED:
// this.enabled = (cur.getInt(colIndex) != 0);
// continue;
// case BlackListTable.UID:
// this.uid = cur.getLong(colIndex);
// continue;
// case BlackListTable.DISPLAY_NAME:
// this.displayName = cur.getString(colIndex);
// }
// }
// }
//
// public boolean isBeginWith() {
// return beginWith;
// }
//
// public void setBeginWith(boolean beginWith) {
// this.beginWith = beginWith;
// }
//
// public String getNormalizedNumber() {
// return normalizedNumber;
// }
//
// public void setNormalizedNumber(String normalizedNumber) {
// this.normalizedNumber = normalizedNumber;
// }
//
// public String getDisplayNumber() {
// return displayNumber;
// }
//
// public void setDisplayNumber(String displayNumber) {
// this.displayNumber = displayNumber;
// }
//
// @SuppressWarnings("unused")
// public Long getUid() {
// return uid;
// }
//
// @SuppressWarnings("unused")
// public void setUid(Long uid) {
// this.uid = uid;
// }
//
// public boolean isEnabled() {
// return enabled;
// }
//
// public void setEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public void toContentValues(@NonNull ContentValues contentValue) {
// if (uid != null) contentValue.put(BlackListTable.UID, uid);
// contentValue.put(BlackListTable.BEGIN_WITH, beginWith ? "1" : "0");
// contentValue.put(BlackListTable.ENABLED, enabled ? "1" : "0");
// contentValue.put(BlackListTable.DISPLAY_NUMBER, displayNumber);
// contentValue.put(BlackListTable.DISPLAY_NAME, displayName);
// contentValue.put(BlackListTable.NORMALIZED_NUMBER, normalizedNumber);
// }
//
// public Uri getUniqueUri() {
// if (uid == null) {
// throw new IllegalStateException("uid is null");
// }
// return ContentUris.withAppendedId(BlackListTable.CONTENT_URI, uid);
// }
//
// @Override
// public String toString() {
// return "BlackListNumberEntity{" +
// "beginWith=" + beginWith +
// ", uid=" + uid +
// ", normalizedNumber='" + normalizedNumber + '\'' +
// ", displayNumber='" + displayNumber + '\'' +
// ", displayName='" + displayName + '\'' +
// ", enabled=" + enabled +
// '}';
// }
// }
// Path: app/src/main/java/com/jachness/blockcalls/services/MatcherService.java
import com.jachness.blockcalls.entities.BlackListNumberEntity;
import hugo.weaving.DebugLog;
import android.support.annotation.NonNull;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.services;
/**
* Created by jachness on 12/11/2016.
*/
public class MatcherService {
private static final int NO_MATCH = 0;
private static final int SOFT_MATCH = 1;
private static final int STRICT_MATCH = 2;
@DebugLog
@SuppressWarnings("SimplifiableIfStatement")
|
public boolean isNumberMatch(@NonNull Call call, BlackListNumberEntity blackListNumberEntity) {
|
jachness/blockcalls
|
app/src/androidTest/java/com/jachness/blockcalls/stuff/AppPreferencesTest.java
|
// Path: app/src/androidTest/java/com/jachness/blockcalls/AndroidTest.java
// public abstract class AndroidTest {
// private Context targetContext;
// private AllComponentTest component;
// private AppPreferences appPreferences;
// private Context context;
//
// protected void setUp() throws Exception {
// targetContext = InstrumentationRegistry.getTargetContext();
// context = InstrumentationRegistry.getContext();
// component = DaggerAllComponentTest.builder().blockModule(new BlockModule(targetContext))
// .appModule(new AppModule(targetContext))
// .dAOModule(new DAOModule(targetContext)).build();
// appPreferences = new AppPreferences(targetContext);
// }
//
// protected Context getTargetContext() {
// return targetContext;
// }
//
// protected AllComponentTest getComponent() {
// return component;
// }
//
// protected AppPreferences getAppPreferences() {
// return appPreferences;
// }
//
// public Context getContext() {
// return context;
// }
// }
|
import android.support.test.filters.SmallTest;
import android.support.test.runner.AndroidJUnit4;
import com.jachness.blockcalls.AndroidTest;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
|
package com.jachness.blockcalls.stuff;
@RunWith(AndroidJUnit4.class)
@SmallTest
|
// Path: app/src/androidTest/java/com/jachness/blockcalls/AndroidTest.java
// public abstract class AndroidTest {
// private Context targetContext;
// private AllComponentTest component;
// private AppPreferences appPreferences;
// private Context context;
//
// protected void setUp() throws Exception {
// targetContext = InstrumentationRegistry.getTargetContext();
// context = InstrumentationRegistry.getContext();
// component = DaggerAllComponentTest.builder().blockModule(new BlockModule(targetContext))
// .appModule(new AppModule(targetContext))
// .dAOModule(new DAOModule(targetContext)).build();
// appPreferences = new AppPreferences(targetContext);
// }
//
// protected Context getTargetContext() {
// return targetContext;
// }
//
// protected AllComponentTest getComponent() {
// return component;
// }
//
// protected AppPreferences getAppPreferences() {
// return appPreferences;
// }
//
// public Context getContext() {
// return context;
// }
// }
// Path: app/src/androidTest/java/com/jachness/blockcalls/stuff/AppPreferencesTest.java
import android.support.test.filters.SmallTest;
import android.support.test.runner.AndroidJUnit4;
import com.jachness.blockcalls.AndroidTest;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
package com.jachness.blockcalls.stuff;
@RunWith(AndroidJUnit4.class)
@SmallTest
|
public class AppPreferencesTest extends AndroidTest {
|
jachness/blockcalls
|
app/src/androidTest/java/com/jachness/blockcalls/services/MainWrapperTest.java
|
// Path: app/src/androidTest/java/com/jachness/blockcalls/AndroidTest.java
// public abstract class AndroidTest {
// private Context targetContext;
// private AllComponentTest component;
// private AppPreferences appPreferences;
// private Context context;
//
// protected void setUp() throws Exception {
// targetContext = InstrumentationRegistry.getTargetContext();
// context = InstrumentationRegistry.getContext();
// component = DaggerAllComponentTest.builder().blockModule(new BlockModule(targetContext))
// .appModule(new AppModule(targetContext))
// .dAOModule(new DAOModule(targetContext)).build();
// appPreferences = new AppPreferences(targetContext);
// }
//
// protected Context getTargetContext() {
// return targetContext;
// }
//
// protected AllComponentTest getComponent() {
// return component;
// }
//
// protected AppPreferences getAppPreferences() {
// return appPreferences;
// }
//
// public Context getContext() {
// return context;
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/PhoneNumberException.java
// public class PhoneNumberException extends Exception {
//
// public PhoneNumberException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/TooShortNumberException.java
// public class TooShortNumberException extends Exception {
// public static final int MINIMUM_LENGTH = 3;
//
// public TooShortNumberException(String message) {
// super(message);
// }
// }
|
import android.support.test.runner.AndroidJUnit4;
import android.util.Log;
import com.google.i18n.phonenumbers.NumberParseException;
import com.jachness.blockcalls.AndroidTest;
import com.jachness.blockcalls.exceptions.PhoneNumberException;
import com.jachness.blockcalls.exceptions.TooShortNumberException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
|
package com.jachness.blockcalls.services;
/**
* Created by jachness on 13/11/2016.
*/
@RunWith(AndroidJUnit4.class)
public class MainWrapperTest extends AndroidTest {
private static final String TAG = MainWrapperTest.class.getSimpleName();
@Before
public void setUp() throws Exception {
super.setUp();
getAppPreferences().deleteAll();
}
@Test
|
// Path: app/src/androidTest/java/com/jachness/blockcalls/AndroidTest.java
// public abstract class AndroidTest {
// private Context targetContext;
// private AllComponentTest component;
// private AppPreferences appPreferences;
// private Context context;
//
// protected void setUp() throws Exception {
// targetContext = InstrumentationRegistry.getTargetContext();
// context = InstrumentationRegistry.getContext();
// component = DaggerAllComponentTest.builder().blockModule(new BlockModule(targetContext))
// .appModule(new AppModule(targetContext))
// .dAOModule(new DAOModule(targetContext)).build();
// appPreferences = new AppPreferences(targetContext);
// }
//
// protected Context getTargetContext() {
// return targetContext;
// }
//
// protected AllComponentTest getComponent() {
// return component;
// }
//
// protected AppPreferences getAppPreferences() {
// return appPreferences;
// }
//
// public Context getContext() {
// return context;
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/PhoneNumberException.java
// public class PhoneNumberException extends Exception {
//
// public PhoneNumberException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/TooShortNumberException.java
// public class TooShortNumberException extends Exception {
// public static final int MINIMUM_LENGTH = 3;
//
// public TooShortNumberException(String message) {
// super(message);
// }
// }
// Path: app/src/androidTest/java/com/jachness/blockcalls/services/MainWrapperTest.java
import android.support.test.runner.AndroidJUnit4;
import android.util.Log;
import com.google.i18n.phonenumbers.NumberParseException;
import com.jachness.blockcalls.AndroidTest;
import com.jachness.blockcalls.exceptions.PhoneNumberException;
import com.jachness.blockcalls.exceptions.TooShortNumberException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
package com.jachness.blockcalls.services;
/**
* Created by jachness on 13/11/2016.
*/
@RunWith(AndroidJUnit4.class)
public class MainWrapperTest extends AndroidTest {
private static final String TAG = MainWrapperTest.class.getSimpleName();
@Before
public void setUp() throws Exception {
super.setUp();
getAppPreferences().deleteAll();
}
@Test
|
public void testCheckAndBlock() throws NumberParseException, PhoneNumberException,
|
jachness/blockcalls
|
app/src/androidTest/java/com/jachness/blockcalls/services/MainWrapperTest.java
|
// Path: app/src/androidTest/java/com/jachness/blockcalls/AndroidTest.java
// public abstract class AndroidTest {
// private Context targetContext;
// private AllComponentTest component;
// private AppPreferences appPreferences;
// private Context context;
//
// protected void setUp() throws Exception {
// targetContext = InstrumentationRegistry.getTargetContext();
// context = InstrumentationRegistry.getContext();
// component = DaggerAllComponentTest.builder().blockModule(new BlockModule(targetContext))
// .appModule(new AppModule(targetContext))
// .dAOModule(new DAOModule(targetContext)).build();
// appPreferences = new AppPreferences(targetContext);
// }
//
// protected Context getTargetContext() {
// return targetContext;
// }
//
// protected AllComponentTest getComponent() {
// return component;
// }
//
// protected AppPreferences getAppPreferences() {
// return appPreferences;
// }
//
// public Context getContext() {
// return context;
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/PhoneNumberException.java
// public class PhoneNumberException extends Exception {
//
// public PhoneNumberException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/TooShortNumberException.java
// public class TooShortNumberException extends Exception {
// public static final int MINIMUM_LENGTH = 3;
//
// public TooShortNumberException(String message) {
// super(message);
// }
// }
|
import android.support.test.runner.AndroidJUnit4;
import android.util.Log;
import com.google.i18n.phonenumbers.NumberParseException;
import com.jachness.blockcalls.AndroidTest;
import com.jachness.blockcalls.exceptions.PhoneNumberException;
import com.jachness.blockcalls.exceptions.TooShortNumberException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
|
package com.jachness.blockcalls.services;
/**
* Created by jachness on 13/11/2016.
*/
@RunWith(AndroidJUnit4.class)
public class MainWrapperTest extends AndroidTest {
private static final String TAG = MainWrapperTest.class.getSimpleName();
@Before
public void setUp() throws Exception {
super.setUp();
getAppPreferences().deleteAll();
}
@Test
public void testCheckAndBlock() throws NumberParseException, PhoneNumberException,
|
// Path: app/src/androidTest/java/com/jachness/blockcalls/AndroidTest.java
// public abstract class AndroidTest {
// private Context targetContext;
// private AllComponentTest component;
// private AppPreferences appPreferences;
// private Context context;
//
// protected void setUp() throws Exception {
// targetContext = InstrumentationRegistry.getTargetContext();
// context = InstrumentationRegistry.getContext();
// component = DaggerAllComponentTest.builder().blockModule(new BlockModule(targetContext))
// .appModule(new AppModule(targetContext))
// .dAOModule(new DAOModule(targetContext)).build();
// appPreferences = new AppPreferences(targetContext);
// }
//
// protected Context getTargetContext() {
// return targetContext;
// }
//
// protected AllComponentTest getComponent() {
// return component;
// }
//
// protected AppPreferences getAppPreferences() {
// return appPreferences;
// }
//
// public Context getContext() {
// return context;
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/PhoneNumberException.java
// public class PhoneNumberException extends Exception {
//
// public PhoneNumberException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/TooShortNumberException.java
// public class TooShortNumberException extends Exception {
// public static final int MINIMUM_LENGTH = 3;
//
// public TooShortNumberException(String message) {
// super(message);
// }
// }
// Path: app/src/androidTest/java/com/jachness/blockcalls/services/MainWrapperTest.java
import android.support.test.runner.AndroidJUnit4;
import android.util.Log;
import com.google.i18n.phonenumbers.NumberParseException;
import com.jachness.blockcalls.AndroidTest;
import com.jachness.blockcalls.exceptions.PhoneNumberException;
import com.jachness.blockcalls.exceptions.TooShortNumberException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
package com.jachness.blockcalls.services;
/**
* Created by jachness on 13/11/2016.
*/
@RunWith(AndroidJUnit4.class)
public class MainWrapperTest extends AndroidTest {
private static final String TAG = MainWrapperTest.class.getSimpleName();
@Before
public void setUp() throws Exception {
super.setUp();
getAppPreferences().deleteAll();
}
@Test
public void testCheckAndBlock() throws NumberParseException, PhoneNumberException,
|
TooShortNumberException {
|
jachness/blockcalls
|
app/src/main/java/com/jachness/blockcalls/services/Call.java
|
// Path: app/src/main/java/com/jachness/blockcalls/stuff/BlockOrigin.java
// public enum BlockOrigin {
// PRIVATE, CONTACTS, BLACK_LIST
// }
|
import android.text.TextUtils;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import com.jachness.blockcalls.stuff.BlockOrigin;
import java.util.HashMap;
import java.util.Map;
|
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.services;
/**
* Created by jachness on 6/11/2016.
*/
public class Call {
public static final String PRIVATE_NUMBER = "private";
private final Map<String, String> extraData = new HashMap<>();
private String number;
|
// Path: app/src/main/java/com/jachness/blockcalls/stuff/BlockOrigin.java
// public enum BlockOrigin {
// PRIVATE, CONTACTS, BLACK_LIST
// }
// Path: app/src/main/java/com/jachness/blockcalls/services/Call.java
import android.text.TextUtils;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import com.jachness.blockcalls.stuff.BlockOrigin;
import java.util.HashMap;
import java.util.Map;
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.services;
/**
* Created by jachness on 6/11/2016.
*/
public class Call {
public static final String PRIVATE_NUMBER = "private";
private final Map<String, String> extraData = new HashMap<>();
private String number;
|
private BlockOrigin blockOrigin;
|
jachness/blockcalls
|
app/src/androidTest/java/com/jachness/blockcalls/services/ImportExportWrapperTest.java
|
// Path: app/src/androidTest/java/com/jachness/blockcalls/AndroidTest.java
// public abstract class AndroidTest {
// private Context targetContext;
// private AllComponentTest component;
// private AppPreferences appPreferences;
// private Context context;
//
// protected void setUp() throws Exception {
// targetContext = InstrumentationRegistry.getTargetContext();
// context = InstrumentationRegistry.getContext();
// component = DaggerAllComponentTest.builder().blockModule(new BlockModule(targetContext))
// .appModule(new AppModule(targetContext))
// .dAOModule(new DAOModule(targetContext)).build();
// appPreferences = new AppPreferences(targetContext);
// }
//
// protected Context getTargetContext() {
// return targetContext;
// }
//
// protected AllComponentTest getComponent() {
// return component;
// }
//
// protected AppPreferences getAppPreferences() {
// return appPreferences;
// }
//
// public Context getContext() {
// return context;
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/FileException.java
// @SuppressWarnings("SameParameterValue")
// public class FileException extends Exception {
// public static final int MEDIA_ERROR = 0;
// public static final int READ_FILE_ERROR = 1;
// public static final int WRITE_FILE_ERROR = 2;
// private final int errorCode;
//
// public FileException(int errorCode) {
// this.errorCode = errorCode;
// }
//
// public FileException(int errorCode, String message) {
// super(message);
// this.errorCode = errorCode;
// }
//
// public FileException(int errorCode, String message, Throwable cause) {
// super(message, cause);
// this.errorCode = errorCode;
// }
//
// public int getErrorCode() {
// return errorCode;
// }
// }
|
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import android.support.test.runner.AndroidJUnit4;
import com.jachness.blockcalls.AndroidTest;
import com.jachness.blockcalls.exceptions.FileException;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
|
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.services;
/**
* Created by jachness on 13/11/2016.
*/
@RunWith(AndroidJUnit4.class)
public class ImportExportWrapperTest extends AndroidTest {
@Before
public void setUp() throws Exception {
super.setUp();
}
@Test
public void importBlackListTest() {
BlackListWrapper blackListWrapper = mock(BlackListWrapper.class);
when(blackListWrapper.addNumberToBlackList(Matchers.any(String.class), Matchers.any
(String.class), Matchers.any(Boolean.class))).thenReturn(1);
ImportExportWrapper wrapper = new ImportExportWrapper(getTargetContext(), blackListWrapper);
try {
wrapper.importBlackList(null);
Assert.fail("Should have had throw FileException exception");
|
// Path: app/src/androidTest/java/com/jachness/blockcalls/AndroidTest.java
// public abstract class AndroidTest {
// private Context targetContext;
// private AllComponentTest component;
// private AppPreferences appPreferences;
// private Context context;
//
// protected void setUp() throws Exception {
// targetContext = InstrumentationRegistry.getTargetContext();
// context = InstrumentationRegistry.getContext();
// component = DaggerAllComponentTest.builder().blockModule(new BlockModule(targetContext))
// .appModule(new AppModule(targetContext))
// .dAOModule(new DAOModule(targetContext)).build();
// appPreferences = new AppPreferences(targetContext);
// }
//
// protected Context getTargetContext() {
// return targetContext;
// }
//
// protected AllComponentTest getComponent() {
// return component;
// }
//
// protected AppPreferences getAppPreferences() {
// return appPreferences;
// }
//
// public Context getContext() {
// return context;
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/FileException.java
// @SuppressWarnings("SameParameterValue")
// public class FileException extends Exception {
// public static final int MEDIA_ERROR = 0;
// public static final int READ_FILE_ERROR = 1;
// public static final int WRITE_FILE_ERROR = 2;
// private final int errorCode;
//
// public FileException(int errorCode) {
// this.errorCode = errorCode;
// }
//
// public FileException(int errorCode, String message) {
// super(message);
// this.errorCode = errorCode;
// }
//
// public FileException(int errorCode, String message, Throwable cause) {
// super(message, cause);
// this.errorCode = errorCode;
// }
//
// public int getErrorCode() {
// return errorCode;
// }
// }
// Path: app/src/androidTest/java/com/jachness/blockcalls/services/ImportExportWrapperTest.java
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import android.support.test.runner.AndroidJUnit4;
import com.jachness.blockcalls.AndroidTest;
import com.jachness.blockcalls.exceptions.FileException;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.services;
/**
* Created by jachness on 13/11/2016.
*/
@RunWith(AndroidJUnit4.class)
public class ImportExportWrapperTest extends AndroidTest {
@Before
public void setUp() throws Exception {
super.setUp();
}
@Test
public void importBlackListTest() {
BlackListWrapper blackListWrapper = mock(BlackListWrapper.class);
when(blackListWrapper.addNumberToBlackList(Matchers.any(String.class), Matchers.any
(String.class), Matchers.any(Boolean.class))).thenReturn(1);
ImportExportWrapper wrapper = new ImportExportWrapper(getTargetContext(), blackListWrapper);
try {
wrapper.importBlackList(null);
Assert.fail("Should have had throw FileException exception");
|
} catch (FileException e) {
|
jachness/blockcalls
|
app/src/androidTest/java/com/jachness/blockcalls/services/MatcherServiceTest.java
|
// Path: app/src/androidTest/java/com/jachness/blockcalls/AndroidTest.java
// public abstract class AndroidTest {
// private Context targetContext;
// private AllComponentTest component;
// private AppPreferences appPreferences;
// private Context context;
//
// protected void setUp() throws Exception {
// targetContext = InstrumentationRegistry.getTargetContext();
// context = InstrumentationRegistry.getContext();
// component = DaggerAllComponentTest.builder().blockModule(new BlockModule(targetContext))
// .appModule(new AppModule(targetContext))
// .dAOModule(new DAOModule(targetContext)).build();
// appPreferences = new AppPreferences(targetContext);
// }
//
// protected Context getTargetContext() {
// return targetContext;
// }
//
// protected AllComponentTest getComponent() {
// return component;
// }
//
// protected AppPreferences getAppPreferences() {
// return appPreferences;
// }
//
// public Context getContext() {
// return context;
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/entities/BlackListNumberEntity.java
// public class BlackListNumberEntity {
// private Long uid;
// private String normalizedNumber = "";
// private String displayNumber = "";
// private String displayName = "";
// private boolean beginWith = false;
// private boolean enabled = true;
//
// public BlackListNumberEntity() {
// }
//
// public BlackListNumberEntity(Cursor cur) {
// for (String colName : cur.getColumnNames()) {
// int colIndex = cur.getColumnIndex(colName);
//
// switch (colName) {
// case BlackListTable.NORMALIZED_NUMBER:
// this.normalizedNumber = (cur.getString(colIndex));
// continue;
// case BlackListTable.DISPLAY_NUMBER:
// this.displayNumber = (cur.getString(colIndex));
// continue;
// case BlackListTable.BEGIN_WITH:
// this.beginWith = (cur.getInt(colIndex) != 0);
// continue;
// case BlackListTable.ENABLED:
// this.enabled = (cur.getInt(colIndex) != 0);
// continue;
// case BlackListTable.UID:
// this.uid = cur.getLong(colIndex);
// continue;
// case BlackListTable.DISPLAY_NAME:
// this.displayName = cur.getString(colIndex);
// }
// }
// }
//
// public boolean isBeginWith() {
// return beginWith;
// }
//
// public void setBeginWith(boolean beginWith) {
// this.beginWith = beginWith;
// }
//
// public String getNormalizedNumber() {
// return normalizedNumber;
// }
//
// public void setNormalizedNumber(String normalizedNumber) {
// this.normalizedNumber = normalizedNumber;
// }
//
// public String getDisplayNumber() {
// return displayNumber;
// }
//
// public void setDisplayNumber(String displayNumber) {
// this.displayNumber = displayNumber;
// }
//
// @SuppressWarnings("unused")
// public Long getUid() {
// return uid;
// }
//
// @SuppressWarnings("unused")
// public void setUid(Long uid) {
// this.uid = uid;
// }
//
// public boolean isEnabled() {
// return enabled;
// }
//
// public void setEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public void toContentValues(@NonNull ContentValues contentValue) {
// if (uid != null) contentValue.put(BlackListTable.UID, uid);
// contentValue.put(BlackListTable.BEGIN_WITH, beginWith ? "1" : "0");
// contentValue.put(BlackListTable.ENABLED, enabled ? "1" : "0");
// contentValue.put(BlackListTable.DISPLAY_NUMBER, displayNumber);
// contentValue.put(BlackListTable.DISPLAY_NAME, displayName);
// contentValue.put(BlackListTable.NORMALIZED_NUMBER, normalizedNumber);
// }
//
// public Uri getUniqueUri() {
// if (uid == null) {
// throw new IllegalStateException("uid is null");
// }
// return ContentUris.withAppendedId(BlackListTable.CONTENT_URI, uid);
// }
//
// @Override
// public String toString() {
// return "BlackListNumberEntity{" +
// "beginWith=" + beginWith +
// ", uid=" + uid +
// ", normalizedNumber='" + normalizedNumber + '\'' +
// ", displayNumber='" + displayNumber + '\'' +
// ", displayName='" + displayName + '\'' +
// ", enabled=" + enabled +
// '}';
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/PhoneNumberException.java
// public class PhoneNumberException extends Exception {
//
// public PhoneNumberException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/TooShortNumberException.java
// public class TooShortNumberException extends Exception {
// public static final int MINIMUM_LENGTH = 3;
//
// public TooShortNumberException(String message) {
// super(message);
// }
// }
|
import android.annotation.SuppressLint;
import android.preference.PreferenceManager;
import android.support.test.runner.AndroidJUnit4;
import android.util.Log;
import com.jachness.blockcalls.AndroidTest;
import com.jachness.blockcalls.entities.BlackListNumberEntity;
import com.jachness.blockcalls.exceptions.PhoneNumberException;
import com.jachness.blockcalls.exceptions.TooShortNumberException;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
|
package com.jachness.blockcalls.services;
/**
* Created by jachness on 12/11/2016.
*/
@SuppressWarnings({"TryWithIdenticalCatches", "ConstantConditions"})
@RunWith(AndroidJUnit4.class)
|
// Path: app/src/androidTest/java/com/jachness/blockcalls/AndroidTest.java
// public abstract class AndroidTest {
// private Context targetContext;
// private AllComponentTest component;
// private AppPreferences appPreferences;
// private Context context;
//
// protected void setUp() throws Exception {
// targetContext = InstrumentationRegistry.getTargetContext();
// context = InstrumentationRegistry.getContext();
// component = DaggerAllComponentTest.builder().blockModule(new BlockModule(targetContext))
// .appModule(new AppModule(targetContext))
// .dAOModule(new DAOModule(targetContext)).build();
// appPreferences = new AppPreferences(targetContext);
// }
//
// protected Context getTargetContext() {
// return targetContext;
// }
//
// protected AllComponentTest getComponent() {
// return component;
// }
//
// protected AppPreferences getAppPreferences() {
// return appPreferences;
// }
//
// public Context getContext() {
// return context;
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/entities/BlackListNumberEntity.java
// public class BlackListNumberEntity {
// private Long uid;
// private String normalizedNumber = "";
// private String displayNumber = "";
// private String displayName = "";
// private boolean beginWith = false;
// private boolean enabled = true;
//
// public BlackListNumberEntity() {
// }
//
// public BlackListNumberEntity(Cursor cur) {
// for (String colName : cur.getColumnNames()) {
// int colIndex = cur.getColumnIndex(colName);
//
// switch (colName) {
// case BlackListTable.NORMALIZED_NUMBER:
// this.normalizedNumber = (cur.getString(colIndex));
// continue;
// case BlackListTable.DISPLAY_NUMBER:
// this.displayNumber = (cur.getString(colIndex));
// continue;
// case BlackListTable.BEGIN_WITH:
// this.beginWith = (cur.getInt(colIndex) != 0);
// continue;
// case BlackListTable.ENABLED:
// this.enabled = (cur.getInt(colIndex) != 0);
// continue;
// case BlackListTable.UID:
// this.uid = cur.getLong(colIndex);
// continue;
// case BlackListTable.DISPLAY_NAME:
// this.displayName = cur.getString(colIndex);
// }
// }
// }
//
// public boolean isBeginWith() {
// return beginWith;
// }
//
// public void setBeginWith(boolean beginWith) {
// this.beginWith = beginWith;
// }
//
// public String getNormalizedNumber() {
// return normalizedNumber;
// }
//
// public void setNormalizedNumber(String normalizedNumber) {
// this.normalizedNumber = normalizedNumber;
// }
//
// public String getDisplayNumber() {
// return displayNumber;
// }
//
// public void setDisplayNumber(String displayNumber) {
// this.displayNumber = displayNumber;
// }
//
// @SuppressWarnings("unused")
// public Long getUid() {
// return uid;
// }
//
// @SuppressWarnings("unused")
// public void setUid(Long uid) {
// this.uid = uid;
// }
//
// public boolean isEnabled() {
// return enabled;
// }
//
// public void setEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public void toContentValues(@NonNull ContentValues contentValue) {
// if (uid != null) contentValue.put(BlackListTable.UID, uid);
// contentValue.put(BlackListTable.BEGIN_WITH, beginWith ? "1" : "0");
// contentValue.put(BlackListTable.ENABLED, enabled ? "1" : "0");
// contentValue.put(BlackListTable.DISPLAY_NUMBER, displayNumber);
// contentValue.put(BlackListTable.DISPLAY_NAME, displayName);
// contentValue.put(BlackListTable.NORMALIZED_NUMBER, normalizedNumber);
// }
//
// public Uri getUniqueUri() {
// if (uid == null) {
// throw new IllegalStateException("uid is null");
// }
// return ContentUris.withAppendedId(BlackListTable.CONTENT_URI, uid);
// }
//
// @Override
// public String toString() {
// return "BlackListNumberEntity{" +
// "beginWith=" + beginWith +
// ", uid=" + uid +
// ", normalizedNumber='" + normalizedNumber + '\'' +
// ", displayNumber='" + displayNumber + '\'' +
// ", displayName='" + displayName + '\'' +
// ", enabled=" + enabled +
// '}';
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/PhoneNumberException.java
// public class PhoneNumberException extends Exception {
//
// public PhoneNumberException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/exceptions/TooShortNumberException.java
// public class TooShortNumberException extends Exception {
// public static final int MINIMUM_LENGTH = 3;
//
// public TooShortNumberException(String message) {
// super(message);
// }
// }
// Path: app/src/androidTest/java/com/jachness/blockcalls/services/MatcherServiceTest.java
import android.annotation.SuppressLint;
import android.preference.PreferenceManager;
import android.support.test.runner.AndroidJUnit4;
import android.util.Log;
import com.jachness.blockcalls.AndroidTest;
import com.jachness.blockcalls.entities.BlackListNumberEntity;
import com.jachness.blockcalls.exceptions.PhoneNumberException;
import com.jachness.blockcalls.exceptions.TooShortNumberException;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
package com.jachness.blockcalls.services;
/**
* Created by jachness on 12/11/2016.
*/
@SuppressWarnings({"TryWithIdenticalCatches", "ConstantConditions"})
@RunWith(AndroidJUnit4.class)
|
public final class MatcherServiceTest extends AndroidTest {
|
jachness/blockcalls
|
app/src/main/java/com/jachness/blockcalls/entities/BlackListNumberEntity.java
|
// Path: app/src/main/java/com/jachness/blockcalls/db/BlackListTable.java
// public class BlackListTable {
// public static final String UID = "_id";
// public static final String NORMALIZED_NUMBER = "normalized_number";
// public static final String DISPLAY_NUMBER = "display_number";
// public static final String DISPLAY_NAME = "display_name";
// public static final String BEGIN_WITH = "begin_with";
// public static final String ENABLED = "enabled";
//
// public static final String TABLE = "black_list";
// public static final String RELATIVE_PATH = "blacklist";
//
// public static final Uri CONTENT_URI = Uri.parse("content://" + BlackListProvider.AUTHORITY +
// "/" + RELATIVE_PATH);
//
// public static final String CONTENT_TYPE = "vnd.android.cursor.dir/" + RELATIVE_PATH;
// public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/" + RELATIVE_PATH;
//
// public static final int SSID_PATH_POSITION = 1;
// public static final String BEGIN_WITH_SYMBOL = "?";
// }
|
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.annotation.NonNull;
import com.jachness.blockcalls.db.BlackListTable;
|
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.entities;
/**
* Created by jachness on 26/9/2016.
*/
public class BlackListNumberEntity {
private Long uid;
private String normalizedNumber = "";
private String displayNumber = "";
private String displayName = "";
private boolean beginWith = false;
private boolean enabled = true;
public BlackListNumberEntity() {
}
public BlackListNumberEntity(Cursor cur) {
for (String colName : cur.getColumnNames()) {
int colIndex = cur.getColumnIndex(colName);
switch (colName) {
|
// Path: app/src/main/java/com/jachness/blockcalls/db/BlackListTable.java
// public class BlackListTable {
// public static final String UID = "_id";
// public static final String NORMALIZED_NUMBER = "normalized_number";
// public static final String DISPLAY_NUMBER = "display_number";
// public static final String DISPLAY_NAME = "display_name";
// public static final String BEGIN_WITH = "begin_with";
// public static final String ENABLED = "enabled";
//
// public static final String TABLE = "black_list";
// public static final String RELATIVE_PATH = "blacklist";
//
// public static final Uri CONTENT_URI = Uri.parse("content://" + BlackListProvider.AUTHORITY +
// "/" + RELATIVE_PATH);
//
// public static final String CONTENT_TYPE = "vnd.android.cursor.dir/" + RELATIVE_PATH;
// public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/" + RELATIVE_PATH;
//
// public static final int SSID_PATH_POSITION = 1;
// public static final String BEGIN_WITH_SYMBOL = "?";
// }
// Path: app/src/main/java/com/jachness/blockcalls/entities/BlackListNumberEntity.java
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.annotation.NonNull;
import com.jachness.blockcalls.db.BlackListTable;
/*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Block Calls is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.entities;
/**
* Created by jachness on 26/9/2016.
*/
public class BlackListNumberEntity {
private Long uid;
private String normalizedNumber = "";
private String displayNumber = "";
private String displayName = "";
private boolean beginWith = false;
private boolean enabled = true;
public BlackListNumberEntity() {
}
public BlackListNumberEntity(Cursor cur) {
for (String colName : cur.getColumnNames()) {
int colIndex = cur.getColumnIndex(colName);
switch (colName) {
|
case BlackListTable.NORMALIZED_NUMBER:
|
jachness/blockcalls
|
app/src/androidTest/java/com/jachness/blockcalls/db/LogProviderTest.java
|
// Path: app/src/main/java/com/jachness/blockcalls/entities/LogEntity.java
// public class LogEntity {
// private Long uid;
// private String callerID;
// private String displayNumber;
// private String displayName;
// private long time;
// private BlockOrigin blockOrigin;
//
// public LogEntity() {
// }
//
// public LogEntity(Cursor cur) {
// for (String colName : cur.getColumnNames()) {
// int colIndex = cur.getColumnIndexOrThrow(colName);
// switch (colName) {
// case LogTable.CALLER_ID:
// this.setCallerID(cur.getString(colIndex));
// break;
// case LogTable.DISPLAY_NUMBER:
// this.setDisplayNumber(cur.getString(colIndex));
// break;
// case LogTable.DATE:
// this.setTime(cur.getLong(colIndex));
// break;
// case LogTable.BLOCK_ORIGIN:
// this.setBlockOrigin(BlockOrigin.valueOf(cur.getString(colIndex)));
// break;
// case LogTable.UID:
// this.setUid(cur.getLong(colIndex));
// break;
// case LogTable.DISPLAY_NAME:
// this.setDisplayName(cur.getString(colIndex));
// break;
// }
// }
// }
//
// public String getCallerID() {
// return callerID;
// }
//
// public void setCallerID(String callerID) {
// this.callerID = callerID;
// }
//
// public long getTime() {
// return time;
// }
//
// public void setTime(long time) {
// this.time = time;
// }
//
// public String getDisplayNumber() {
// return displayNumber;
// }
//
// public void setDisplayNumber(String displayNumber) {
// this.displayNumber = displayNumber;
// }
//
// public BlockOrigin getBlockOrigin() {
// return blockOrigin;
// }
//
// public void setBlockOrigin(BlockOrigin blockOrigin) {
// this.blockOrigin = blockOrigin;
// }
//
// @SuppressWarnings("unused")
// public Long getUid() {
// return uid;
// }
//
// @SuppressWarnings("WeakerAccess")
// public void setUid(Long uid) {
// this.uid = uid;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public void toContentValues(@NonNull ContentValues contentValue) {
// if (uid != null) contentValue.put(LogTable.UID, uid);
// contentValue.put(LogTable.CALLER_ID, callerID);
// contentValue.put(LogTable.DISPLAY_NUMBER, displayNumber);
// contentValue.put(LogTable.DISPLAY_NAME, displayName);
// contentValue.put(LogTable.DATE, Long.toString(time));
// contentValue.put(LogTable.BLOCK_ORIGIN, blockOrigin.toString());
// }
//
// @Override
// public String toString() {
// return "LogEntity{" +
// "blockOrigin=" + blockOrigin +
// ", uid=" + uid +
// ", callerID='" + callerID + '\'' +
// ", displayNumber='" + displayNumber + '\'' +
// ", displayName='" + displayName + '\'' +
// ", time=" + time +
// '}';
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/stuff/BlockOrigin.java
// public enum BlockOrigin {
// PRIVATE, CONTACTS, BLACK_LIST
// }
|
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.test.ProviderTestCase2;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import com.jachness.blockcalls.entities.LogEntity;
import com.jachness.blockcalls.stuff.BlockOrigin;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Date;
import java.util.Random;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
|
package com.jachness.blockcalls.db;
@SuppressWarnings("ConstantConditions")
@RunWith(AndroidJUnit4.class)
//@SmallTest
public class LogProviderTest extends ProviderTestCase2<LogProvider> {
private PhoneNumberUtil phoneUtil;
public LogProviderTest() {
super(LogProvider.class, LogProvider.AUTHORITY);
}
@Override
// @Before
public void setUp() throws Exception {
setContext(InstrumentationRegistry.getTargetContext());
phoneUtil = PhoneNumberUtil.getInstance();
super.setUp();
}
private PhoneNumber getRandomPhoneNumber() throws NumberParseException {
int min = 10000000;
int max = 99999999;
Random r = new Random();
int num = r.nextInt(max - min + 1) + min;
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
return phoneUtil.parseAndKeepRawInput(Integer.toString(num), "AR");
}
@Test
public void test1() throws NumberParseException {
PhoneNumber number = getRandomPhoneNumber();
String numberE164 = phoneUtil.format(number, PhoneNumberUtil.PhoneNumberFormat.E164);
String numberInt = phoneUtil.format(number, PhoneNumberUtil.PhoneNumberFormat
.INTERNATIONAL);
|
// Path: app/src/main/java/com/jachness/blockcalls/entities/LogEntity.java
// public class LogEntity {
// private Long uid;
// private String callerID;
// private String displayNumber;
// private String displayName;
// private long time;
// private BlockOrigin blockOrigin;
//
// public LogEntity() {
// }
//
// public LogEntity(Cursor cur) {
// for (String colName : cur.getColumnNames()) {
// int colIndex = cur.getColumnIndexOrThrow(colName);
// switch (colName) {
// case LogTable.CALLER_ID:
// this.setCallerID(cur.getString(colIndex));
// break;
// case LogTable.DISPLAY_NUMBER:
// this.setDisplayNumber(cur.getString(colIndex));
// break;
// case LogTable.DATE:
// this.setTime(cur.getLong(colIndex));
// break;
// case LogTable.BLOCK_ORIGIN:
// this.setBlockOrigin(BlockOrigin.valueOf(cur.getString(colIndex)));
// break;
// case LogTable.UID:
// this.setUid(cur.getLong(colIndex));
// break;
// case LogTable.DISPLAY_NAME:
// this.setDisplayName(cur.getString(colIndex));
// break;
// }
// }
// }
//
// public String getCallerID() {
// return callerID;
// }
//
// public void setCallerID(String callerID) {
// this.callerID = callerID;
// }
//
// public long getTime() {
// return time;
// }
//
// public void setTime(long time) {
// this.time = time;
// }
//
// public String getDisplayNumber() {
// return displayNumber;
// }
//
// public void setDisplayNumber(String displayNumber) {
// this.displayNumber = displayNumber;
// }
//
// public BlockOrigin getBlockOrigin() {
// return blockOrigin;
// }
//
// public void setBlockOrigin(BlockOrigin blockOrigin) {
// this.blockOrigin = blockOrigin;
// }
//
// @SuppressWarnings("unused")
// public Long getUid() {
// return uid;
// }
//
// @SuppressWarnings("WeakerAccess")
// public void setUid(Long uid) {
// this.uid = uid;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public void toContentValues(@NonNull ContentValues contentValue) {
// if (uid != null) contentValue.put(LogTable.UID, uid);
// contentValue.put(LogTable.CALLER_ID, callerID);
// contentValue.put(LogTable.DISPLAY_NUMBER, displayNumber);
// contentValue.put(LogTable.DISPLAY_NAME, displayName);
// contentValue.put(LogTable.DATE, Long.toString(time));
// contentValue.put(LogTable.BLOCK_ORIGIN, blockOrigin.toString());
// }
//
// @Override
// public String toString() {
// return "LogEntity{" +
// "blockOrigin=" + blockOrigin +
// ", uid=" + uid +
// ", callerID='" + callerID + '\'' +
// ", displayNumber='" + displayNumber + '\'' +
// ", displayName='" + displayName + '\'' +
// ", time=" + time +
// '}';
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/stuff/BlockOrigin.java
// public enum BlockOrigin {
// PRIVATE, CONTACTS, BLACK_LIST
// }
// Path: app/src/androidTest/java/com/jachness/blockcalls/db/LogProviderTest.java
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.test.ProviderTestCase2;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import com.jachness.blockcalls.entities.LogEntity;
import com.jachness.blockcalls.stuff.BlockOrigin;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Date;
import java.util.Random;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
package com.jachness.blockcalls.db;
@SuppressWarnings("ConstantConditions")
@RunWith(AndroidJUnit4.class)
//@SmallTest
public class LogProviderTest extends ProviderTestCase2<LogProvider> {
private PhoneNumberUtil phoneUtil;
public LogProviderTest() {
super(LogProvider.class, LogProvider.AUTHORITY);
}
@Override
// @Before
public void setUp() throws Exception {
setContext(InstrumentationRegistry.getTargetContext());
phoneUtil = PhoneNumberUtil.getInstance();
super.setUp();
}
private PhoneNumber getRandomPhoneNumber() throws NumberParseException {
int min = 10000000;
int max = 99999999;
Random r = new Random();
int num = r.nextInt(max - min + 1) + min;
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
return phoneUtil.parseAndKeepRawInput(Integer.toString(num), "AR");
}
@Test
public void test1() throws NumberParseException {
PhoneNumber number = getRandomPhoneNumber();
String numberE164 = phoneUtil.format(number, PhoneNumberUtil.PhoneNumberFormat.E164);
String numberInt = phoneUtil.format(number, PhoneNumberUtil.PhoneNumberFormat
.INTERNATIONAL);
|
LogEntity logEntity = new LogEntity();
|
jachness/blockcalls
|
app/src/androidTest/java/com/jachness/blockcalls/db/LogProviderTest.java
|
// Path: app/src/main/java/com/jachness/blockcalls/entities/LogEntity.java
// public class LogEntity {
// private Long uid;
// private String callerID;
// private String displayNumber;
// private String displayName;
// private long time;
// private BlockOrigin blockOrigin;
//
// public LogEntity() {
// }
//
// public LogEntity(Cursor cur) {
// for (String colName : cur.getColumnNames()) {
// int colIndex = cur.getColumnIndexOrThrow(colName);
// switch (colName) {
// case LogTable.CALLER_ID:
// this.setCallerID(cur.getString(colIndex));
// break;
// case LogTable.DISPLAY_NUMBER:
// this.setDisplayNumber(cur.getString(colIndex));
// break;
// case LogTable.DATE:
// this.setTime(cur.getLong(colIndex));
// break;
// case LogTable.BLOCK_ORIGIN:
// this.setBlockOrigin(BlockOrigin.valueOf(cur.getString(colIndex)));
// break;
// case LogTable.UID:
// this.setUid(cur.getLong(colIndex));
// break;
// case LogTable.DISPLAY_NAME:
// this.setDisplayName(cur.getString(colIndex));
// break;
// }
// }
// }
//
// public String getCallerID() {
// return callerID;
// }
//
// public void setCallerID(String callerID) {
// this.callerID = callerID;
// }
//
// public long getTime() {
// return time;
// }
//
// public void setTime(long time) {
// this.time = time;
// }
//
// public String getDisplayNumber() {
// return displayNumber;
// }
//
// public void setDisplayNumber(String displayNumber) {
// this.displayNumber = displayNumber;
// }
//
// public BlockOrigin getBlockOrigin() {
// return blockOrigin;
// }
//
// public void setBlockOrigin(BlockOrigin blockOrigin) {
// this.blockOrigin = blockOrigin;
// }
//
// @SuppressWarnings("unused")
// public Long getUid() {
// return uid;
// }
//
// @SuppressWarnings("WeakerAccess")
// public void setUid(Long uid) {
// this.uid = uid;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public void toContentValues(@NonNull ContentValues contentValue) {
// if (uid != null) contentValue.put(LogTable.UID, uid);
// contentValue.put(LogTable.CALLER_ID, callerID);
// contentValue.put(LogTable.DISPLAY_NUMBER, displayNumber);
// contentValue.put(LogTable.DISPLAY_NAME, displayName);
// contentValue.put(LogTable.DATE, Long.toString(time));
// contentValue.put(LogTable.BLOCK_ORIGIN, blockOrigin.toString());
// }
//
// @Override
// public String toString() {
// return "LogEntity{" +
// "blockOrigin=" + blockOrigin +
// ", uid=" + uid +
// ", callerID='" + callerID + '\'' +
// ", displayNumber='" + displayNumber + '\'' +
// ", displayName='" + displayName + '\'' +
// ", time=" + time +
// '}';
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/stuff/BlockOrigin.java
// public enum BlockOrigin {
// PRIVATE, CONTACTS, BLACK_LIST
// }
|
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.test.ProviderTestCase2;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import com.jachness.blockcalls.entities.LogEntity;
import com.jachness.blockcalls.stuff.BlockOrigin;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Date;
import java.util.Random;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
|
@Override
// @Before
public void setUp() throws Exception {
setContext(InstrumentationRegistry.getTargetContext());
phoneUtil = PhoneNumberUtil.getInstance();
super.setUp();
}
private PhoneNumber getRandomPhoneNumber() throws NumberParseException {
int min = 10000000;
int max = 99999999;
Random r = new Random();
int num = r.nextInt(max - min + 1) + min;
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
return phoneUtil.parseAndKeepRawInput(Integer.toString(num), "AR");
}
@Test
public void test1() throws NumberParseException {
PhoneNumber number = getRandomPhoneNumber();
String numberE164 = phoneUtil.format(number, PhoneNumberUtil.PhoneNumberFormat.E164);
String numberInt = phoneUtil.format(number, PhoneNumberUtil.PhoneNumberFormat
.INTERNATIONAL);
LogEntity logEntity = new LogEntity();
logEntity.setCallerID(numberE164);
logEntity.setDisplayNumber(numberInt);
|
// Path: app/src/main/java/com/jachness/blockcalls/entities/LogEntity.java
// public class LogEntity {
// private Long uid;
// private String callerID;
// private String displayNumber;
// private String displayName;
// private long time;
// private BlockOrigin blockOrigin;
//
// public LogEntity() {
// }
//
// public LogEntity(Cursor cur) {
// for (String colName : cur.getColumnNames()) {
// int colIndex = cur.getColumnIndexOrThrow(colName);
// switch (colName) {
// case LogTable.CALLER_ID:
// this.setCallerID(cur.getString(colIndex));
// break;
// case LogTable.DISPLAY_NUMBER:
// this.setDisplayNumber(cur.getString(colIndex));
// break;
// case LogTable.DATE:
// this.setTime(cur.getLong(colIndex));
// break;
// case LogTable.BLOCK_ORIGIN:
// this.setBlockOrigin(BlockOrigin.valueOf(cur.getString(colIndex)));
// break;
// case LogTable.UID:
// this.setUid(cur.getLong(colIndex));
// break;
// case LogTable.DISPLAY_NAME:
// this.setDisplayName(cur.getString(colIndex));
// break;
// }
// }
// }
//
// public String getCallerID() {
// return callerID;
// }
//
// public void setCallerID(String callerID) {
// this.callerID = callerID;
// }
//
// public long getTime() {
// return time;
// }
//
// public void setTime(long time) {
// this.time = time;
// }
//
// public String getDisplayNumber() {
// return displayNumber;
// }
//
// public void setDisplayNumber(String displayNumber) {
// this.displayNumber = displayNumber;
// }
//
// public BlockOrigin getBlockOrigin() {
// return blockOrigin;
// }
//
// public void setBlockOrigin(BlockOrigin blockOrigin) {
// this.blockOrigin = blockOrigin;
// }
//
// @SuppressWarnings("unused")
// public Long getUid() {
// return uid;
// }
//
// @SuppressWarnings("WeakerAccess")
// public void setUid(Long uid) {
// this.uid = uid;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public void toContentValues(@NonNull ContentValues contentValue) {
// if (uid != null) contentValue.put(LogTable.UID, uid);
// contentValue.put(LogTable.CALLER_ID, callerID);
// contentValue.put(LogTable.DISPLAY_NUMBER, displayNumber);
// contentValue.put(LogTable.DISPLAY_NAME, displayName);
// contentValue.put(LogTable.DATE, Long.toString(time));
// contentValue.put(LogTable.BLOCK_ORIGIN, blockOrigin.toString());
// }
//
// @Override
// public String toString() {
// return "LogEntity{" +
// "blockOrigin=" + blockOrigin +
// ", uid=" + uid +
// ", callerID='" + callerID + '\'' +
// ", displayNumber='" + displayNumber + '\'' +
// ", displayName='" + displayName + '\'' +
// ", time=" + time +
// '}';
// }
// }
//
// Path: app/src/main/java/com/jachness/blockcalls/stuff/BlockOrigin.java
// public enum BlockOrigin {
// PRIVATE, CONTACTS, BLACK_LIST
// }
// Path: app/src/androidTest/java/com/jachness/blockcalls/db/LogProviderTest.java
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.test.ProviderTestCase2;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import com.jachness.blockcalls.entities.LogEntity;
import com.jachness.blockcalls.stuff.BlockOrigin;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Date;
import java.util.Random;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
@Override
// @Before
public void setUp() throws Exception {
setContext(InstrumentationRegistry.getTargetContext());
phoneUtil = PhoneNumberUtil.getInstance();
super.setUp();
}
private PhoneNumber getRandomPhoneNumber() throws NumberParseException {
int min = 10000000;
int max = 99999999;
Random r = new Random();
int num = r.nextInt(max - min + 1) + min;
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
return phoneUtil.parseAndKeepRawInput(Integer.toString(num), "AR");
}
@Test
public void test1() throws NumberParseException {
PhoneNumber number = getRandomPhoneNumber();
String numberE164 = phoneUtil.format(number, PhoneNumberUtil.PhoneNumberFormat.E164);
String numberInt = phoneUtil.format(number, PhoneNumberUtil.PhoneNumberFormat
.INTERNATIONAL);
LogEntity logEntity = new LogEntity();
logEntity.setCallerID(numberE164);
logEntity.setDisplayNumber(numberInt);
|
logEntity.setBlockOrigin(BlockOrigin.CONTACTS);
|
jachness/blockcalls
|
app/src/main/java/com/jachness/blockcalls/activities/AddActivity.java
|
// Path: app/src/main/java/com/jachness/blockcalls/stuff/PermUtil.java
// @SuppressWarnings("SimplifiableIfStatement")
// public class PermUtil {
// public static final String READ_CONTACTS = Manifest.permission.READ_CONTACTS;
// public static final String CALL_PHONE = Manifest.permission.CALL_PHONE;
// public static final String WRITE_EXTERNAL_STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE;
// @SuppressLint("InlinedApi")
// public static final String READ_EXTERNAL_STORAGE = Manifest.permission.READ_EXTERNAL_STORAGE;
//
// @DebugLog
// public static boolean checkReadContacts(Context context) {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// return context.checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED;
// }
// return true;
// }
//
// @DebugLog
// public static boolean checkCallPhone(Context context) {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// return context.checkSelfPermission(CALL_PHONE) == PackageManager.PERMISSION_GRANTED;
// }
// return true;
// }
//
// @DebugLog
// public static boolean checkWriteExternalStorage(Context context) {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// return context.checkSelfPermission(WRITE_EXTERNAL_STORAGE) == PackageManager
// .PERMISSION_GRANTED;
// }
// return true;
// }
//
// @DebugLog
// public static boolean checkReadExternalStorage(Context context) {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// return context.checkSelfPermission(READ_EXTERNAL_STORAGE) == PackageManager
// .PERMISSION_GRANTED;
// }
// return true;
// }
//
// @DebugLog
// private static boolean checkNotificationPolicyAccess(Context context) {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// return ManagerUtil.getNotificationManager(context).isNotificationPolicyAccessGranted();
// }
// return true;
// }
//
//
// @DebugLog
// public static boolean[] checkInitialPermissions(AppContext context) {
// return new boolean[]{checkCallPhone(context), checkNotificationPolicyAccess(context),
// checkProtectedApps(context)};
// }
//
// /**
// * This is for Huawei phones. It has built in a "feature" called Protected Apps, that can be
// * accessed from the phone settings (Battery Manager > Protected Apps). This allows elected
// * apps to keep running after the screen is turned off.
// */
// private static boolean checkProtectedApps(AppContext context) {
// if (context.getAppPreferences().isShowProtectedAppsMessage()) {
// Intent intent = new Intent();
// intent.setClassName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize" +
// ".process.ProtectActivity");
// List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(intent,
// PackageManager.MATCH_DEFAULT_ONLY);
// return list.size() == 0;
// }
// return true;
// }
//
//
// }
|
import com.jachness.blockcalls.stuff.PermUtil;
import hugo.weaving.DebugLog;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import com.jachness.blockcalls.BuildConfig;
import com.jachness.blockcalls.R;
|
tr.replace(R.id.fragment_container, fragment, TAG_FRAGMENT);
tr.commit();
}
@Override
@DebugLog
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (null != fragment) {
outState.putString(TAG_FRAGMENT, fragment.getTag());
}
}
@Override
@DebugLog
protected void onRestart() {
super.onRestart();
if (!hasGrantedPermissions()) {
if (BuildConfig.DEBUG) Log.d(TAG, "Finish activity due to contact permission revoked");
finish();
}
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
private boolean hasGrantedPermissions() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
String val = getIntent().getExtras().getString(FRAGMENT_KEY);
if (val.equals(FRAGMENT_CONTACTS)) {
|
// Path: app/src/main/java/com/jachness/blockcalls/stuff/PermUtil.java
// @SuppressWarnings("SimplifiableIfStatement")
// public class PermUtil {
// public static final String READ_CONTACTS = Manifest.permission.READ_CONTACTS;
// public static final String CALL_PHONE = Manifest.permission.CALL_PHONE;
// public static final String WRITE_EXTERNAL_STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE;
// @SuppressLint("InlinedApi")
// public static final String READ_EXTERNAL_STORAGE = Manifest.permission.READ_EXTERNAL_STORAGE;
//
// @DebugLog
// public static boolean checkReadContacts(Context context) {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// return context.checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED;
// }
// return true;
// }
//
// @DebugLog
// public static boolean checkCallPhone(Context context) {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// return context.checkSelfPermission(CALL_PHONE) == PackageManager.PERMISSION_GRANTED;
// }
// return true;
// }
//
// @DebugLog
// public static boolean checkWriteExternalStorage(Context context) {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// return context.checkSelfPermission(WRITE_EXTERNAL_STORAGE) == PackageManager
// .PERMISSION_GRANTED;
// }
// return true;
// }
//
// @DebugLog
// public static boolean checkReadExternalStorage(Context context) {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// return context.checkSelfPermission(READ_EXTERNAL_STORAGE) == PackageManager
// .PERMISSION_GRANTED;
// }
// return true;
// }
//
// @DebugLog
// private static boolean checkNotificationPolicyAccess(Context context) {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// return ManagerUtil.getNotificationManager(context).isNotificationPolicyAccessGranted();
// }
// return true;
// }
//
//
// @DebugLog
// public static boolean[] checkInitialPermissions(AppContext context) {
// return new boolean[]{checkCallPhone(context), checkNotificationPolicyAccess(context),
// checkProtectedApps(context)};
// }
//
// /**
// * This is for Huawei phones. It has built in a "feature" called Protected Apps, that can be
// * accessed from the phone settings (Battery Manager > Protected Apps). This allows elected
// * apps to keep running after the screen is turned off.
// */
// private static boolean checkProtectedApps(AppContext context) {
// if (context.getAppPreferences().isShowProtectedAppsMessage()) {
// Intent intent = new Intent();
// intent.setClassName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize" +
// ".process.ProtectActivity");
// List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(intent,
// PackageManager.MATCH_DEFAULT_ONLY);
// return list.size() == 0;
// }
// return true;
// }
//
//
// }
// Path: app/src/main/java/com/jachness/blockcalls/activities/AddActivity.java
import com.jachness.blockcalls.stuff.PermUtil;
import hugo.weaving.DebugLog;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import com.jachness.blockcalls.BuildConfig;
import com.jachness.blockcalls.R;
tr.replace(R.id.fragment_container, fragment, TAG_FRAGMENT);
tr.commit();
}
@Override
@DebugLog
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (null != fragment) {
outState.putString(TAG_FRAGMENT, fragment.getTag());
}
}
@Override
@DebugLog
protected void onRestart() {
super.onRestart();
if (!hasGrantedPermissions()) {
if (BuildConfig.DEBUG) Log.d(TAG, "Finish activity due to contact permission revoked");
finish();
}
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
private boolean hasGrantedPermissions() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
String val = getIntent().getExtras().getString(FRAGMENT_KEY);
if (val.equals(FRAGMENT_CONTACTS)) {
|
return PermUtil.checkReadContacts(this);
|
lrscp/ControlAndroidDeviceFromPC
|
src/com/android/ddmuilib/AllocationPanel.java
|
// Path: src/com/android/ddmlib/AndroidDebugBridge.java
// public interface IClientChangeListener {
// /**
// * Sent when an existing client information changed.
// * <p/>
// * This is sent from a non UI thread.
// * @param client the updated client.
// * @param changeMask the bit mask describing the changed properties. It can contain
// * any of the following values: {@link Client#CHANGE_INFO},
// * {@link Client#CHANGE_DEBUGGER_STATUS}, {@link Client#CHANGE_THREAD_MODE},
// * {@link Client#CHANGE_THREAD_DATA}, {@link Client#CHANGE_HEAP_MODE},
// * {@link Client#CHANGE_HEAP_DATA}, {@link Client#CHANGE_NATIVE_HEAP_DATA}
// */
// public void clientChanged(Client client, int changeMask);
// }
//
// Path: src/com/android/ddmlib/ClientData.java
// public static enum AllocationTrackingStatus {
// /**
// * Allocation tracking status: unknown.
// * <p/>This happens right after a {@link Client} is discovered
// * by the {@link AndroidDebugBridge}, and before the {@link Client} answered the query
// * regarding its allocation tracking status.
// * @see Client#requestAllocationStatus()
// */
// UNKNOWN,
// /** Allocation tracking status: the {@link Client} is not tracking allocations. */
// OFF,
// /** Allocation tracking status: the {@link Client} is tracking allocations. */
// ON;
// }
|
import com.android.ddmlib.AllocationInfo;
import com.android.ddmlib.AllocationInfo.AllocationSorter;
import com.android.ddmlib.AllocationInfo.SortMode;
import com.android.ddmlib.AndroidDebugBridge.IClientChangeListener;
import com.android.ddmlib.Client;
import com.android.ddmlib.ClientData.AllocationTrackingStatus;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Sash;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
|
// pass
}
}
/**
* Create our control(s).
*/
@Override
protected Control createControl(Composite parent) {
final IPreferenceStore store = DdmUiPreferences.getStore();
Display display = parent.getDisplay();
// get some images
mSortUpImg = ImageLoader.getDdmUiLibLoader().loadImage("sort_up.png", display);
mSortDownImg = ImageLoader.getDdmUiLibLoader().loadImage("sort_down.png", display);
// base composite for selected client with enabled thread update.
mAllocationBase = new Composite(parent, SWT.NONE);
mAllocationBase.setLayout(new FormLayout());
// table above the sash
Composite topParent = new Composite(mAllocationBase, SWT.NONE);
topParent.setLayout(new GridLayout(6, false));
mEnableButton = new Button(topParent, SWT.PUSH);
mEnableButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Client current = getCurrentClient();
|
// Path: src/com/android/ddmlib/AndroidDebugBridge.java
// public interface IClientChangeListener {
// /**
// * Sent when an existing client information changed.
// * <p/>
// * This is sent from a non UI thread.
// * @param client the updated client.
// * @param changeMask the bit mask describing the changed properties. It can contain
// * any of the following values: {@link Client#CHANGE_INFO},
// * {@link Client#CHANGE_DEBUGGER_STATUS}, {@link Client#CHANGE_THREAD_MODE},
// * {@link Client#CHANGE_THREAD_DATA}, {@link Client#CHANGE_HEAP_MODE},
// * {@link Client#CHANGE_HEAP_DATA}, {@link Client#CHANGE_NATIVE_HEAP_DATA}
// */
// public void clientChanged(Client client, int changeMask);
// }
//
// Path: src/com/android/ddmlib/ClientData.java
// public static enum AllocationTrackingStatus {
// /**
// * Allocation tracking status: unknown.
// * <p/>This happens right after a {@link Client} is discovered
// * by the {@link AndroidDebugBridge}, and before the {@link Client} answered the query
// * regarding its allocation tracking status.
// * @see Client#requestAllocationStatus()
// */
// UNKNOWN,
// /** Allocation tracking status: the {@link Client} is not tracking allocations. */
// OFF,
// /** Allocation tracking status: the {@link Client} is tracking allocations. */
// ON;
// }
// Path: src/com/android/ddmuilib/AllocationPanel.java
import com.android.ddmlib.AllocationInfo;
import com.android.ddmlib.AllocationInfo.AllocationSorter;
import com.android.ddmlib.AllocationInfo.SortMode;
import com.android.ddmlib.AndroidDebugBridge.IClientChangeListener;
import com.android.ddmlib.Client;
import com.android.ddmlib.ClientData.AllocationTrackingStatus;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Sash;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
// pass
}
}
/**
* Create our control(s).
*/
@Override
protected Control createControl(Composite parent) {
final IPreferenceStore store = DdmUiPreferences.getStore();
Display display = parent.getDisplay();
// get some images
mSortUpImg = ImageLoader.getDdmUiLibLoader().loadImage("sort_up.png", display);
mSortDownImg = ImageLoader.getDdmUiLibLoader().loadImage("sort_down.png", display);
// base composite for selected client with enabled thread update.
mAllocationBase = new Composite(parent, SWT.NONE);
mAllocationBase.setLayout(new FormLayout());
// table above the sash
Composite topParent = new Composite(mAllocationBase, SWT.NONE);
topParent.setLayout(new GridLayout(6, false));
mEnableButton = new Button(topParent, SWT.PUSH);
mEnableButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Client current = getCurrentClient();
|
AllocationTrackingStatus status = current.getClientData().getAllocationStatus();
|
lrscp/ControlAndroidDeviceFromPC
|
src/com/android/ddmuilib/logcat/LogFilter.java
|
// Path: src/com/android/ddmuilib/logcat/LogPanel.java
// protected static class LogMessage {
// public LogMessageInfo data;
// public String msg;
//
// @Override
// public String toString() {
// return data.time + ": " //$NON-NLS-1$
// + data.logLevel + "/" //$NON-NLS-1$
// + data.tag + "(" //$NON-NLS-1$
// + data.pidString + "): " //$NON-NLS-1$
// + msg;
// }
// }
|
import com.android.ddmlib.Log;
import com.android.ddmlib.Log.LogLevel;
import com.android.ddmuilib.annotation.UiThread;
import com.android.ddmuilib.logcat.LogPanel.LogMessage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import java.util.ArrayList;
import java.util.regex.PatternSyntaxException;
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.ddmuilib.logcat;
/** logcat output filter class */
public class LogFilter {
public final static int MODE_PID = 0x01;
public final static int MODE_TAG = 0x02;
public final static int MODE_LEVEL = 0x04;
private String mName;
/**
* Filtering mode. Value can be a mix of MODE_PID, MODE_TAG, MODE_LEVEL
*/
private int mMode = 0;
/**
* pid used for filtering. Only valid if mMode is MODE_PID.
*/
private int mPid;
/** Single level log level as defined in Log.mLevelChar. Only valid
* if mMode is MODE_LEVEL */
private int mLogLevel;
/**
* log tag filtering. Only valid if mMode is MODE_TAG
*/
private String mTag;
private Table mTable;
private TabItem mTabItem;
private boolean mIsCurrentTabItem = false;
private int mUnreadCount = 0;
/** Temp keyword filtering */
private String[] mTempKeywordFilters;
/** temp pid filtering */
private int mTempPid = -1;
/** temp tag filtering */
private String mTempTag;
/** temp log level filtering */
private int mTempLogLevel = -1;
private LogColors mColors;
private boolean mTempFilteringStatus = false;
|
// Path: src/com/android/ddmuilib/logcat/LogPanel.java
// protected static class LogMessage {
// public LogMessageInfo data;
// public String msg;
//
// @Override
// public String toString() {
// return data.time + ": " //$NON-NLS-1$
// + data.logLevel + "/" //$NON-NLS-1$
// + data.tag + "(" //$NON-NLS-1$
// + data.pidString + "): " //$NON-NLS-1$
// + msg;
// }
// }
// Path: src/com/android/ddmuilib/logcat/LogFilter.java
import com.android.ddmlib.Log;
import com.android.ddmlib.Log.LogLevel;
import com.android.ddmuilib.annotation.UiThread;
import com.android.ddmuilib.logcat.LogPanel.LogMessage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import java.util.ArrayList;
import java.util.regex.PatternSyntaxException;
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.ddmuilib.logcat;
/** logcat output filter class */
public class LogFilter {
public final static int MODE_PID = 0x01;
public final static int MODE_TAG = 0x02;
public final static int MODE_LEVEL = 0x04;
private String mName;
/**
* Filtering mode. Value can be a mix of MODE_PID, MODE_TAG, MODE_LEVEL
*/
private int mMode = 0;
/**
* pid used for filtering. Only valid if mMode is MODE_PID.
*/
private int mPid;
/** Single level log level as defined in Log.mLevelChar. Only valid
* if mMode is MODE_LEVEL */
private int mLogLevel;
/**
* log tag filtering. Only valid if mMode is MODE_TAG
*/
private String mTag;
private Table mTable;
private TabItem mTabItem;
private boolean mIsCurrentTabItem = false;
private int mUnreadCount = 0;
/** Temp keyword filtering */
private String[] mTempKeywordFilters;
/** temp pid filtering */
private int mTempPid = -1;
/** temp tag filtering */
private String mTempTag;
/** temp log level filtering */
private int mTempLogLevel = -1;
private LogColors mColors;
private boolean mTempFilteringStatus = false;
|
private final ArrayList<LogMessage> mMessages = new ArrayList<LogMessage>();
|
lrscp/ControlAndroidDeviceFromPC
|
src/com/android/ddmuilib/location/TrackLabelProvider.java
|
// Path: src/com/android/ddmuilib/location/GpxParser.java
// public final static class Track {
// private String mName;
// private String mComment;
// private List<TrackPoint> mPoints = new ArrayList<TrackPoint>();
//
// void setName(String name) {
// mName = name;
// }
//
// public String getName() {
// return mName;
// }
//
// void setComment(String comment) {
// mComment = comment;
// }
//
// public String getComment() {
// return mComment;
// }
//
// void addPoint(TrackPoint trackPoint) {
// mPoints.add(trackPoint);
// }
//
// public TrackPoint[] getPoints() {
// return mPoints.toArray(new TrackPoint[mPoints.size()]);
// }
//
// public long getFirstPointTime() {
// if (mPoints.size() > 0) {
// return mPoints.get(0).getTime();
// }
//
// return -1;
// }
//
// public long getLastPointTime() {
// if (mPoints.size() > 0) {
// return mPoints.get(mPoints.size()-1).getTime();
// }
//
// return -1;
// }
//
// public int getPointCount() {
// return mPoints.size();
// }
// }
|
import com.android.ddmuilib.location.GpxParser.Track;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Table;
import java.util.Date;
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.ddmuilib.location;
/**
* Label Provider for {@link Table} objects displaying {@link Track} objects.
*/
public class TrackLabelProvider implements ITableLabelProvider {
@Override
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
@Override
public String getColumnText(Object element, int columnIndex) {
|
// Path: src/com/android/ddmuilib/location/GpxParser.java
// public final static class Track {
// private String mName;
// private String mComment;
// private List<TrackPoint> mPoints = new ArrayList<TrackPoint>();
//
// void setName(String name) {
// mName = name;
// }
//
// public String getName() {
// return mName;
// }
//
// void setComment(String comment) {
// mComment = comment;
// }
//
// public String getComment() {
// return mComment;
// }
//
// void addPoint(TrackPoint trackPoint) {
// mPoints.add(trackPoint);
// }
//
// public TrackPoint[] getPoints() {
// return mPoints.toArray(new TrackPoint[mPoints.size()]);
// }
//
// public long getFirstPointTime() {
// if (mPoints.size() > 0) {
// return mPoints.get(0).getTime();
// }
//
// return -1;
// }
//
// public long getLastPointTime() {
// if (mPoints.size() > 0) {
// return mPoints.get(mPoints.size()-1).getTime();
// }
//
// return -1;
// }
//
// public int getPointCount() {
// return mPoints.size();
// }
// }
// Path: src/com/android/ddmuilib/location/TrackLabelProvider.java
import com.android.ddmuilib.location.GpxParser.Track;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Table;
import java.util.Date;
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.ddmuilib.location;
/**
* Label Provider for {@link Table} objects displaying {@link Track} objects.
*/
public class TrackLabelProvider implements ITableLabelProvider {
@Override
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
@Override
public String getColumnText(Object element, int columnIndex) {
|
if (element instanceof Track) {
|
lrscp/ControlAndroidDeviceFromPC
|
src/com/android/ddmuilib/TablePanel.java
|
// Path: src/com/android/ddmuilib/ITableFocusListener.java
// public interface IFocusedTableActivator {
// public void copy(Clipboard clipboard);
//
// public void selectAll();
// }
|
import com.android.ddmuilib.ITableFocusListener.IFocusedTableActivator;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import java.util.Arrays;
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.ddmuilib;
/**
* Base class for panel containing Table that need to support copy-paste-selectAll
*/
public abstract class TablePanel extends ClientDisplayPanel {
private ITableFocusListener mGlobalListener;
/**
* Sets a TableFocusListener which will be notified when one of the tables
* gets or loses focus.
*
* @param listener
*/
public void setTableFocusListener(ITableFocusListener listener) {
// record the global listener, to make sure table created after
// this call will still be setup.
mGlobalListener = listener;
setTableFocusListener();
}
/**
* Sets up the Table of object of the panel to work with the global listener.<br>
* Default implementation does nothing.
*/
protected void setTableFocusListener() {
}
/**
* Sets up a Table object to notify the global Table Focus listener when it
* gets or loses the focus.
*
* @param table the Table object.
* @param colStart
* @param colEnd
*/
protected final void addTableToFocusListener(final Table table,
final int colStart, final int colEnd) {
// create the activator for this table
|
// Path: src/com/android/ddmuilib/ITableFocusListener.java
// public interface IFocusedTableActivator {
// public void copy(Clipboard clipboard);
//
// public void selectAll();
// }
// Path: src/com/android/ddmuilib/TablePanel.java
import com.android.ddmuilib.ITableFocusListener.IFocusedTableActivator;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import java.util.Arrays;
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.ddmuilib;
/**
* Base class for panel containing Table that need to support copy-paste-selectAll
*/
public abstract class TablePanel extends ClientDisplayPanel {
private ITableFocusListener mGlobalListener;
/**
* Sets a TableFocusListener which will be notified when one of the tables
* gets or loses focus.
*
* @param listener
*/
public void setTableFocusListener(ITableFocusListener listener) {
// record the global listener, to make sure table created after
// this call will still be setup.
mGlobalListener = listener;
setTableFocusListener();
}
/**
* Sets up the Table of object of the panel to work with the global listener.<br>
* Default implementation does nothing.
*/
protected void setTableFocusListener() {
}
/**
* Sets up a Table object to notify the global Table Focus listener when it
* gets or loses the focus.
*
* @param table the Table object.
* @param colStart
* @param colEnd
*/
protected final void addTableToFocusListener(final Table table,
final int colStart, final int colEnd) {
// create the activator for this table
|
final IFocusedTableActivator activator = new IFocusedTableActivator() {
|
lrscp/ControlAndroidDeviceFromPC
|
src/com/android/ddmuilib/location/TrackContentProvider.java
|
// Path: src/com/android/ddmuilib/location/GpxParser.java
// public final static class Track {
// private String mName;
// private String mComment;
// private List<TrackPoint> mPoints = new ArrayList<TrackPoint>();
//
// void setName(String name) {
// mName = name;
// }
//
// public String getName() {
// return mName;
// }
//
// void setComment(String comment) {
// mComment = comment;
// }
//
// public String getComment() {
// return mComment;
// }
//
// void addPoint(TrackPoint trackPoint) {
// mPoints.add(trackPoint);
// }
//
// public TrackPoint[] getPoints() {
// return mPoints.toArray(new TrackPoint[mPoints.size()]);
// }
//
// public long getFirstPointTime() {
// if (mPoints.size() > 0) {
// return mPoints.get(0).getTime();
// }
//
// return -1;
// }
//
// public long getLastPointTime() {
// if (mPoints.size() > 0) {
// return mPoints.get(mPoints.size()-1).getTime();
// }
//
// return -1;
// }
//
// public int getPointCount() {
// return mPoints.size();
// }
// }
|
import com.android.ddmuilib.location.GpxParser.Track;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.Viewer;
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.ddmuilib.location;
/**
* Content provider to display {@link Track} objects in a Table.
* <p/>The expected type for the input is {@link Track}<code>[]</code>.
*/
public class TrackContentProvider implements IStructuredContentProvider {
@Override
public Object[] getElements(Object inputElement) {
|
// Path: src/com/android/ddmuilib/location/GpxParser.java
// public final static class Track {
// private String mName;
// private String mComment;
// private List<TrackPoint> mPoints = new ArrayList<TrackPoint>();
//
// void setName(String name) {
// mName = name;
// }
//
// public String getName() {
// return mName;
// }
//
// void setComment(String comment) {
// mComment = comment;
// }
//
// public String getComment() {
// return mComment;
// }
//
// void addPoint(TrackPoint trackPoint) {
// mPoints.add(trackPoint);
// }
//
// public TrackPoint[] getPoints() {
// return mPoints.toArray(new TrackPoint[mPoints.size()]);
// }
//
// public long getFirstPointTime() {
// if (mPoints.size() > 0) {
// return mPoints.get(0).getTime();
// }
//
// return -1;
// }
//
// public long getLastPointTime() {
// if (mPoints.size() > 0) {
// return mPoints.get(mPoints.size()-1).getTime();
// }
//
// return -1;
// }
//
// public int getPointCount() {
// return mPoints.size();
// }
// }
// Path: src/com/android/ddmuilib/location/TrackContentProvider.java
import com.android.ddmuilib.location.GpxParser.Track;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.Viewer;
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.ddmuilib.location;
/**
* Content provider to display {@link Track} objects in a Table.
* <p/>The expected type for the input is {@link Track}<code>[]</code>.
*/
public class TrackContentProvider implements IStructuredContentProvider {
@Override
public Object[] getElements(Object inputElement) {
|
if (inputElement instanceof Track[]) {
|
ChenXun1989/ace
|
ace-core/src/main/java/wiki/chenxun/ace/core/base/config/DefaultConfig.java
|
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/common/AceApplicationConfig.java
// @Data
// @ConfigBean(AceApplicationConfig.PREFIX)
// public class AceApplicationConfig {
//
//
// public static final String PREFIX = "ace.application";
//
// private String name;
//
// private String dispatch;
//
// private String server;
//
// private String packages ="wiki.chenxun.ace.core";
//
// private String container;
//
// private String register;
//
// }
//
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/common/AceServerConfig.java
// @Data
// @ConfigBean(AceServerConfig.PREFIX)
// public class AceServerConfig {
//
// public static final String PREFIX = "ace.server";
//
// private long timeout = 1000L;
//
// private int port = 8080;
//
// private int backSize = 1024;
// }
|
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import wiki.chenxun.ace.core.base.annotations.ConfigBean;
import wiki.chenxun.ace.core.base.common.AceApplicationConfig;
import wiki.chenxun.ace.core.base.common.AceServerConfig;
import wiki.chenxun.ace.core.base.register.RegisterConfig;
import wiki.chenxun.ace.core.base.support.InetAddressUtil;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
|
configBeanParser = new ConfigBeanParser();
configBeanParser.parser(cls);
add(configBeanParser);
}
return configBeanParser;
}
@Override
public void add(ConfigBeanParser parser) {
configInstances.put(parser.getConfigBean().getClass(), parser);
}
@Override
public synchronized void export() {
if (zooKeeper != null) {
return;
}
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
RegisterConfig registerConfig = (RegisterConfig) configInstances.get(RegisterConfig.class).getConfigBean();
try {
zooKeeper = new ZooKeeper(registerConfig.getUrl(), registerConfig.getTimeout(), new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
}
});
String ip = InetAddressUtil.getHostIp();
|
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/common/AceApplicationConfig.java
// @Data
// @ConfigBean(AceApplicationConfig.PREFIX)
// public class AceApplicationConfig {
//
//
// public static final String PREFIX = "ace.application";
//
// private String name;
//
// private String dispatch;
//
// private String server;
//
// private String packages ="wiki.chenxun.ace.core";
//
// private String container;
//
// private String register;
//
// }
//
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/common/AceServerConfig.java
// @Data
// @ConfigBean(AceServerConfig.PREFIX)
// public class AceServerConfig {
//
// public static final String PREFIX = "ace.server";
//
// private long timeout = 1000L;
//
// private int port = 8080;
//
// private int backSize = 1024;
// }
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/config/DefaultConfig.java
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import wiki.chenxun.ace.core.base.annotations.ConfigBean;
import wiki.chenxun.ace.core.base.common.AceApplicationConfig;
import wiki.chenxun.ace.core.base.common.AceServerConfig;
import wiki.chenxun.ace.core.base.register.RegisterConfig;
import wiki.chenxun.ace.core.base.support.InetAddressUtil;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
configBeanParser = new ConfigBeanParser();
configBeanParser.parser(cls);
add(configBeanParser);
}
return configBeanParser;
}
@Override
public void add(ConfigBeanParser parser) {
configInstances.put(parser.getConfigBean().getClass(), parser);
}
@Override
public synchronized void export() {
if (zooKeeper != null) {
return;
}
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
RegisterConfig registerConfig = (RegisterConfig) configInstances.get(RegisterConfig.class).getConfigBean();
try {
zooKeeper = new ZooKeeper(registerConfig.getUrl(), registerConfig.getTimeout(), new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
}
});
String ip = InetAddressUtil.getHostIp();
|
AceServerConfig aceServerConfig = (AceServerConfig) configBeanParser(AceServerConfig.class).getConfigBean();
|
ChenXun1989/ace
|
ace-admin/src/main/java/wiki/chenxun/ace/admin/service/impl/ConfigManageServiceImpl.java
|
// Path: ace-admin/src/main/java/wiki/chenxun/ace/admin/entity/ConfigEntity.java
// @Data
// public class ConfigEntity {
//
// private String name;
//
// private Date time;
// }
//
// Path: ace-admin/src/main/java/wiki/chenxun/ace/admin/entity/Page.java
// @Data
// public class Page<T> {
//
// private long total;
//
// private List<T> rows;
//
// }
|
import org.springframework.stereotype.Component;
import wiki.chenxun.ace.admin.entity.ConfigEntity;
import wiki.chenxun.ace.admin.entity.Page;
import wiki.chenxun.ace.admin.service.ConfigManageService;
import wiki.chenxun.ace.core.base.annotations.AceService;
import wiki.chenxun.ace.core.base.annotations.Get;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
|
package wiki.chenxun.ace.admin.service.impl;
/**
* @Description: Created by chenxun on 2017/4/23.
*/
@AceService(path = "/config")
@Component
public class ConfigManageServiceImpl implements ConfigManageService {
@Get
@Override
|
// Path: ace-admin/src/main/java/wiki/chenxun/ace/admin/entity/ConfigEntity.java
// @Data
// public class ConfigEntity {
//
// private String name;
//
// private Date time;
// }
//
// Path: ace-admin/src/main/java/wiki/chenxun/ace/admin/entity/Page.java
// @Data
// public class Page<T> {
//
// private long total;
//
// private List<T> rows;
//
// }
// Path: ace-admin/src/main/java/wiki/chenxun/ace/admin/service/impl/ConfigManageServiceImpl.java
import org.springframework.stereotype.Component;
import wiki.chenxun.ace.admin.entity.ConfigEntity;
import wiki.chenxun.ace.admin.entity.Page;
import wiki.chenxun.ace.admin.service.ConfigManageService;
import wiki.chenxun.ace.core.base.annotations.AceService;
import wiki.chenxun.ace.core.base.annotations.Get;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
package wiki.chenxun.ace.admin.service.impl;
/**
* @Description: Created by chenxun on 2017/4/23.
*/
@AceService(path = "/config")
@Component
public class ConfigManageServiceImpl implements ConfigManageService {
@Get
@Override
|
public Page<ConfigEntity> page() {
|
ChenXun1989/ace
|
ace-admin/src/main/java/wiki/chenxun/ace/admin/service/impl/ConfigManageServiceImpl.java
|
// Path: ace-admin/src/main/java/wiki/chenxun/ace/admin/entity/ConfigEntity.java
// @Data
// public class ConfigEntity {
//
// private String name;
//
// private Date time;
// }
//
// Path: ace-admin/src/main/java/wiki/chenxun/ace/admin/entity/Page.java
// @Data
// public class Page<T> {
//
// private long total;
//
// private List<T> rows;
//
// }
|
import org.springframework.stereotype.Component;
import wiki.chenxun.ace.admin.entity.ConfigEntity;
import wiki.chenxun.ace.admin.entity.Page;
import wiki.chenxun.ace.admin.service.ConfigManageService;
import wiki.chenxun.ace.core.base.annotations.AceService;
import wiki.chenxun.ace.core.base.annotations.Get;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
|
package wiki.chenxun.ace.admin.service.impl;
/**
* @Description: Created by chenxun on 2017/4/23.
*/
@AceService(path = "/config")
@Component
public class ConfigManageServiceImpl implements ConfigManageService {
@Get
@Override
|
// Path: ace-admin/src/main/java/wiki/chenxun/ace/admin/entity/ConfigEntity.java
// @Data
// public class ConfigEntity {
//
// private String name;
//
// private Date time;
// }
//
// Path: ace-admin/src/main/java/wiki/chenxun/ace/admin/entity/Page.java
// @Data
// public class Page<T> {
//
// private long total;
//
// private List<T> rows;
//
// }
// Path: ace-admin/src/main/java/wiki/chenxun/ace/admin/service/impl/ConfigManageServiceImpl.java
import org.springframework.stereotype.Component;
import wiki.chenxun.ace.admin.entity.ConfigEntity;
import wiki.chenxun.ace.admin.entity.Page;
import wiki.chenxun.ace.admin.service.ConfigManageService;
import wiki.chenxun.ace.core.base.annotations.AceService;
import wiki.chenxun.ace.core.base.annotations.Get;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
package wiki.chenxun.ace.admin.service.impl;
/**
* @Description: Created by chenxun on 2017/4/23.
*/
@AceService(path = "/config")
@Component
public class ConfigManageServiceImpl implements ConfigManageService {
@Get
@Override
|
public Page<ConfigEntity> page() {
|
ChenXun1989/ace
|
ace-admin/src/main/java/wiki/chenxun/ace/admin/service/impl/ZookeeperManageServiceImpl.java
|
// Path: ace-admin/src/main/java/wiki/chenxun/ace/admin/entity/ApplicationInfo.java
// @Data
// public class ApplicationInfo {
//
// private String name;
//
// private String ip;
//
// private String port;
// }
//
// Path: ace-admin/src/main/java/wiki/chenxun/ace/admin/entity/Page.java
// @Data
// public class Page<T> {
//
// private long total;
//
// private List<T> rows;
//
// }
//
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/common/AceApplicationConfig.java
// @Data
// @ConfigBean(AceApplicationConfig.PREFIX)
// public class AceApplicationConfig {
//
//
// public static final String PREFIX = "ace.application";
//
// private String name;
//
// private String dispatch;
//
// private String server;
//
// private String packages ="wiki.chenxun.ace.core";
//
// private String container;
//
// private String register;
//
// }
|
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import wiki.chenxun.ace.admin.entity.ApplicationInfo;
import wiki.chenxun.ace.admin.entity.Page;
import wiki.chenxun.ace.admin.service.ZookeeperManageService;
import wiki.chenxun.ace.core.base.annotations.AceService;
import wiki.chenxun.ace.core.base.annotations.Get;
import wiki.chenxun.ace.core.base.common.AceApplicationConfig;
import wiki.chenxun.ace.core.base.config.Config;
import wiki.chenxun.ace.core.base.register.RegisterConfig;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
|
package wiki.chenxun.ace.admin.service.impl;
/**
* @Description: Created by chenxun on 2017/4/23.
*/
@AceService(path = "/zookeeper/manage")
@Component
public class ZookeeperManageServiceImpl implements ZookeeperManageService {
@Autowired
private RegisterConfig registerConfig;
@Get
@Override
|
// Path: ace-admin/src/main/java/wiki/chenxun/ace/admin/entity/ApplicationInfo.java
// @Data
// public class ApplicationInfo {
//
// private String name;
//
// private String ip;
//
// private String port;
// }
//
// Path: ace-admin/src/main/java/wiki/chenxun/ace/admin/entity/Page.java
// @Data
// public class Page<T> {
//
// private long total;
//
// private List<T> rows;
//
// }
//
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/common/AceApplicationConfig.java
// @Data
// @ConfigBean(AceApplicationConfig.PREFIX)
// public class AceApplicationConfig {
//
//
// public static final String PREFIX = "ace.application";
//
// private String name;
//
// private String dispatch;
//
// private String server;
//
// private String packages ="wiki.chenxun.ace.core";
//
// private String container;
//
// private String register;
//
// }
// Path: ace-admin/src/main/java/wiki/chenxun/ace/admin/service/impl/ZookeeperManageServiceImpl.java
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import wiki.chenxun.ace.admin.entity.ApplicationInfo;
import wiki.chenxun.ace.admin.entity.Page;
import wiki.chenxun.ace.admin.service.ZookeeperManageService;
import wiki.chenxun.ace.core.base.annotations.AceService;
import wiki.chenxun.ace.core.base.annotations.Get;
import wiki.chenxun.ace.core.base.common.AceApplicationConfig;
import wiki.chenxun.ace.core.base.config.Config;
import wiki.chenxun.ace.core.base.register.RegisterConfig;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
package wiki.chenxun.ace.admin.service.impl;
/**
* @Description: Created by chenxun on 2017/4/23.
*/
@AceService(path = "/zookeeper/manage")
@Component
public class ZookeeperManageServiceImpl implements ZookeeperManageService {
@Autowired
private RegisterConfig registerConfig;
@Get
@Override
|
public Page<ApplicationInfo> queryAllManageNodes() {
|
ChenXun1989/ace
|
ace-admin/src/main/java/wiki/chenxun/ace/admin/service/impl/ZookeeperManageServiceImpl.java
|
// Path: ace-admin/src/main/java/wiki/chenxun/ace/admin/entity/ApplicationInfo.java
// @Data
// public class ApplicationInfo {
//
// private String name;
//
// private String ip;
//
// private String port;
// }
//
// Path: ace-admin/src/main/java/wiki/chenxun/ace/admin/entity/Page.java
// @Data
// public class Page<T> {
//
// private long total;
//
// private List<T> rows;
//
// }
//
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/common/AceApplicationConfig.java
// @Data
// @ConfigBean(AceApplicationConfig.PREFIX)
// public class AceApplicationConfig {
//
//
// public static final String PREFIX = "ace.application";
//
// private String name;
//
// private String dispatch;
//
// private String server;
//
// private String packages ="wiki.chenxun.ace.core";
//
// private String container;
//
// private String register;
//
// }
|
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import wiki.chenxun.ace.admin.entity.ApplicationInfo;
import wiki.chenxun.ace.admin.entity.Page;
import wiki.chenxun.ace.admin.service.ZookeeperManageService;
import wiki.chenxun.ace.core.base.annotations.AceService;
import wiki.chenxun.ace.core.base.annotations.Get;
import wiki.chenxun.ace.core.base.common.AceApplicationConfig;
import wiki.chenxun.ace.core.base.config.Config;
import wiki.chenxun.ace.core.base.register.RegisterConfig;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
|
package wiki.chenxun.ace.admin.service.impl;
/**
* @Description: Created by chenxun on 2017/4/23.
*/
@AceService(path = "/zookeeper/manage")
@Component
public class ZookeeperManageServiceImpl implements ZookeeperManageService {
@Autowired
private RegisterConfig registerConfig;
@Get
@Override
|
// Path: ace-admin/src/main/java/wiki/chenxun/ace/admin/entity/ApplicationInfo.java
// @Data
// public class ApplicationInfo {
//
// private String name;
//
// private String ip;
//
// private String port;
// }
//
// Path: ace-admin/src/main/java/wiki/chenxun/ace/admin/entity/Page.java
// @Data
// public class Page<T> {
//
// private long total;
//
// private List<T> rows;
//
// }
//
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/common/AceApplicationConfig.java
// @Data
// @ConfigBean(AceApplicationConfig.PREFIX)
// public class AceApplicationConfig {
//
//
// public static final String PREFIX = "ace.application";
//
// private String name;
//
// private String dispatch;
//
// private String server;
//
// private String packages ="wiki.chenxun.ace.core";
//
// private String container;
//
// private String register;
//
// }
// Path: ace-admin/src/main/java/wiki/chenxun/ace/admin/service/impl/ZookeeperManageServiceImpl.java
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import wiki.chenxun.ace.admin.entity.ApplicationInfo;
import wiki.chenxun.ace.admin.entity.Page;
import wiki.chenxun.ace.admin.service.ZookeeperManageService;
import wiki.chenxun.ace.core.base.annotations.AceService;
import wiki.chenxun.ace.core.base.annotations.Get;
import wiki.chenxun.ace.core.base.common.AceApplicationConfig;
import wiki.chenxun.ace.core.base.config.Config;
import wiki.chenxun.ace.core.base.register.RegisterConfig;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
package wiki.chenxun.ace.admin.service.impl;
/**
* @Description: Created by chenxun on 2017/4/23.
*/
@AceService(path = "/zookeeper/manage")
@Component
public class ZookeeperManageServiceImpl implements ZookeeperManageService {
@Autowired
private RegisterConfig registerConfig;
@Get
@Override
|
public Page<ApplicationInfo> queryAllManageNodes() {
|
ChenXun1989/ace
|
ace-admin/src/main/java/wiki/chenxun/ace/admin/service/impl/ZookeeperManageServiceImpl.java
|
// Path: ace-admin/src/main/java/wiki/chenxun/ace/admin/entity/ApplicationInfo.java
// @Data
// public class ApplicationInfo {
//
// private String name;
//
// private String ip;
//
// private String port;
// }
//
// Path: ace-admin/src/main/java/wiki/chenxun/ace/admin/entity/Page.java
// @Data
// public class Page<T> {
//
// private long total;
//
// private List<T> rows;
//
// }
//
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/common/AceApplicationConfig.java
// @Data
// @ConfigBean(AceApplicationConfig.PREFIX)
// public class AceApplicationConfig {
//
//
// public static final String PREFIX = "ace.application";
//
// private String name;
//
// private String dispatch;
//
// private String server;
//
// private String packages ="wiki.chenxun.ace.core";
//
// private String container;
//
// private String register;
//
// }
|
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import wiki.chenxun.ace.admin.entity.ApplicationInfo;
import wiki.chenxun.ace.admin.entity.Page;
import wiki.chenxun.ace.admin.service.ZookeeperManageService;
import wiki.chenxun.ace.core.base.annotations.AceService;
import wiki.chenxun.ace.core.base.annotations.Get;
import wiki.chenxun.ace.core.base.common.AceApplicationConfig;
import wiki.chenxun.ace.core.base.config.Config;
import wiki.chenxun.ace.core.base.register.RegisterConfig;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
|
package wiki.chenxun.ace.admin.service.impl;
/**
* @Description: Created by chenxun on 2017/4/23.
*/
@AceService(path = "/zookeeper/manage")
@Component
public class ZookeeperManageServiceImpl implements ZookeeperManageService {
@Autowired
private RegisterConfig registerConfig;
@Get
@Override
public Page<ApplicationInfo> queryAllManageNodes() {
Page<ApplicationInfo> page = new Page<>();
ZooKeeper zooKeeper = null;
try {
|
// Path: ace-admin/src/main/java/wiki/chenxun/ace/admin/entity/ApplicationInfo.java
// @Data
// public class ApplicationInfo {
//
// private String name;
//
// private String ip;
//
// private String port;
// }
//
// Path: ace-admin/src/main/java/wiki/chenxun/ace/admin/entity/Page.java
// @Data
// public class Page<T> {
//
// private long total;
//
// private List<T> rows;
//
// }
//
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/common/AceApplicationConfig.java
// @Data
// @ConfigBean(AceApplicationConfig.PREFIX)
// public class AceApplicationConfig {
//
//
// public static final String PREFIX = "ace.application";
//
// private String name;
//
// private String dispatch;
//
// private String server;
//
// private String packages ="wiki.chenxun.ace.core";
//
// private String container;
//
// private String register;
//
// }
// Path: ace-admin/src/main/java/wiki/chenxun/ace/admin/service/impl/ZookeeperManageServiceImpl.java
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import wiki.chenxun.ace.admin.entity.ApplicationInfo;
import wiki.chenxun.ace.admin.entity.Page;
import wiki.chenxun.ace.admin.service.ZookeeperManageService;
import wiki.chenxun.ace.core.base.annotations.AceService;
import wiki.chenxun.ace.core.base.annotations.Get;
import wiki.chenxun.ace.core.base.common.AceApplicationConfig;
import wiki.chenxun.ace.core.base.config.Config;
import wiki.chenxun.ace.core.base.register.RegisterConfig;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
package wiki.chenxun.ace.admin.service.impl;
/**
* @Description: Created by chenxun on 2017/4/23.
*/
@AceService(path = "/zookeeper/manage")
@Component
public class ZookeeperManageServiceImpl implements ZookeeperManageService {
@Autowired
private RegisterConfig registerConfig;
@Get
@Override
public Page<ApplicationInfo> queryAllManageNodes() {
Page<ApplicationInfo> page = new Page<>();
ZooKeeper zooKeeper = null;
try {
|
String path = Config.ROOT_PATH + AceApplicationConfig.PREFIX;
|
ChenXun1989/ace
|
ace-core/src/main/java/wiki/chenxun/ace/core/Main.java
|
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/common/AceApplication.java
// public class AceApplication implements ConfigBeanAware<AceApplicationConfig> {
//
// private String basePage = "wiki.chenxun.ace.core";
//
// private AceApplicationConfig aceApplicationConfig;
//
// private volatile int state = 0;
//
// private Config config;
//
// private Container container;
//
// private Server server;
//
// private Register register;
//
// @Override
// public void setConfigBean(AceApplicationConfig aceApplicationConfig) {
// this.aceApplicationConfig = aceApplicationConfig;
// }
//
// public void scan() {
// config = DefaultConfig.INSTANCE;
// if (aceApplicationConfig == null) {
// aceApplicationConfig = (AceApplicationConfig) config.configBeanParser(AceApplicationConfig.class).getConfigBean();
// }
// if (aceApplicationConfig.getName() == null && aceApplicationConfig.getName().trim().length() == 0) {
// throw new RuntimeException("ace.application.name must not empty ");
// }
//
// Set<Class<?>> baseSet = ScanUtil.findFileClass(basePage);
// String[] packages = aceApplicationConfig.getPackages().split(",");
// //扫描
// Set<Class<?>> classSet = ScanUtil.findFileClass(packages);
// classSet.addAll(baseSet);
// for (Class cls : classSet) {
// initAceServiceBean(cls);
// }
// config.configBeanParser(AceApplicationConfig.class).addObserver(this);
// initContainer(packages);
// }
//
// private void initAceServiceBean(Class cls) {
// if (cls.isAnnotationPresent(AceService.class)) {
// AceServiceBean aceServiceBean = new AceServiceBean();
// try {
// aceServiceBean.setInstance(cls.newInstance());
// AceService aceService = (AceService) cls.getAnnotation(AceService.class);
// aceServiceBean.setPath(aceService.path());
// register(aceServiceBean);
//
// } catch (InstantiationException e) {
// //TODO: 异常处理
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// //TODO: 异常处理
// e.printStackTrace();
// }
//
// }
//
// }
//
// /**
// * 初始化Method
// *
// * @param clazz aceService
// * @param method method
// */
// private void initAceServiceMethod(Class<?> clazz, Method method) throws IOException {
// for (AceHttpMethod aceHttpMethod : AceHttpMethod.values()) {
// if (method.isAnnotationPresent(aceHttpMethod.getAnnotationClazz())) {
// Context.putAceServiceMethodMap(clazz, aceHttpMethod, method);
// return;
// }
// }
// }
//
//
// private void initContainer(String... packages) {
// container = ExtendLoader.getExtendLoader(Container.class).getExtension(aceApplicationConfig.getContainer());
// container.init(packages);
// container.start();
// for (AceServiceBean aceServiceBean : Context.beans()) {
// Class cls = aceServiceBean.getInstance().getClass();
// Object bean = null;
// try {
// bean = container.getBean(cls);
// } catch (Exception ex) {
//
// }
// if (bean != null) {
// aceServiceBean.setInstance(bean);
// }
// }
// container.registerShutdownHook();
//
// }
//
//
// @Override
// public void update(Observable o, Object arg) {
//
// }
//
// public enum Event {
// START;
// }
//
//
// public void register(AceServiceBean... aceServiceBeans) {
// for (AceServiceBean aceServiceBean : aceServiceBeans) {
// Context.putAceServiceMap(aceServiceBean);
// Class cls = aceServiceBean.getInstance().getClass();
// for (Method method : cls.getMethods()) {
// try {
// initAceServiceMethod(cls, method);
// } catch (IOException e) {
// //TODO: 异常处理
// e.printStackTrace();
// }
// }
// }
// register = ExtendLoader.getExtendLoader(Register.class).getExtension(aceApplicationConfig.getRegister());
// register.setConfigBean((RegisterConfig) config.configBeanParser(RegisterConfig.class).getConfigBean());
// //TODO: 注册服务
// }
//
// public void start() {
//
// server = ExtendLoader.getExtendLoader(Server.class).getExtension(aceApplicationConfig.getServer());
//
// server.setConfigBean((AceServerConfig) config.configBeanParser(AceServerConfig.class).getConfigBean());
// Thread serverThread = new Thread(new Runnable() {
// @Override
// public void run() {
// try {
// server.start();
// } catch (Exception e) {
// // TODO:异常
// }
// }
// });
// serverThread.setDaemon(true);
// serverThread.start();
// config.export();
//
// }
//
//
// public void close() {
// Runtime.getRuntime().removeShutdownHook(new Thread(new Runnable() {
// @Override
// public void run() {
// synchronized (this) {
// server.close();
// container.stop();
// config.clean();
// state = 1;
// System.out.println("shutdown !!!");
// AceApplication.class.notifyAll();
// }
// }
// }));
//
// while (state == 0) {
// synchronized (this) {
// try {
// wait();
// } catch (InterruptedException e) {
//
// }
// }
// }
//
// //TODO:结束
// }
//
//
// }
|
import wiki.chenxun.ace.core.base.common.AceApplication;
|
package wiki.chenxun.ace.core;
/**
* 项目启动类
* Created by chenxun on 2017/4/7.
*/
public final class Main {
private Main() {
}
/**
* 入口
*
* @param args 启动参数
*/
public static void main(String[] args) {
|
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/common/AceApplication.java
// public class AceApplication implements ConfigBeanAware<AceApplicationConfig> {
//
// private String basePage = "wiki.chenxun.ace.core";
//
// private AceApplicationConfig aceApplicationConfig;
//
// private volatile int state = 0;
//
// private Config config;
//
// private Container container;
//
// private Server server;
//
// private Register register;
//
// @Override
// public void setConfigBean(AceApplicationConfig aceApplicationConfig) {
// this.aceApplicationConfig = aceApplicationConfig;
// }
//
// public void scan() {
// config = DefaultConfig.INSTANCE;
// if (aceApplicationConfig == null) {
// aceApplicationConfig = (AceApplicationConfig) config.configBeanParser(AceApplicationConfig.class).getConfigBean();
// }
// if (aceApplicationConfig.getName() == null && aceApplicationConfig.getName().trim().length() == 0) {
// throw new RuntimeException("ace.application.name must not empty ");
// }
//
// Set<Class<?>> baseSet = ScanUtil.findFileClass(basePage);
// String[] packages = aceApplicationConfig.getPackages().split(",");
// //扫描
// Set<Class<?>> classSet = ScanUtil.findFileClass(packages);
// classSet.addAll(baseSet);
// for (Class cls : classSet) {
// initAceServiceBean(cls);
// }
// config.configBeanParser(AceApplicationConfig.class).addObserver(this);
// initContainer(packages);
// }
//
// private void initAceServiceBean(Class cls) {
// if (cls.isAnnotationPresent(AceService.class)) {
// AceServiceBean aceServiceBean = new AceServiceBean();
// try {
// aceServiceBean.setInstance(cls.newInstance());
// AceService aceService = (AceService) cls.getAnnotation(AceService.class);
// aceServiceBean.setPath(aceService.path());
// register(aceServiceBean);
//
// } catch (InstantiationException e) {
// //TODO: 异常处理
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// //TODO: 异常处理
// e.printStackTrace();
// }
//
// }
//
// }
//
// /**
// * 初始化Method
// *
// * @param clazz aceService
// * @param method method
// */
// private void initAceServiceMethod(Class<?> clazz, Method method) throws IOException {
// for (AceHttpMethod aceHttpMethod : AceHttpMethod.values()) {
// if (method.isAnnotationPresent(aceHttpMethod.getAnnotationClazz())) {
// Context.putAceServiceMethodMap(clazz, aceHttpMethod, method);
// return;
// }
// }
// }
//
//
// private void initContainer(String... packages) {
// container = ExtendLoader.getExtendLoader(Container.class).getExtension(aceApplicationConfig.getContainer());
// container.init(packages);
// container.start();
// for (AceServiceBean aceServiceBean : Context.beans()) {
// Class cls = aceServiceBean.getInstance().getClass();
// Object bean = null;
// try {
// bean = container.getBean(cls);
// } catch (Exception ex) {
//
// }
// if (bean != null) {
// aceServiceBean.setInstance(bean);
// }
// }
// container.registerShutdownHook();
//
// }
//
//
// @Override
// public void update(Observable o, Object arg) {
//
// }
//
// public enum Event {
// START;
// }
//
//
// public void register(AceServiceBean... aceServiceBeans) {
// for (AceServiceBean aceServiceBean : aceServiceBeans) {
// Context.putAceServiceMap(aceServiceBean);
// Class cls = aceServiceBean.getInstance().getClass();
// for (Method method : cls.getMethods()) {
// try {
// initAceServiceMethod(cls, method);
// } catch (IOException e) {
// //TODO: 异常处理
// e.printStackTrace();
// }
// }
// }
// register = ExtendLoader.getExtendLoader(Register.class).getExtension(aceApplicationConfig.getRegister());
// register.setConfigBean((RegisterConfig) config.configBeanParser(RegisterConfig.class).getConfigBean());
// //TODO: 注册服务
// }
//
// public void start() {
//
// server = ExtendLoader.getExtendLoader(Server.class).getExtension(aceApplicationConfig.getServer());
//
// server.setConfigBean((AceServerConfig) config.configBeanParser(AceServerConfig.class).getConfigBean());
// Thread serverThread = new Thread(new Runnable() {
// @Override
// public void run() {
// try {
// server.start();
// } catch (Exception e) {
// // TODO:异常
// }
// }
// });
// serverThread.setDaemon(true);
// serverThread.start();
// config.export();
//
// }
//
//
// public void close() {
// Runtime.getRuntime().removeShutdownHook(new Thread(new Runnable() {
// @Override
// public void run() {
// synchronized (this) {
// server.close();
// container.stop();
// config.clean();
// state = 1;
// System.out.println("shutdown !!!");
// AceApplication.class.notifyAll();
// }
// }
// }));
//
// while (state == 0) {
// synchronized (this) {
// try {
// wait();
// } catch (InterruptedException e) {
//
// }
// }
// }
//
// //TODO:结束
// }
//
//
// }
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/Main.java
import wiki.chenxun.ace.core.base.common.AceApplication;
package wiki.chenxun.ace.core;
/**
* 项目启动类
* Created by chenxun on 2017/4/7.
*/
public final class Main {
private Main() {
}
/**
* 入口
*
* @param args 启动参数
*/
public static void main(String[] args) {
|
AceApplication aceApplication = new AceApplication();
|
ChenXun1989/ace
|
ace-examples/example-simple/src/test/java/wiki/chenxun/ace/examples/simple/test/Test.java
|
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/Main.java
// public final class Main {
//
// private Main() {
//
// }
//
// /**
// * 入口
// *
// * @param args 启动参数
// */
// public static void main(String[] args) {
//
// AceApplication aceApplication = new AceApplication();
// aceApplication.scan();
// aceApplication.start();
// aceApplication.close();
//
//
// }
//
//
// }
|
import wiki.chenxun.ace.core.Main;
import java.util.ArrayList;
import java.util.List;
|
package wiki.chenxun.ace.examples.simple.test;
/**
* @Description: Created by chenxun on 2017/4/9.
*/
public class Test {
public static void main(String[] args) {
|
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/Main.java
// public final class Main {
//
// private Main() {
//
// }
//
// /**
// * 入口
// *
// * @param args 启动参数
// */
// public static void main(String[] args) {
//
// AceApplication aceApplication = new AceApplication();
// aceApplication.scan();
// aceApplication.start();
// aceApplication.close();
//
//
// }
//
//
// }
// Path: ace-examples/example-simple/src/test/java/wiki/chenxun/ace/examples/simple/test/Test.java
import wiki.chenxun.ace.core.Main;
import java.util.ArrayList;
import java.util.List;
package wiki.chenxun.ace.examples.simple.test;
/**
* @Description: Created by chenxun on 2017/4/9.
*/
public class Test {
public static void main(String[] args) {
|
Main.main(args);
|
ChenXun1989/ace
|
ace-core/src/main/java/wiki/chenxun/ace/core/base/common/AceApplication.java
|
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/config/DefaultConfig.java
// public enum DefaultConfig implements Config {
//
// INSTANCE;
//
// /**
// * 配置类解析实例
// */
// private Map<Class, ConfigBeanParser> configInstances = new ConcurrentHashMap<>();
//
// private volatile ZooKeeper zooKeeper;
//
//
//
// @Override
// public ConfigBeanParser configBeanParser(Class cls) {
// ConfigBeanParser configBeanParser = configInstances.get(cls);
// if (configBeanParser == null) {
// configBeanParser = new ConfigBeanParser();
// configBeanParser.parser(cls);
// add(configBeanParser);
// }
// return configBeanParser;
//
// }
//
// @Override
// public void add(ConfigBeanParser parser) {
// configInstances.put(parser.getConfigBean().getClass(), parser);
// }
//
// @Override
// public synchronized void export() {
// if (zooKeeper != null) {
// return;
// }
// Thread thread = new Thread(new Runnable() {
// @Override
// public void run() {
// RegisterConfig registerConfig = (RegisterConfig) configInstances.get(RegisterConfig.class).getConfigBean();
// try {
// zooKeeper = new ZooKeeper(registerConfig.getUrl(), registerConfig.getTimeout(), new Watcher() {
// @Override
// public void process(WatchedEvent watchedEvent) {
//
// }
// });
// String ip = InetAddressUtil.getHostIp();
// AceServerConfig aceServerConfig = (AceServerConfig) configBeanParser(AceServerConfig.class).getConfigBean();
// String tmp = ip + ":" + aceServerConfig.getPort();
// for (ConfigBeanParser parser : configInstances.values()) {
// ConfigBean configBean = parser.getConfigBean().getClass().getAnnotation(ConfigBean.class);
// String path = configBean.value();
// path = ROOT_PATH + path;
// createNode(path);
// ObjectMapper om = new ObjectMapper();
// byte[] data = om.writer().writeValueAsBytes(parser.getConfigBean());
// zooKeeper.create(path + "/" + tmp, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
// }
//
//
// } catch (IOException e) {
// e.printStackTrace();
// } catch (InterruptedException e) {
// e.printStackTrace();
// } catch (KeeperException e) {
// e.printStackTrace();
// }
// }
// });
// thread.setName("ace-config");
// thread.setDaemon(true);
// thread.start();
// }
//
//
// private void createNode(String path) throws KeeperException, InterruptedException {
// String[] arr = path.split("/");
// StringBuilder stringBuffer = new StringBuilder();
// for (int i = 0; i < arr.length; i++) {
// if (arr[i] != null && arr[i].trim().length() > 0) {
// stringBuffer.append("/");
// stringBuffer.append(arr[i]);
// String node = stringBuffer.toString();
// Stat state = zooKeeper.exists(node, true);
// if (state == null) {
// zooKeeper.create(node, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// }
// }
//
// }
//
//
// }
//
// public void clean(){
// try {
// zooKeeper.close();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// };
//
// }
//
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/register/Register.java
// @Spi("zookeeper")
// public interface Register extends ConfigBeanAware<RegisterConfig> {
//
// String ROOT="/ace";
//
// void register();
//
// void unregister();
//
//
//
//
//
// }
//
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/remote/Server.java
// @Spi("netty")
// public interface Server extends ConfigBeanAware<AceServerConfig> {
//
//
//
// /**
// * 开启服务
// *
// * @throws Exception 异常基类
// */
// void start() throws Exception;
//
// void close();
//
//
// }
|
import wiki.chenxun.ace.core.base.annotations.AceHttpMethod;
import wiki.chenxun.ace.core.base.annotations.AceService;
import wiki.chenxun.ace.core.base.config.Config;
import wiki.chenxun.ace.core.base.config.ConfigBeanAware;
import wiki.chenxun.ace.core.base.config.DefaultConfig;
import wiki.chenxun.ace.core.base.container.Container;
import wiki.chenxun.ace.core.base.register.Register;
import wiki.chenxun.ace.core.base.register.RegisterConfig;
import wiki.chenxun.ace.core.base.remote.Server;
import wiki.chenxun.ace.core.base.support.ScanUtil;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Observable;
import java.util.Set;
|
package wiki.chenxun.ace.core.base.common;
/**
* @Description: Created by chenxun on 2017/4/21.
*/
public class AceApplication implements ConfigBeanAware<AceApplicationConfig> {
private String basePage = "wiki.chenxun.ace.core";
private AceApplicationConfig aceApplicationConfig;
private volatile int state = 0;
private Config config;
private Container container;
|
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/config/DefaultConfig.java
// public enum DefaultConfig implements Config {
//
// INSTANCE;
//
// /**
// * 配置类解析实例
// */
// private Map<Class, ConfigBeanParser> configInstances = new ConcurrentHashMap<>();
//
// private volatile ZooKeeper zooKeeper;
//
//
//
// @Override
// public ConfigBeanParser configBeanParser(Class cls) {
// ConfigBeanParser configBeanParser = configInstances.get(cls);
// if (configBeanParser == null) {
// configBeanParser = new ConfigBeanParser();
// configBeanParser.parser(cls);
// add(configBeanParser);
// }
// return configBeanParser;
//
// }
//
// @Override
// public void add(ConfigBeanParser parser) {
// configInstances.put(parser.getConfigBean().getClass(), parser);
// }
//
// @Override
// public synchronized void export() {
// if (zooKeeper != null) {
// return;
// }
// Thread thread = new Thread(new Runnable() {
// @Override
// public void run() {
// RegisterConfig registerConfig = (RegisterConfig) configInstances.get(RegisterConfig.class).getConfigBean();
// try {
// zooKeeper = new ZooKeeper(registerConfig.getUrl(), registerConfig.getTimeout(), new Watcher() {
// @Override
// public void process(WatchedEvent watchedEvent) {
//
// }
// });
// String ip = InetAddressUtil.getHostIp();
// AceServerConfig aceServerConfig = (AceServerConfig) configBeanParser(AceServerConfig.class).getConfigBean();
// String tmp = ip + ":" + aceServerConfig.getPort();
// for (ConfigBeanParser parser : configInstances.values()) {
// ConfigBean configBean = parser.getConfigBean().getClass().getAnnotation(ConfigBean.class);
// String path = configBean.value();
// path = ROOT_PATH + path;
// createNode(path);
// ObjectMapper om = new ObjectMapper();
// byte[] data = om.writer().writeValueAsBytes(parser.getConfigBean());
// zooKeeper.create(path + "/" + tmp, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
// }
//
//
// } catch (IOException e) {
// e.printStackTrace();
// } catch (InterruptedException e) {
// e.printStackTrace();
// } catch (KeeperException e) {
// e.printStackTrace();
// }
// }
// });
// thread.setName("ace-config");
// thread.setDaemon(true);
// thread.start();
// }
//
//
// private void createNode(String path) throws KeeperException, InterruptedException {
// String[] arr = path.split("/");
// StringBuilder stringBuffer = new StringBuilder();
// for (int i = 0; i < arr.length; i++) {
// if (arr[i] != null && arr[i].trim().length() > 0) {
// stringBuffer.append("/");
// stringBuffer.append(arr[i]);
// String node = stringBuffer.toString();
// Stat state = zooKeeper.exists(node, true);
// if (state == null) {
// zooKeeper.create(node, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// }
// }
//
// }
//
//
// }
//
// public void clean(){
// try {
// zooKeeper.close();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// };
//
// }
//
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/register/Register.java
// @Spi("zookeeper")
// public interface Register extends ConfigBeanAware<RegisterConfig> {
//
// String ROOT="/ace";
//
// void register();
//
// void unregister();
//
//
//
//
//
// }
//
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/remote/Server.java
// @Spi("netty")
// public interface Server extends ConfigBeanAware<AceServerConfig> {
//
//
//
// /**
// * 开启服务
// *
// * @throws Exception 异常基类
// */
// void start() throws Exception;
//
// void close();
//
//
// }
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/common/AceApplication.java
import wiki.chenxun.ace.core.base.annotations.AceHttpMethod;
import wiki.chenxun.ace.core.base.annotations.AceService;
import wiki.chenxun.ace.core.base.config.Config;
import wiki.chenxun.ace.core.base.config.ConfigBeanAware;
import wiki.chenxun.ace.core.base.config.DefaultConfig;
import wiki.chenxun.ace.core.base.container.Container;
import wiki.chenxun.ace.core.base.register.Register;
import wiki.chenxun.ace.core.base.register.RegisterConfig;
import wiki.chenxun.ace.core.base.remote.Server;
import wiki.chenxun.ace.core.base.support.ScanUtil;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Observable;
import java.util.Set;
package wiki.chenxun.ace.core.base.common;
/**
* @Description: Created by chenxun on 2017/4/21.
*/
public class AceApplication implements ConfigBeanAware<AceApplicationConfig> {
private String basePage = "wiki.chenxun.ace.core";
private AceApplicationConfig aceApplicationConfig;
private volatile int state = 0;
private Config config;
private Container container;
|
private Server server;
|
ChenXun1989/ace
|
ace-core/src/main/java/wiki/chenxun/ace/core/base/common/AceApplication.java
|
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/config/DefaultConfig.java
// public enum DefaultConfig implements Config {
//
// INSTANCE;
//
// /**
// * 配置类解析实例
// */
// private Map<Class, ConfigBeanParser> configInstances = new ConcurrentHashMap<>();
//
// private volatile ZooKeeper zooKeeper;
//
//
//
// @Override
// public ConfigBeanParser configBeanParser(Class cls) {
// ConfigBeanParser configBeanParser = configInstances.get(cls);
// if (configBeanParser == null) {
// configBeanParser = new ConfigBeanParser();
// configBeanParser.parser(cls);
// add(configBeanParser);
// }
// return configBeanParser;
//
// }
//
// @Override
// public void add(ConfigBeanParser parser) {
// configInstances.put(parser.getConfigBean().getClass(), parser);
// }
//
// @Override
// public synchronized void export() {
// if (zooKeeper != null) {
// return;
// }
// Thread thread = new Thread(new Runnable() {
// @Override
// public void run() {
// RegisterConfig registerConfig = (RegisterConfig) configInstances.get(RegisterConfig.class).getConfigBean();
// try {
// zooKeeper = new ZooKeeper(registerConfig.getUrl(), registerConfig.getTimeout(), new Watcher() {
// @Override
// public void process(WatchedEvent watchedEvent) {
//
// }
// });
// String ip = InetAddressUtil.getHostIp();
// AceServerConfig aceServerConfig = (AceServerConfig) configBeanParser(AceServerConfig.class).getConfigBean();
// String tmp = ip + ":" + aceServerConfig.getPort();
// for (ConfigBeanParser parser : configInstances.values()) {
// ConfigBean configBean = parser.getConfigBean().getClass().getAnnotation(ConfigBean.class);
// String path = configBean.value();
// path = ROOT_PATH + path;
// createNode(path);
// ObjectMapper om = new ObjectMapper();
// byte[] data = om.writer().writeValueAsBytes(parser.getConfigBean());
// zooKeeper.create(path + "/" + tmp, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
// }
//
//
// } catch (IOException e) {
// e.printStackTrace();
// } catch (InterruptedException e) {
// e.printStackTrace();
// } catch (KeeperException e) {
// e.printStackTrace();
// }
// }
// });
// thread.setName("ace-config");
// thread.setDaemon(true);
// thread.start();
// }
//
//
// private void createNode(String path) throws KeeperException, InterruptedException {
// String[] arr = path.split("/");
// StringBuilder stringBuffer = new StringBuilder();
// for (int i = 0; i < arr.length; i++) {
// if (arr[i] != null && arr[i].trim().length() > 0) {
// stringBuffer.append("/");
// stringBuffer.append(arr[i]);
// String node = stringBuffer.toString();
// Stat state = zooKeeper.exists(node, true);
// if (state == null) {
// zooKeeper.create(node, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// }
// }
//
// }
//
//
// }
//
// public void clean(){
// try {
// zooKeeper.close();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// };
//
// }
//
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/register/Register.java
// @Spi("zookeeper")
// public interface Register extends ConfigBeanAware<RegisterConfig> {
//
// String ROOT="/ace";
//
// void register();
//
// void unregister();
//
//
//
//
//
// }
//
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/remote/Server.java
// @Spi("netty")
// public interface Server extends ConfigBeanAware<AceServerConfig> {
//
//
//
// /**
// * 开启服务
// *
// * @throws Exception 异常基类
// */
// void start() throws Exception;
//
// void close();
//
//
// }
|
import wiki.chenxun.ace.core.base.annotations.AceHttpMethod;
import wiki.chenxun.ace.core.base.annotations.AceService;
import wiki.chenxun.ace.core.base.config.Config;
import wiki.chenxun.ace.core.base.config.ConfigBeanAware;
import wiki.chenxun.ace.core.base.config.DefaultConfig;
import wiki.chenxun.ace.core.base.container.Container;
import wiki.chenxun.ace.core.base.register.Register;
import wiki.chenxun.ace.core.base.register.RegisterConfig;
import wiki.chenxun.ace.core.base.remote.Server;
import wiki.chenxun.ace.core.base.support.ScanUtil;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Observable;
import java.util.Set;
|
package wiki.chenxun.ace.core.base.common;
/**
* @Description: Created by chenxun on 2017/4/21.
*/
public class AceApplication implements ConfigBeanAware<AceApplicationConfig> {
private String basePage = "wiki.chenxun.ace.core";
private AceApplicationConfig aceApplicationConfig;
private volatile int state = 0;
private Config config;
private Container container;
private Server server;
|
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/config/DefaultConfig.java
// public enum DefaultConfig implements Config {
//
// INSTANCE;
//
// /**
// * 配置类解析实例
// */
// private Map<Class, ConfigBeanParser> configInstances = new ConcurrentHashMap<>();
//
// private volatile ZooKeeper zooKeeper;
//
//
//
// @Override
// public ConfigBeanParser configBeanParser(Class cls) {
// ConfigBeanParser configBeanParser = configInstances.get(cls);
// if (configBeanParser == null) {
// configBeanParser = new ConfigBeanParser();
// configBeanParser.parser(cls);
// add(configBeanParser);
// }
// return configBeanParser;
//
// }
//
// @Override
// public void add(ConfigBeanParser parser) {
// configInstances.put(parser.getConfigBean().getClass(), parser);
// }
//
// @Override
// public synchronized void export() {
// if (zooKeeper != null) {
// return;
// }
// Thread thread = new Thread(new Runnable() {
// @Override
// public void run() {
// RegisterConfig registerConfig = (RegisterConfig) configInstances.get(RegisterConfig.class).getConfigBean();
// try {
// zooKeeper = new ZooKeeper(registerConfig.getUrl(), registerConfig.getTimeout(), new Watcher() {
// @Override
// public void process(WatchedEvent watchedEvent) {
//
// }
// });
// String ip = InetAddressUtil.getHostIp();
// AceServerConfig aceServerConfig = (AceServerConfig) configBeanParser(AceServerConfig.class).getConfigBean();
// String tmp = ip + ":" + aceServerConfig.getPort();
// for (ConfigBeanParser parser : configInstances.values()) {
// ConfigBean configBean = parser.getConfigBean().getClass().getAnnotation(ConfigBean.class);
// String path = configBean.value();
// path = ROOT_PATH + path;
// createNode(path);
// ObjectMapper om = new ObjectMapper();
// byte[] data = om.writer().writeValueAsBytes(parser.getConfigBean());
// zooKeeper.create(path + "/" + tmp, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
// }
//
//
// } catch (IOException e) {
// e.printStackTrace();
// } catch (InterruptedException e) {
// e.printStackTrace();
// } catch (KeeperException e) {
// e.printStackTrace();
// }
// }
// });
// thread.setName("ace-config");
// thread.setDaemon(true);
// thread.start();
// }
//
//
// private void createNode(String path) throws KeeperException, InterruptedException {
// String[] arr = path.split("/");
// StringBuilder stringBuffer = new StringBuilder();
// for (int i = 0; i < arr.length; i++) {
// if (arr[i] != null && arr[i].trim().length() > 0) {
// stringBuffer.append("/");
// stringBuffer.append(arr[i]);
// String node = stringBuffer.toString();
// Stat state = zooKeeper.exists(node, true);
// if (state == null) {
// zooKeeper.create(node, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// }
// }
//
// }
//
//
// }
//
// public void clean(){
// try {
// zooKeeper.close();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// };
//
// }
//
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/register/Register.java
// @Spi("zookeeper")
// public interface Register extends ConfigBeanAware<RegisterConfig> {
//
// String ROOT="/ace";
//
// void register();
//
// void unregister();
//
//
//
//
//
// }
//
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/remote/Server.java
// @Spi("netty")
// public interface Server extends ConfigBeanAware<AceServerConfig> {
//
//
//
// /**
// * 开启服务
// *
// * @throws Exception 异常基类
// */
// void start() throws Exception;
//
// void close();
//
//
// }
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/common/AceApplication.java
import wiki.chenxun.ace.core.base.annotations.AceHttpMethod;
import wiki.chenxun.ace.core.base.annotations.AceService;
import wiki.chenxun.ace.core.base.config.Config;
import wiki.chenxun.ace.core.base.config.ConfigBeanAware;
import wiki.chenxun.ace.core.base.config.DefaultConfig;
import wiki.chenxun.ace.core.base.container.Container;
import wiki.chenxun.ace.core.base.register.Register;
import wiki.chenxun.ace.core.base.register.RegisterConfig;
import wiki.chenxun.ace.core.base.remote.Server;
import wiki.chenxun.ace.core.base.support.ScanUtil;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Observable;
import java.util.Set;
package wiki.chenxun.ace.core.base.common;
/**
* @Description: Created by chenxun on 2017/4/21.
*/
public class AceApplication implements ConfigBeanAware<AceApplicationConfig> {
private String basePage = "wiki.chenxun.ace.core";
private AceApplicationConfig aceApplicationConfig;
private volatile int state = 0;
private Config config;
private Container container;
private Server server;
|
private Register register;
|
ChenXun1989/ace
|
ace-core/src/main/java/wiki/chenxun/ace/core/base/common/AceApplication.java
|
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/config/DefaultConfig.java
// public enum DefaultConfig implements Config {
//
// INSTANCE;
//
// /**
// * 配置类解析实例
// */
// private Map<Class, ConfigBeanParser> configInstances = new ConcurrentHashMap<>();
//
// private volatile ZooKeeper zooKeeper;
//
//
//
// @Override
// public ConfigBeanParser configBeanParser(Class cls) {
// ConfigBeanParser configBeanParser = configInstances.get(cls);
// if (configBeanParser == null) {
// configBeanParser = new ConfigBeanParser();
// configBeanParser.parser(cls);
// add(configBeanParser);
// }
// return configBeanParser;
//
// }
//
// @Override
// public void add(ConfigBeanParser parser) {
// configInstances.put(parser.getConfigBean().getClass(), parser);
// }
//
// @Override
// public synchronized void export() {
// if (zooKeeper != null) {
// return;
// }
// Thread thread = new Thread(new Runnable() {
// @Override
// public void run() {
// RegisterConfig registerConfig = (RegisterConfig) configInstances.get(RegisterConfig.class).getConfigBean();
// try {
// zooKeeper = new ZooKeeper(registerConfig.getUrl(), registerConfig.getTimeout(), new Watcher() {
// @Override
// public void process(WatchedEvent watchedEvent) {
//
// }
// });
// String ip = InetAddressUtil.getHostIp();
// AceServerConfig aceServerConfig = (AceServerConfig) configBeanParser(AceServerConfig.class).getConfigBean();
// String tmp = ip + ":" + aceServerConfig.getPort();
// for (ConfigBeanParser parser : configInstances.values()) {
// ConfigBean configBean = parser.getConfigBean().getClass().getAnnotation(ConfigBean.class);
// String path = configBean.value();
// path = ROOT_PATH + path;
// createNode(path);
// ObjectMapper om = new ObjectMapper();
// byte[] data = om.writer().writeValueAsBytes(parser.getConfigBean());
// zooKeeper.create(path + "/" + tmp, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
// }
//
//
// } catch (IOException e) {
// e.printStackTrace();
// } catch (InterruptedException e) {
// e.printStackTrace();
// } catch (KeeperException e) {
// e.printStackTrace();
// }
// }
// });
// thread.setName("ace-config");
// thread.setDaemon(true);
// thread.start();
// }
//
//
// private void createNode(String path) throws KeeperException, InterruptedException {
// String[] arr = path.split("/");
// StringBuilder stringBuffer = new StringBuilder();
// for (int i = 0; i < arr.length; i++) {
// if (arr[i] != null && arr[i].trim().length() > 0) {
// stringBuffer.append("/");
// stringBuffer.append(arr[i]);
// String node = stringBuffer.toString();
// Stat state = zooKeeper.exists(node, true);
// if (state == null) {
// zooKeeper.create(node, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// }
// }
//
// }
//
//
// }
//
// public void clean(){
// try {
// zooKeeper.close();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// };
//
// }
//
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/register/Register.java
// @Spi("zookeeper")
// public interface Register extends ConfigBeanAware<RegisterConfig> {
//
// String ROOT="/ace";
//
// void register();
//
// void unregister();
//
//
//
//
//
// }
//
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/remote/Server.java
// @Spi("netty")
// public interface Server extends ConfigBeanAware<AceServerConfig> {
//
//
//
// /**
// * 开启服务
// *
// * @throws Exception 异常基类
// */
// void start() throws Exception;
//
// void close();
//
//
// }
|
import wiki.chenxun.ace.core.base.annotations.AceHttpMethod;
import wiki.chenxun.ace.core.base.annotations.AceService;
import wiki.chenxun.ace.core.base.config.Config;
import wiki.chenxun.ace.core.base.config.ConfigBeanAware;
import wiki.chenxun.ace.core.base.config.DefaultConfig;
import wiki.chenxun.ace.core.base.container.Container;
import wiki.chenxun.ace.core.base.register.Register;
import wiki.chenxun.ace.core.base.register.RegisterConfig;
import wiki.chenxun.ace.core.base.remote.Server;
import wiki.chenxun.ace.core.base.support.ScanUtil;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Observable;
import java.util.Set;
|
package wiki.chenxun.ace.core.base.common;
/**
* @Description: Created by chenxun on 2017/4/21.
*/
public class AceApplication implements ConfigBeanAware<AceApplicationConfig> {
private String basePage = "wiki.chenxun.ace.core";
private AceApplicationConfig aceApplicationConfig;
private volatile int state = 0;
private Config config;
private Container container;
private Server server;
private Register register;
@Override
public void setConfigBean(AceApplicationConfig aceApplicationConfig) {
this.aceApplicationConfig = aceApplicationConfig;
}
public void scan() {
|
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/config/DefaultConfig.java
// public enum DefaultConfig implements Config {
//
// INSTANCE;
//
// /**
// * 配置类解析实例
// */
// private Map<Class, ConfigBeanParser> configInstances = new ConcurrentHashMap<>();
//
// private volatile ZooKeeper zooKeeper;
//
//
//
// @Override
// public ConfigBeanParser configBeanParser(Class cls) {
// ConfigBeanParser configBeanParser = configInstances.get(cls);
// if (configBeanParser == null) {
// configBeanParser = new ConfigBeanParser();
// configBeanParser.parser(cls);
// add(configBeanParser);
// }
// return configBeanParser;
//
// }
//
// @Override
// public void add(ConfigBeanParser parser) {
// configInstances.put(parser.getConfigBean().getClass(), parser);
// }
//
// @Override
// public synchronized void export() {
// if (zooKeeper != null) {
// return;
// }
// Thread thread = new Thread(new Runnable() {
// @Override
// public void run() {
// RegisterConfig registerConfig = (RegisterConfig) configInstances.get(RegisterConfig.class).getConfigBean();
// try {
// zooKeeper = new ZooKeeper(registerConfig.getUrl(), registerConfig.getTimeout(), new Watcher() {
// @Override
// public void process(WatchedEvent watchedEvent) {
//
// }
// });
// String ip = InetAddressUtil.getHostIp();
// AceServerConfig aceServerConfig = (AceServerConfig) configBeanParser(AceServerConfig.class).getConfigBean();
// String tmp = ip + ":" + aceServerConfig.getPort();
// for (ConfigBeanParser parser : configInstances.values()) {
// ConfigBean configBean = parser.getConfigBean().getClass().getAnnotation(ConfigBean.class);
// String path = configBean.value();
// path = ROOT_PATH + path;
// createNode(path);
// ObjectMapper om = new ObjectMapper();
// byte[] data = om.writer().writeValueAsBytes(parser.getConfigBean());
// zooKeeper.create(path + "/" + tmp, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
// }
//
//
// } catch (IOException e) {
// e.printStackTrace();
// } catch (InterruptedException e) {
// e.printStackTrace();
// } catch (KeeperException e) {
// e.printStackTrace();
// }
// }
// });
// thread.setName("ace-config");
// thread.setDaemon(true);
// thread.start();
// }
//
//
// private void createNode(String path) throws KeeperException, InterruptedException {
// String[] arr = path.split("/");
// StringBuilder stringBuffer = new StringBuilder();
// for (int i = 0; i < arr.length; i++) {
// if (arr[i] != null && arr[i].trim().length() > 0) {
// stringBuffer.append("/");
// stringBuffer.append(arr[i]);
// String node = stringBuffer.toString();
// Stat state = zooKeeper.exists(node, true);
// if (state == null) {
// zooKeeper.create(node, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// }
// }
//
// }
//
//
// }
//
// public void clean(){
// try {
// zooKeeper.close();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// };
//
// }
//
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/register/Register.java
// @Spi("zookeeper")
// public interface Register extends ConfigBeanAware<RegisterConfig> {
//
// String ROOT="/ace";
//
// void register();
//
// void unregister();
//
//
//
//
//
// }
//
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/remote/Server.java
// @Spi("netty")
// public interface Server extends ConfigBeanAware<AceServerConfig> {
//
//
//
// /**
// * 开启服务
// *
// * @throws Exception 异常基类
// */
// void start() throws Exception;
//
// void close();
//
//
// }
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/common/AceApplication.java
import wiki.chenxun.ace.core.base.annotations.AceHttpMethod;
import wiki.chenxun.ace.core.base.annotations.AceService;
import wiki.chenxun.ace.core.base.config.Config;
import wiki.chenxun.ace.core.base.config.ConfigBeanAware;
import wiki.chenxun.ace.core.base.config.DefaultConfig;
import wiki.chenxun.ace.core.base.container.Container;
import wiki.chenxun.ace.core.base.register.Register;
import wiki.chenxun.ace.core.base.register.RegisterConfig;
import wiki.chenxun.ace.core.base.remote.Server;
import wiki.chenxun.ace.core.base.support.ScanUtil;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Observable;
import java.util.Set;
package wiki.chenxun.ace.core.base.common;
/**
* @Description: Created by chenxun on 2017/4/21.
*/
public class AceApplication implements ConfigBeanAware<AceApplicationConfig> {
private String basePage = "wiki.chenxun.ace.core";
private AceApplicationConfig aceApplicationConfig;
private volatile int state = 0;
private Config config;
private Container container;
private Server server;
private Register register;
@Override
public void setConfigBean(AceApplicationConfig aceApplicationConfig) {
this.aceApplicationConfig = aceApplicationConfig;
}
public void scan() {
|
config = DefaultConfig.INSTANCE;
|
ChenXun1989/ace
|
ace-core/src/test/java/wiki/chenxun/ace/test/TestChar.java
|
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/common/AceApplicationConfig.java
// @Data
// @ConfigBean(AceApplicationConfig.PREFIX)
// public class AceApplicationConfig {
//
//
// public static final String PREFIX = "ace.application";
//
// private String name;
//
// private String dispatch;
//
// private String server;
//
// private String packages ="wiki.chenxun.ace.core";
//
// private String container;
//
// private String register;
//
// }
|
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.BeanSerializer;
import org.springframework.aop.framework.AopContext;
import wiki.chenxun.ace.core.base.common.AceApplicationConfig;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.regex.Pattern;
|
package wiki.chenxun.ace.test;
/**
* @Description: Created by chenxun on 2017/4/11.
*/
public class TestChar {
public static void main(String[] args) throws IOException {
|
// Path: ace-core/src/main/java/wiki/chenxun/ace/core/base/common/AceApplicationConfig.java
// @Data
// @ConfigBean(AceApplicationConfig.PREFIX)
// public class AceApplicationConfig {
//
//
// public static final String PREFIX = "ace.application";
//
// private String name;
//
// private String dispatch;
//
// private String server;
//
// private String packages ="wiki.chenxun.ace.core";
//
// private String container;
//
// private String register;
//
// }
// Path: ace-core/src/test/java/wiki/chenxun/ace/test/TestChar.java
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.BeanSerializer;
import org.springframework.aop.framework.AopContext;
import wiki.chenxun.ace.core.base.common.AceApplicationConfig;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.regex.Pattern;
package wiki.chenxun.ace.test;
/**
* @Description: Created by chenxun on 2017/4/11.
*/
public class TestChar {
public static void main(String[] args) throws IOException {
|
AceApplicationConfig aceApplicationConfig=new AceApplicationConfig();
|
alexgamas/treinamento-spring-boot
|
treinamento_5/src/main/java/br/com/gamas/treinamento/service/InscricaoService.java
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Situacao.java
// public enum Situacao {
// PENDENTE(1, "Pendente de avaliação"),
// APROVADO(2, "Aprovado"),
// REPROVADO(3, "Reprovado");
//
// private int codigo;
// private String descricao;
//
// Situacao(int codigo, String descricao) {
// this.codigo = codigo;
// this.descricao = descricao;
// }
//
// public int getCodigo() {
// return codigo;
// }
//
// public String getDescricao() {
// return descricao;
// }
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/repository/InscricaoRepository.java
// @Repository
// public interface InscricaoRepository extends JpaRepository<Inscricao, Long> {
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/service/mail/MailService.java
// @Service
// public class MailService {
//
// @Autowired
// private JavaMailSender javaMailSender;
//
// //@Async
// public void sendMail(String to, String subject, String msg){
// SimpleMailMessage smm = new SimpleMailMessage();
// smm.setTo(to);
// smm.setSubject(subject);
// smm.setText(msg);
// javaMailSender.send(smm);
// }
// }
|
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.Situacao;
import br.com.gamas.treinamento.repository.InscricaoRepository;
import br.com.gamas.treinamento.service.mail.MailService;
|
package br.com.gamas.treinamento.service;
@Service
public class InscricaoService {
@Autowired
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Situacao.java
// public enum Situacao {
// PENDENTE(1, "Pendente de avaliação"),
// APROVADO(2, "Aprovado"),
// REPROVADO(3, "Reprovado");
//
// private int codigo;
// private String descricao;
//
// Situacao(int codigo, String descricao) {
// this.codigo = codigo;
// this.descricao = descricao;
// }
//
// public int getCodigo() {
// return codigo;
// }
//
// public String getDescricao() {
// return descricao;
// }
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/repository/InscricaoRepository.java
// @Repository
// public interface InscricaoRepository extends JpaRepository<Inscricao, Long> {
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/service/mail/MailService.java
// @Service
// public class MailService {
//
// @Autowired
// private JavaMailSender javaMailSender;
//
// //@Async
// public void sendMail(String to, String subject, String msg){
// SimpleMailMessage smm = new SimpleMailMessage();
// smm.setTo(to);
// smm.setSubject(subject);
// smm.setText(msg);
// javaMailSender.send(smm);
// }
// }
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/service/InscricaoService.java
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.Situacao;
import br.com.gamas.treinamento.repository.InscricaoRepository;
import br.com.gamas.treinamento.service.mail.MailService;
package br.com.gamas.treinamento.service;
@Service
public class InscricaoService {
@Autowired
|
private InscricaoRepository inscricaoRepository;
|
alexgamas/treinamento-spring-boot
|
treinamento_5/src/main/java/br/com/gamas/treinamento/service/InscricaoService.java
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Situacao.java
// public enum Situacao {
// PENDENTE(1, "Pendente de avaliação"),
// APROVADO(2, "Aprovado"),
// REPROVADO(3, "Reprovado");
//
// private int codigo;
// private String descricao;
//
// Situacao(int codigo, String descricao) {
// this.codigo = codigo;
// this.descricao = descricao;
// }
//
// public int getCodigo() {
// return codigo;
// }
//
// public String getDescricao() {
// return descricao;
// }
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/repository/InscricaoRepository.java
// @Repository
// public interface InscricaoRepository extends JpaRepository<Inscricao, Long> {
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/service/mail/MailService.java
// @Service
// public class MailService {
//
// @Autowired
// private JavaMailSender javaMailSender;
//
// //@Async
// public void sendMail(String to, String subject, String msg){
// SimpleMailMessage smm = new SimpleMailMessage();
// smm.setTo(to);
// smm.setSubject(subject);
// smm.setText(msg);
// javaMailSender.send(smm);
// }
// }
|
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.Situacao;
import br.com.gamas.treinamento.repository.InscricaoRepository;
import br.com.gamas.treinamento.service.mail.MailService;
|
package br.com.gamas.treinamento.service;
@Service
public class InscricaoService {
@Autowired
private InscricaoRepository inscricaoRepository;
@Autowired
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Situacao.java
// public enum Situacao {
// PENDENTE(1, "Pendente de avaliação"),
// APROVADO(2, "Aprovado"),
// REPROVADO(3, "Reprovado");
//
// private int codigo;
// private String descricao;
//
// Situacao(int codigo, String descricao) {
// this.codigo = codigo;
// this.descricao = descricao;
// }
//
// public int getCodigo() {
// return codigo;
// }
//
// public String getDescricao() {
// return descricao;
// }
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/repository/InscricaoRepository.java
// @Repository
// public interface InscricaoRepository extends JpaRepository<Inscricao, Long> {
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/service/mail/MailService.java
// @Service
// public class MailService {
//
// @Autowired
// private JavaMailSender javaMailSender;
//
// //@Async
// public void sendMail(String to, String subject, String msg){
// SimpleMailMessage smm = new SimpleMailMessage();
// smm.setTo(to);
// smm.setSubject(subject);
// smm.setText(msg);
// javaMailSender.send(smm);
// }
// }
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/service/InscricaoService.java
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.Situacao;
import br.com.gamas.treinamento.repository.InscricaoRepository;
import br.com.gamas.treinamento.service.mail.MailService;
package br.com.gamas.treinamento.service;
@Service
public class InscricaoService {
@Autowired
private InscricaoRepository inscricaoRepository;
@Autowired
|
private MailService mailService;
|
alexgamas/treinamento-spring-boot
|
treinamento_5/src/main/java/br/com/gamas/treinamento/service/InscricaoService.java
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Situacao.java
// public enum Situacao {
// PENDENTE(1, "Pendente de avaliação"),
// APROVADO(2, "Aprovado"),
// REPROVADO(3, "Reprovado");
//
// private int codigo;
// private String descricao;
//
// Situacao(int codigo, String descricao) {
// this.codigo = codigo;
// this.descricao = descricao;
// }
//
// public int getCodigo() {
// return codigo;
// }
//
// public String getDescricao() {
// return descricao;
// }
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/repository/InscricaoRepository.java
// @Repository
// public interface InscricaoRepository extends JpaRepository<Inscricao, Long> {
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/service/mail/MailService.java
// @Service
// public class MailService {
//
// @Autowired
// private JavaMailSender javaMailSender;
//
// //@Async
// public void sendMail(String to, String subject, String msg){
// SimpleMailMessage smm = new SimpleMailMessage();
// smm.setTo(to);
// smm.setSubject(subject);
// smm.setText(msg);
// javaMailSender.send(smm);
// }
// }
|
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.Situacao;
import br.com.gamas.treinamento.repository.InscricaoRepository;
import br.com.gamas.treinamento.service.mail.MailService;
|
package br.com.gamas.treinamento.service;
@Service
public class InscricaoService {
@Autowired
private InscricaoRepository inscricaoRepository;
@Autowired
private MailService mailService;
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Situacao.java
// public enum Situacao {
// PENDENTE(1, "Pendente de avaliação"),
// APROVADO(2, "Aprovado"),
// REPROVADO(3, "Reprovado");
//
// private int codigo;
// private String descricao;
//
// Situacao(int codigo, String descricao) {
// this.codigo = codigo;
// this.descricao = descricao;
// }
//
// public int getCodigo() {
// return codigo;
// }
//
// public String getDescricao() {
// return descricao;
// }
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/repository/InscricaoRepository.java
// @Repository
// public interface InscricaoRepository extends JpaRepository<Inscricao, Long> {
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/service/mail/MailService.java
// @Service
// public class MailService {
//
// @Autowired
// private JavaMailSender javaMailSender;
//
// //@Async
// public void sendMail(String to, String subject, String msg){
// SimpleMailMessage smm = new SimpleMailMessage();
// smm.setTo(to);
// smm.setSubject(subject);
// smm.setText(msg);
// javaMailSender.send(smm);
// }
// }
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/service/InscricaoService.java
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.Situacao;
import br.com.gamas.treinamento.repository.InscricaoRepository;
import br.com.gamas.treinamento.service.mail.MailService;
package br.com.gamas.treinamento.service;
@Service
public class InscricaoService {
@Autowired
private InscricaoRepository inscricaoRepository;
@Autowired
private MailService mailService;
|
public Inscricao buscarInscricaoPorId(Long id) {
|
alexgamas/treinamento-spring-boot
|
treinamento_5/src/main/java/br/com/gamas/treinamento/service/InscricaoService.java
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Situacao.java
// public enum Situacao {
// PENDENTE(1, "Pendente de avaliação"),
// APROVADO(2, "Aprovado"),
// REPROVADO(3, "Reprovado");
//
// private int codigo;
// private String descricao;
//
// Situacao(int codigo, String descricao) {
// this.codigo = codigo;
// this.descricao = descricao;
// }
//
// public int getCodigo() {
// return codigo;
// }
//
// public String getDescricao() {
// return descricao;
// }
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/repository/InscricaoRepository.java
// @Repository
// public interface InscricaoRepository extends JpaRepository<Inscricao, Long> {
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/service/mail/MailService.java
// @Service
// public class MailService {
//
// @Autowired
// private JavaMailSender javaMailSender;
//
// //@Async
// public void sendMail(String to, String subject, String msg){
// SimpleMailMessage smm = new SimpleMailMessage();
// smm.setTo(to);
// smm.setSubject(subject);
// smm.setText(msg);
// javaMailSender.send(smm);
// }
// }
|
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.Situacao;
import br.com.gamas.treinamento.repository.InscricaoRepository;
import br.com.gamas.treinamento.service.mail.MailService;
|
package br.com.gamas.treinamento.service;
@Service
public class InscricaoService {
@Autowired
private InscricaoRepository inscricaoRepository;
@Autowired
private MailService mailService;
public Inscricao buscarInscricaoPorId(Long id) {
return inscricaoRepository.findOne(id);
}
public void save(Inscricao inscricao) {
inscricaoRepository.save(inscricao);
mailService.sendMail(inscricao.getEmail(), "Cadastro realizado", "Seu cadastro foi criado com sucesso, aguarde parecer.");
}
public List<Inscricao> findAll() {
return inscricaoRepository.findAll();
}
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Situacao.java
// public enum Situacao {
// PENDENTE(1, "Pendente de avaliação"),
// APROVADO(2, "Aprovado"),
// REPROVADO(3, "Reprovado");
//
// private int codigo;
// private String descricao;
//
// Situacao(int codigo, String descricao) {
// this.codigo = codigo;
// this.descricao = descricao;
// }
//
// public int getCodigo() {
// return codigo;
// }
//
// public String getDescricao() {
// return descricao;
// }
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/repository/InscricaoRepository.java
// @Repository
// public interface InscricaoRepository extends JpaRepository<Inscricao, Long> {
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/service/mail/MailService.java
// @Service
// public class MailService {
//
// @Autowired
// private JavaMailSender javaMailSender;
//
// //@Async
// public void sendMail(String to, String subject, String msg){
// SimpleMailMessage smm = new SimpleMailMessage();
// smm.setTo(to);
// smm.setSubject(subject);
// smm.setText(msg);
// javaMailSender.send(smm);
// }
// }
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/service/InscricaoService.java
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.Situacao;
import br.com.gamas.treinamento.repository.InscricaoRepository;
import br.com.gamas.treinamento.service.mail.MailService;
package br.com.gamas.treinamento.service;
@Service
public class InscricaoService {
@Autowired
private InscricaoRepository inscricaoRepository;
@Autowired
private MailService mailService;
public Inscricao buscarInscricaoPorId(Long id) {
return inscricaoRepository.findOne(id);
}
public void save(Inscricao inscricao) {
inscricaoRepository.save(inscricao);
mailService.sendMail(inscricao.getEmail(), "Cadastro realizado", "Seu cadastro foi criado com sucesso, aguarde parecer.");
}
public List<Inscricao> findAll() {
return inscricaoRepository.findAll();
}
|
public void alterarSituacao(Long id, Situacao situacao) {
|
alexgamas/treinamento-spring-boot
|
treinamento_5/src/main/java/br/com/gamas/treinamento/controller/AvaliacaoController.java
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Situacao.java
// public enum Situacao {
// PENDENTE(1, "Pendente de avaliação"),
// APROVADO(2, "Aprovado"),
// REPROVADO(3, "Reprovado");
//
// private int codigo;
// private String descricao;
//
// Situacao(int codigo, String descricao) {
// this.codigo = codigo;
// this.descricao = descricao;
// }
//
// public int getCodigo() {
// return codigo;
// }
//
// public String getDescricao() {
// return descricao;
// }
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/service/InscricaoService.java
// @Service
// public class InscricaoService {
//
// @Autowired
// private InscricaoRepository inscricaoRepository;
//
// @Autowired
// private MailService mailService;
//
// public Inscricao buscarInscricaoPorId(Long id) {
// return inscricaoRepository.findOne(id);
// }
//
// public void save(Inscricao inscricao) {
// inscricaoRepository.save(inscricao);
// mailService.sendMail(inscricao.getEmail(), "Cadastro realizado", "Seu cadastro foi criado com sucesso, aguarde parecer.");
// }
//
// public List<Inscricao> findAll() {
// return inscricaoRepository.findAll();
// }
//
// public void alterarSituacao(Long id, Situacao situacao) {
// Inscricao inscricao = buscarInscricaoPorId(id);
//
// if (inscricao != null){
//
// inscricaoRepository.save(inscricao);
//
// StringBuilder sb = new StringBuilder();
// sb.append("Seu cadastro de número: ");
// sb.append(inscricao.getId());
// sb.append(" foi ");
// sb.append(situacao.getDescricao());
// sb.append(".");
//
// mailService.sendMail(inscricao.getEmail(), "Alteração de cadastro.", sb.toString());
// inscricao.setSituacao(situacao);
// }
// }
//
//
// }
|
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.Situacao;
import br.com.gamas.treinamento.service.InscricaoService;
|
package br.com.gamas.treinamento.controller;
@Controller
@RequestMapping("/avaliacao")
public class AvaliacaoController {
@Autowired
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Situacao.java
// public enum Situacao {
// PENDENTE(1, "Pendente de avaliação"),
// APROVADO(2, "Aprovado"),
// REPROVADO(3, "Reprovado");
//
// private int codigo;
// private String descricao;
//
// Situacao(int codigo, String descricao) {
// this.codigo = codigo;
// this.descricao = descricao;
// }
//
// public int getCodigo() {
// return codigo;
// }
//
// public String getDescricao() {
// return descricao;
// }
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/service/InscricaoService.java
// @Service
// public class InscricaoService {
//
// @Autowired
// private InscricaoRepository inscricaoRepository;
//
// @Autowired
// private MailService mailService;
//
// public Inscricao buscarInscricaoPorId(Long id) {
// return inscricaoRepository.findOne(id);
// }
//
// public void save(Inscricao inscricao) {
// inscricaoRepository.save(inscricao);
// mailService.sendMail(inscricao.getEmail(), "Cadastro realizado", "Seu cadastro foi criado com sucesso, aguarde parecer.");
// }
//
// public List<Inscricao> findAll() {
// return inscricaoRepository.findAll();
// }
//
// public void alterarSituacao(Long id, Situacao situacao) {
// Inscricao inscricao = buscarInscricaoPorId(id);
//
// if (inscricao != null){
//
// inscricaoRepository.save(inscricao);
//
// StringBuilder sb = new StringBuilder();
// sb.append("Seu cadastro de número: ");
// sb.append(inscricao.getId());
// sb.append(" foi ");
// sb.append(situacao.getDescricao());
// sb.append(".");
//
// mailService.sendMail(inscricao.getEmail(), "Alteração de cadastro.", sb.toString());
// inscricao.setSituacao(situacao);
// }
// }
//
//
// }
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/controller/AvaliacaoController.java
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.Situacao;
import br.com.gamas.treinamento.service.InscricaoService;
package br.com.gamas.treinamento.controller;
@Controller
@RequestMapping("/avaliacao")
public class AvaliacaoController {
@Autowired
|
private InscricaoService inscricaoService;
|
alexgamas/treinamento-spring-boot
|
treinamento_5/src/main/java/br/com/gamas/treinamento/controller/AvaliacaoController.java
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Situacao.java
// public enum Situacao {
// PENDENTE(1, "Pendente de avaliação"),
// APROVADO(2, "Aprovado"),
// REPROVADO(3, "Reprovado");
//
// private int codigo;
// private String descricao;
//
// Situacao(int codigo, String descricao) {
// this.codigo = codigo;
// this.descricao = descricao;
// }
//
// public int getCodigo() {
// return codigo;
// }
//
// public String getDescricao() {
// return descricao;
// }
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/service/InscricaoService.java
// @Service
// public class InscricaoService {
//
// @Autowired
// private InscricaoRepository inscricaoRepository;
//
// @Autowired
// private MailService mailService;
//
// public Inscricao buscarInscricaoPorId(Long id) {
// return inscricaoRepository.findOne(id);
// }
//
// public void save(Inscricao inscricao) {
// inscricaoRepository.save(inscricao);
// mailService.sendMail(inscricao.getEmail(), "Cadastro realizado", "Seu cadastro foi criado com sucesso, aguarde parecer.");
// }
//
// public List<Inscricao> findAll() {
// return inscricaoRepository.findAll();
// }
//
// public void alterarSituacao(Long id, Situacao situacao) {
// Inscricao inscricao = buscarInscricaoPorId(id);
//
// if (inscricao != null){
//
// inscricaoRepository.save(inscricao);
//
// StringBuilder sb = new StringBuilder();
// sb.append("Seu cadastro de número: ");
// sb.append(inscricao.getId());
// sb.append(" foi ");
// sb.append(situacao.getDescricao());
// sb.append(".");
//
// mailService.sendMail(inscricao.getEmail(), "Alteração de cadastro.", sb.toString());
// inscricao.setSituacao(situacao);
// }
// }
//
//
// }
|
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.Situacao;
import br.com.gamas.treinamento.service.InscricaoService;
|
package br.com.gamas.treinamento.controller;
@Controller
@RequestMapping("/avaliacao")
public class AvaliacaoController {
@Autowired
private InscricaoService inscricaoService;
@RequestMapping(value = "/lista", method = RequestMethod.GET)
public ModelAndView view() {
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Situacao.java
// public enum Situacao {
// PENDENTE(1, "Pendente de avaliação"),
// APROVADO(2, "Aprovado"),
// REPROVADO(3, "Reprovado");
//
// private int codigo;
// private String descricao;
//
// Situacao(int codigo, String descricao) {
// this.codigo = codigo;
// this.descricao = descricao;
// }
//
// public int getCodigo() {
// return codigo;
// }
//
// public String getDescricao() {
// return descricao;
// }
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/service/InscricaoService.java
// @Service
// public class InscricaoService {
//
// @Autowired
// private InscricaoRepository inscricaoRepository;
//
// @Autowired
// private MailService mailService;
//
// public Inscricao buscarInscricaoPorId(Long id) {
// return inscricaoRepository.findOne(id);
// }
//
// public void save(Inscricao inscricao) {
// inscricaoRepository.save(inscricao);
// mailService.sendMail(inscricao.getEmail(), "Cadastro realizado", "Seu cadastro foi criado com sucesso, aguarde parecer.");
// }
//
// public List<Inscricao> findAll() {
// return inscricaoRepository.findAll();
// }
//
// public void alterarSituacao(Long id, Situacao situacao) {
// Inscricao inscricao = buscarInscricaoPorId(id);
//
// if (inscricao != null){
//
// inscricaoRepository.save(inscricao);
//
// StringBuilder sb = new StringBuilder();
// sb.append("Seu cadastro de número: ");
// sb.append(inscricao.getId());
// sb.append(" foi ");
// sb.append(situacao.getDescricao());
// sb.append(".");
//
// mailService.sendMail(inscricao.getEmail(), "Alteração de cadastro.", sb.toString());
// inscricao.setSituacao(situacao);
// }
// }
//
//
// }
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/controller/AvaliacaoController.java
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.Situacao;
import br.com.gamas.treinamento.service.InscricaoService;
package br.com.gamas.treinamento.controller;
@Controller
@RequestMapping("/avaliacao")
public class AvaliacaoController {
@Autowired
private InscricaoService inscricaoService;
@RequestMapping(value = "/lista", method = RequestMethod.GET)
public ModelAndView view() {
|
List<Inscricao> inscricoes = inscricaoService.findAll();
|
alexgamas/treinamento-spring-boot
|
treinamento_5/src/main/java/br/com/gamas/treinamento/controller/AvaliacaoController.java
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Situacao.java
// public enum Situacao {
// PENDENTE(1, "Pendente de avaliação"),
// APROVADO(2, "Aprovado"),
// REPROVADO(3, "Reprovado");
//
// private int codigo;
// private String descricao;
//
// Situacao(int codigo, String descricao) {
// this.codigo = codigo;
// this.descricao = descricao;
// }
//
// public int getCodigo() {
// return codigo;
// }
//
// public String getDescricao() {
// return descricao;
// }
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/service/InscricaoService.java
// @Service
// public class InscricaoService {
//
// @Autowired
// private InscricaoRepository inscricaoRepository;
//
// @Autowired
// private MailService mailService;
//
// public Inscricao buscarInscricaoPorId(Long id) {
// return inscricaoRepository.findOne(id);
// }
//
// public void save(Inscricao inscricao) {
// inscricaoRepository.save(inscricao);
// mailService.sendMail(inscricao.getEmail(), "Cadastro realizado", "Seu cadastro foi criado com sucesso, aguarde parecer.");
// }
//
// public List<Inscricao> findAll() {
// return inscricaoRepository.findAll();
// }
//
// public void alterarSituacao(Long id, Situacao situacao) {
// Inscricao inscricao = buscarInscricaoPorId(id);
//
// if (inscricao != null){
//
// inscricaoRepository.save(inscricao);
//
// StringBuilder sb = new StringBuilder();
// sb.append("Seu cadastro de número: ");
// sb.append(inscricao.getId());
// sb.append(" foi ");
// sb.append(situacao.getDescricao());
// sb.append(".");
//
// mailService.sendMail(inscricao.getEmail(), "Alteração de cadastro.", sb.toString());
// inscricao.setSituacao(situacao);
// }
// }
//
//
// }
|
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.Situacao;
import br.com.gamas.treinamento.service.InscricaoService;
|
package br.com.gamas.treinamento.controller;
@Controller
@RequestMapping("/avaliacao")
public class AvaliacaoController {
@Autowired
private InscricaoService inscricaoService;
@RequestMapping(value = "/lista", method = RequestMethod.GET)
public ModelAndView view() {
List<Inscricao> inscricoes = inscricaoService.findAll();
return new ModelAndView("pages/lista").addObject("inscricoes", inscricoes);
}
@RequestMapping(value = "/aprovar/{id}", method = RequestMethod.GET)
public ModelAndView aprovar(@PathVariable("id") Long id) {
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Situacao.java
// public enum Situacao {
// PENDENTE(1, "Pendente de avaliação"),
// APROVADO(2, "Aprovado"),
// REPROVADO(3, "Reprovado");
//
// private int codigo;
// private String descricao;
//
// Situacao(int codigo, String descricao) {
// this.codigo = codigo;
// this.descricao = descricao;
// }
//
// public int getCodigo() {
// return codigo;
// }
//
// public String getDescricao() {
// return descricao;
// }
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/service/InscricaoService.java
// @Service
// public class InscricaoService {
//
// @Autowired
// private InscricaoRepository inscricaoRepository;
//
// @Autowired
// private MailService mailService;
//
// public Inscricao buscarInscricaoPorId(Long id) {
// return inscricaoRepository.findOne(id);
// }
//
// public void save(Inscricao inscricao) {
// inscricaoRepository.save(inscricao);
// mailService.sendMail(inscricao.getEmail(), "Cadastro realizado", "Seu cadastro foi criado com sucesso, aguarde parecer.");
// }
//
// public List<Inscricao> findAll() {
// return inscricaoRepository.findAll();
// }
//
// public void alterarSituacao(Long id, Situacao situacao) {
// Inscricao inscricao = buscarInscricaoPorId(id);
//
// if (inscricao != null){
//
// inscricaoRepository.save(inscricao);
//
// StringBuilder sb = new StringBuilder();
// sb.append("Seu cadastro de número: ");
// sb.append(inscricao.getId());
// sb.append(" foi ");
// sb.append(situacao.getDescricao());
// sb.append(".");
//
// mailService.sendMail(inscricao.getEmail(), "Alteração de cadastro.", sb.toString());
// inscricao.setSituacao(situacao);
// }
// }
//
//
// }
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/controller/AvaliacaoController.java
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.Situacao;
import br.com.gamas.treinamento.service.InscricaoService;
package br.com.gamas.treinamento.controller;
@Controller
@RequestMapping("/avaliacao")
public class AvaliacaoController {
@Autowired
private InscricaoService inscricaoService;
@RequestMapping(value = "/lista", method = RequestMethod.GET)
public ModelAndView view() {
List<Inscricao> inscricoes = inscricaoService.findAll();
return new ModelAndView("pages/lista").addObject("inscricoes", inscricoes);
}
@RequestMapping(value = "/aprovar/{id}", method = RequestMethod.GET)
public ModelAndView aprovar(@PathVariable("id") Long id) {
|
inscricaoService.alterarSituacao(id, Situacao.APROVADO);
|
alexgamas/treinamento-spring-boot
|
treinamento_5/src/main/java/br/com/gamas/treinamento/security/CurrentUserControllerAdvice.java
|
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Usuario.java
// @Entity
// @Table(name = "usuario")
// public class Usuario implements UserDetails{
//
// private static final long serialVersionUID = 3317339439073208844L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// @Column(name = "id", nullable = false, updatable = false)
// private Long id;
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password", nullable = false)
// private String password;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// @Override
// public Collection<? extends GrantedAuthority> getAuthorities() {
// List<GrantedAuthority> authorities = new ArrayList<>();
//
// if (role != null) {
// GrantedAuthority authority = new SimpleGrantedAuthority(role.name());
// authorities.add(authority);
// }
//
// return authorities;
// }
//
// @Override
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// @Override
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// @Override
// public boolean isAccountNonExpired() {
// return true;
// }
//
// @Override
// public boolean isAccountNonLocked() {
// return true;
// }
//
// @Override
// public boolean isCredentialsNonExpired() {
// return true;
// }
//
// @Override
// public boolean isEnabled() {
// return true;
// }
//
//
// }
|
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import br.com.gamas.treinamento.model.Usuario;
|
package br.com.gamas.treinamento.security;
@ControllerAdvice
public class CurrentUserControllerAdvice {
@ModelAttribute("currentUser")
|
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Usuario.java
// @Entity
// @Table(name = "usuario")
// public class Usuario implements UserDetails{
//
// private static final long serialVersionUID = 3317339439073208844L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// @Column(name = "id", nullable = false, updatable = false)
// private Long id;
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password", nullable = false)
// private String password;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// @Override
// public Collection<? extends GrantedAuthority> getAuthorities() {
// List<GrantedAuthority> authorities = new ArrayList<>();
//
// if (role != null) {
// GrantedAuthority authority = new SimpleGrantedAuthority(role.name());
// authorities.add(authority);
// }
//
// return authorities;
// }
//
// @Override
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// @Override
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// @Override
// public boolean isAccountNonExpired() {
// return true;
// }
//
// @Override
// public boolean isAccountNonLocked() {
// return true;
// }
//
// @Override
// public boolean isCredentialsNonExpired() {
// return true;
// }
//
// @Override
// public boolean isEnabled() {
// return true;
// }
//
//
// }
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/security/CurrentUserControllerAdvice.java
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import br.com.gamas.treinamento.model.Usuario;
package br.com.gamas.treinamento.security;
@ControllerAdvice
public class CurrentUserControllerAdvice {
@ModelAttribute("currentUser")
|
public Usuario getCurrentUser(Authentication authentication) {
|
alexgamas/treinamento-spring-boot
|
treinamento_5/src/main/java/br/com/gamas/treinamento/controller/FormularioController.java
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/service/InscricaoService.java
// @Service
// public class InscricaoService {
//
// @Autowired
// private InscricaoRepository inscricaoRepository;
//
// @Autowired
// private MailService mailService;
//
// public Inscricao buscarInscricaoPorId(Long id) {
// return inscricaoRepository.findOne(id);
// }
//
// public void save(Inscricao inscricao) {
// inscricaoRepository.save(inscricao);
// mailService.sendMail(inscricao.getEmail(), "Cadastro realizado", "Seu cadastro foi criado com sucesso, aguarde parecer.");
// }
//
// public List<Inscricao> findAll() {
// return inscricaoRepository.findAll();
// }
//
// public void alterarSituacao(Long id, Situacao situacao) {
// Inscricao inscricao = buscarInscricaoPorId(id);
//
// if (inscricao != null){
//
// inscricaoRepository.save(inscricao);
//
// StringBuilder sb = new StringBuilder();
// sb.append("Seu cadastro de número: ");
// sb.append(inscricao.getId());
// sb.append(" foi ");
// sb.append(situacao.getDescricao());
// sb.append(".");
//
// mailService.sendMail(inscricao.getEmail(), "Alteração de cadastro.", sb.toString());
// inscricao.setSituacao(situacao);
// }
// }
//
//
// }
|
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.service.InscricaoService;
|
package br.com.gamas.treinamento.controller;
@Controller
@RequestMapping("/formulario")
public class FormularioController {
@Autowired
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/service/InscricaoService.java
// @Service
// public class InscricaoService {
//
// @Autowired
// private InscricaoRepository inscricaoRepository;
//
// @Autowired
// private MailService mailService;
//
// public Inscricao buscarInscricaoPorId(Long id) {
// return inscricaoRepository.findOne(id);
// }
//
// public void save(Inscricao inscricao) {
// inscricaoRepository.save(inscricao);
// mailService.sendMail(inscricao.getEmail(), "Cadastro realizado", "Seu cadastro foi criado com sucesso, aguarde parecer.");
// }
//
// public List<Inscricao> findAll() {
// return inscricaoRepository.findAll();
// }
//
// public void alterarSituacao(Long id, Situacao situacao) {
// Inscricao inscricao = buscarInscricaoPorId(id);
//
// if (inscricao != null){
//
// inscricaoRepository.save(inscricao);
//
// StringBuilder sb = new StringBuilder();
// sb.append("Seu cadastro de número: ");
// sb.append(inscricao.getId());
// sb.append(" foi ");
// sb.append(situacao.getDescricao());
// sb.append(".");
//
// mailService.sendMail(inscricao.getEmail(), "Alteração de cadastro.", sb.toString());
// inscricao.setSituacao(situacao);
// }
// }
//
//
// }
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/controller/FormularioController.java
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.service.InscricaoService;
package br.com.gamas.treinamento.controller;
@Controller
@RequestMapping("/formulario")
public class FormularioController {
@Autowired
|
private InscricaoService inscricaoService;
|
alexgamas/treinamento-spring-boot
|
treinamento_5/src/main/java/br/com/gamas/treinamento/controller/FormularioController.java
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/service/InscricaoService.java
// @Service
// public class InscricaoService {
//
// @Autowired
// private InscricaoRepository inscricaoRepository;
//
// @Autowired
// private MailService mailService;
//
// public Inscricao buscarInscricaoPorId(Long id) {
// return inscricaoRepository.findOne(id);
// }
//
// public void save(Inscricao inscricao) {
// inscricaoRepository.save(inscricao);
// mailService.sendMail(inscricao.getEmail(), "Cadastro realizado", "Seu cadastro foi criado com sucesso, aguarde parecer.");
// }
//
// public List<Inscricao> findAll() {
// return inscricaoRepository.findAll();
// }
//
// public void alterarSituacao(Long id, Situacao situacao) {
// Inscricao inscricao = buscarInscricaoPorId(id);
//
// if (inscricao != null){
//
// inscricaoRepository.save(inscricao);
//
// StringBuilder sb = new StringBuilder();
// sb.append("Seu cadastro de número: ");
// sb.append(inscricao.getId());
// sb.append(" foi ");
// sb.append(situacao.getDescricao());
// sb.append(".");
//
// mailService.sendMail(inscricao.getEmail(), "Alteração de cadastro.", sb.toString());
// inscricao.setSituacao(situacao);
// }
// }
//
//
// }
|
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.service.InscricaoService;
|
package br.com.gamas.treinamento.controller;
@Controller
@RequestMapping("/formulario")
public class FormularioController {
@Autowired
private InscricaoService inscricaoService;
@RequestMapping(value = "/inscricao", method = RequestMethod.GET)
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/service/InscricaoService.java
// @Service
// public class InscricaoService {
//
// @Autowired
// private InscricaoRepository inscricaoRepository;
//
// @Autowired
// private MailService mailService;
//
// public Inscricao buscarInscricaoPorId(Long id) {
// return inscricaoRepository.findOne(id);
// }
//
// public void save(Inscricao inscricao) {
// inscricaoRepository.save(inscricao);
// mailService.sendMail(inscricao.getEmail(), "Cadastro realizado", "Seu cadastro foi criado com sucesso, aguarde parecer.");
// }
//
// public List<Inscricao> findAll() {
// return inscricaoRepository.findAll();
// }
//
// public void alterarSituacao(Long id, Situacao situacao) {
// Inscricao inscricao = buscarInscricaoPorId(id);
//
// if (inscricao != null){
//
// inscricaoRepository.save(inscricao);
//
// StringBuilder sb = new StringBuilder();
// sb.append("Seu cadastro de número: ");
// sb.append(inscricao.getId());
// sb.append(" foi ");
// sb.append(situacao.getDescricao());
// sb.append(".");
//
// mailService.sendMail(inscricao.getEmail(), "Alteração de cadastro.", sb.toString());
// inscricao.setSituacao(situacao);
// }
// }
//
//
// }
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/controller/FormularioController.java
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.service.InscricaoService;
package br.com.gamas.treinamento.controller;
@Controller
@RequestMapping("/formulario")
public class FormularioController {
@Autowired
private InscricaoService inscricaoService;
@RequestMapping(value = "/inscricao", method = RequestMethod.GET)
|
public String root(@ModelAttribute Inscricao inscricao) {
|
alexgamas/treinamento-spring-boot
|
treinamento_5/src/main/java/br/com/gamas/treinamento/service/CurrentUserDetailsService.java
|
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Usuario.java
// @Entity
// @Table(name = "usuario")
// public class Usuario implements UserDetails{
//
// private static final long serialVersionUID = 3317339439073208844L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// @Column(name = "id", nullable = false, updatable = false)
// private Long id;
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password", nullable = false)
// private String password;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// @Override
// public Collection<? extends GrantedAuthority> getAuthorities() {
// List<GrantedAuthority> authorities = new ArrayList<>();
//
// if (role != null) {
// GrantedAuthority authority = new SimpleGrantedAuthority(role.name());
// authorities.add(authority);
// }
//
// return authorities;
// }
//
// @Override
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// @Override
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// @Override
// public boolean isAccountNonExpired() {
// return true;
// }
//
// @Override
// public boolean isAccountNonLocked() {
// return true;
// }
//
// @Override
// public boolean isCredentialsNonExpired() {
// return true;
// }
//
// @Override
// public boolean isEnabled() {
// return true;
// }
//
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/repository/UsuarioRepository.java
// @Repository
// public class UsuarioRepository {
//
// @PersistenceContext
// private EntityManager em;
//
// public Usuario loadUserByUsername(String username) {
//
// TypedQuery<Usuario> query = em.createQuery("select usuario from Usuario usuario where usuario.username = :username", Usuario.class);
//
// query.setParameter("username", username);
//
// List<Usuario> usuarios = query.getResultList();
// if (!CollectionUtils.isEmpty(usuarios)) {
// return usuarios.iterator().next();
// }
//
// return null;
// }
// }
|
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import br.com.gamas.treinamento.model.Usuario;
import br.com.gamas.treinamento.repository.UsuarioRepository;
|
package br.com.gamas.treinamento.service;
@Service
public class CurrentUserDetailsService implements UserDetailsService {
@Autowired
|
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Usuario.java
// @Entity
// @Table(name = "usuario")
// public class Usuario implements UserDetails{
//
// private static final long serialVersionUID = 3317339439073208844L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// @Column(name = "id", nullable = false, updatable = false)
// private Long id;
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password", nullable = false)
// private String password;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// @Override
// public Collection<? extends GrantedAuthority> getAuthorities() {
// List<GrantedAuthority> authorities = new ArrayList<>();
//
// if (role != null) {
// GrantedAuthority authority = new SimpleGrantedAuthority(role.name());
// authorities.add(authority);
// }
//
// return authorities;
// }
//
// @Override
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// @Override
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// @Override
// public boolean isAccountNonExpired() {
// return true;
// }
//
// @Override
// public boolean isAccountNonLocked() {
// return true;
// }
//
// @Override
// public boolean isCredentialsNonExpired() {
// return true;
// }
//
// @Override
// public boolean isEnabled() {
// return true;
// }
//
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/repository/UsuarioRepository.java
// @Repository
// public class UsuarioRepository {
//
// @PersistenceContext
// private EntityManager em;
//
// public Usuario loadUserByUsername(String username) {
//
// TypedQuery<Usuario> query = em.createQuery("select usuario from Usuario usuario where usuario.username = :username", Usuario.class);
//
// query.setParameter("username", username);
//
// List<Usuario> usuarios = query.getResultList();
// if (!CollectionUtils.isEmpty(usuarios)) {
// return usuarios.iterator().next();
// }
//
// return null;
// }
// }
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/service/CurrentUserDetailsService.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import br.com.gamas.treinamento.model.Usuario;
import br.com.gamas.treinamento.repository.UsuarioRepository;
package br.com.gamas.treinamento.service;
@Service
public class CurrentUserDetailsService implements UserDetailsService {
@Autowired
|
private UsuarioRepository usuarioRepository;
|
alexgamas/treinamento-spring-boot
|
treinamento_5/src/main/java/br/com/gamas/treinamento/service/CurrentUserDetailsService.java
|
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Usuario.java
// @Entity
// @Table(name = "usuario")
// public class Usuario implements UserDetails{
//
// private static final long serialVersionUID = 3317339439073208844L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// @Column(name = "id", nullable = false, updatable = false)
// private Long id;
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password", nullable = false)
// private String password;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// @Override
// public Collection<? extends GrantedAuthority> getAuthorities() {
// List<GrantedAuthority> authorities = new ArrayList<>();
//
// if (role != null) {
// GrantedAuthority authority = new SimpleGrantedAuthority(role.name());
// authorities.add(authority);
// }
//
// return authorities;
// }
//
// @Override
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// @Override
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// @Override
// public boolean isAccountNonExpired() {
// return true;
// }
//
// @Override
// public boolean isAccountNonLocked() {
// return true;
// }
//
// @Override
// public boolean isCredentialsNonExpired() {
// return true;
// }
//
// @Override
// public boolean isEnabled() {
// return true;
// }
//
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/repository/UsuarioRepository.java
// @Repository
// public class UsuarioRepository {
//
// @PersistenceContext
// private EntityManager em;
//
// public Usuario loadUserByUsername(String username) {
//
// TypedQuery<Usuario> query = em.createQuery("select usuario from Usuario usuario where usuario.username = :username", Usuario.class);
//
// query.setParameter("username", username);
//
// List<Usuario> usuarios = query.getResultList();
// if (!CollectionUtils.isEmpty(usuarios)) {
// return usuarios.iterator().next();
// }
//
// return null;
// }
// }
|
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import br.com.gamas.treinamento.model.Usuario;
import br.com.gamas.treinamento.repository.UsuarioRepository;
|
package br.com.gamas.treinamento.service;
@Service
public class CurrentUserDetailsService implements UserDetailsService {
@Autowired
private UsuarioRepository usuarioRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Usuario.java
// @Entity
// @Table(name = "usuario")
// public class Usuario implements UserDetails{
//
// private static final long serialVersionUID = 3317339439073208844L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// @Column(name = "id", nullable = false, updatable = false)
// private Long id;
//
// @Column(name = "username", nullable = false, unique = true)
// private String username;
//
// @Column(name = "password", nullable = false)
// private String password;
//
// @Column(name = "role", nullable = false)
// @Enumerated(EnumType.STRING)
// private Role role;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// @Override
// public Collection<? extends GrantedAuthority> getAuthorities() {
// List<GrantedAuthority> authorities = new ArrayList<>();
//
// if (role != null) {
// GrantedAuthority authority = new SimpleGrantedAuthority(role.name());
// authorities.add(authority);
// }
//
// return authorities;
// }
//
// @Override
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// @Override
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// @Override
// public boolean isAccountNonExpired() {
// return true;
// }
//
// @Override
// public boolean isAccountNonLocked() {
// return true;
// }
//
// @Override
// public boolean isCredentialsNonExpired() {
// return true;
// }
//
// @Override
// public boolean isEnabled() {
// return true;
// }
//
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/repository/UsuarioRepository.java
// @Repository
// public class UsuarioRepository {
//
// @PersistenceContext
// private EntityManager em;
//
// public Usuario loadUserByUsername(String username) {
//
// TypedQuery<Usuario> query = em.createQuery("select usuario from Usuario usuario where usuario.username = :username", Usuario.class);
//
// query.setParameter("username", username);
//
// List<Usuario> usuarios = query.getResultList();
// if (!CollectionUtils.isEmpty(usuarios)) {
// return usuarios.iterator().next();
// }
//
// return null;
// }
// }
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/service/CurrentUserDetailsService.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import br.com.gamas.treinamento.model.Usuario;
import br.com.gamas.treinamento.repository.UsuarioRepository;
package br.com.gamas.treinamento.service;
@Service
public class CurrentUserDetailsService implements UserDetailsService {
@Autowired
private UsuarioRepository usuarioRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
Usuario usuario = usuarioRepository.loadUserByUsername(username);
|
alexgamas/treinamento-spring-boot
|
treinamento_4/src/main/java/br/com/gamas/treinamento/service/InscricaoService.java
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Situacao.java
// public enum Situacao {
// PENDENTE(1, "Pendente de avaliação"),
// APROVADO(2, "Aprovado"),
// REPROVADO(3, "Reprovado");
//
// private int codigo;
// private String descricao;
//
// Situacao(int codigo, String descricao) {
// this.codigo = codigo;
// this.descricao = descricao;
// }
//
// public int getCodigo() {
// return codigo;
// }
//
// public String getDescricao() {
// return descricao;
// }
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/repository/InscricaoRepository.java
// @Repository
// public interface InscricaoRepository extends JpaRepository<Inscricao, Long> {
// }
|
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.Situacao;
import br.com.gamas.treinamento.repository.InscricaoRepository;
|
package br.com.gamas.treinamento.service;
@Service
public class InscricaoService {
@Autowired
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Situacao.java
// public enum Situacao {
// PENDENTE(1, "Pendente de avaliação"),
// APROVADO(2, "Aprovado"),
// REPROVADO(3, "Reprovado");
//
// private int codigo;
// private String descricao;
//
// Situacao(int codigo, String descricao) {
// this.codigo = codigo;
// this.descricao = descricao;
// }
//
// public int getCodigo() {
// return codigo;
// }
//
// public String getDescricao() {
// return descricao;
// }
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/repository/InscricaoRepository.java
// @Repository
// public interface InscricaoRepository extends JpaRepository<Inscricao, Long> {
// }
// Path: treinamento_4/src/main/java/br/com/gamas/treinamento/service/InscricaoService.java
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.Situacao;
import br.com.gamas.treinamento.repository.InscricaoRepository;
package br.com.gamas.treinamento.service;
@Service
public class InscricaoService {
@Autowired
|
private InscricaoRepository inscricaoRepository;
|
alexgamas/treinamento-spring-boot
|
treinamento_4/src/main/java/br/com/gamas/treinamento/service/InscricaoService.java
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Situacao.java
// public enum Situacao {
// PENDENTE(1, "Pendente de avaliação"),
// APROVADO(2, "Aprovado"),
// REPROVADO(3, "Reprovado");
//
// private int codigo;
// private String descricao;
//
// Situacao(int codigo, String descricao) {
// this.codigo = codigo;
// this.descricao = descricao;
// }
//
// public int getCodigo() {
// return codigo;
// }
//
// public String getDescricao() {
// return descricao;
// }
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/repository/InscricaoRepository.java
// @Repository
// public interface InscricaoRepository extends JpaRepository<Inscricao, Long> {
// }
|
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.Situacao;
import br.com.gamas.treinamento.repository.InscricaoRepository;
|
package br.com.gamas.treinamento.service;
@Service
public class InscricaoService {
@Autowired
private InscricaoRepository inscricaoRepository;
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Situacao.java
// public enum Situacao {
// PENDENTE(1, "Pendente de avaliação"),
// APROVADO(2, "Aprovado"),
// REPROVADO(3, "Reprovado");
//
// private int codigo;
// private String descricao;
//
// Situacao(int codigo, String descricao) {
// this.codigo = codigo;
// this.descricao = descricao;
// }
//
// public int getCodigo() {
// return codigo;
// }
//
// public String getDescricao() {
// return descricao;
// }
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/repository/InscricaoRepository.java
// @Repository
// public interface InscricaoRepository extends JpaRepository<Inscricao, Long> {
// }
// Path: treinamento_4/src/main/java/br/com/gamas/treinamento/service/InscricaoService.java
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.Situacao;
import br.com.gamas.treinamento.repository.InscricaoRepository;
package br.com.gamas.treinamento.service;
@Service
public class InscricaoService {
@Autowired
private InscricaoRepository inscricaoRepository;
|
public Inscricao buscarInscricaoPorId(Long id) {
|
alexgamas/treinamento-spring-boot
|
treinamento_4/src/main/java/br/com/gamas/treinamento/service/InscricaoService.java
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Situacao.java
// public enum Situacao {
// PENDENTE(1, "Pendente de avaliação"),
// APROVADO(2, "Aprovado"),
// REPROVADO(3, "Reprovado");
//
// private int codigo;
// private String descricao;
//
// Situacao(int codigo, String descricao) {
// this.codigo = codigo;
// this.descricao = descricao;
// }
//
// public int getCodigo() {
// return codigo;
// }
//
// public String getDescricao() {
// return descricao;
// }
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/repository/InscricaoRepository.java
// @Repository
// public interface InscricaoRepository extends JpaRepository<Inscricao, Long> {
// }
|
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.Situacao;
import br.com.gamas.treinamento.repository.InscricaoRepository;
|
package br.com.gamas.treinamento.service;
@Service
public class InscricaoService {
@Autowired
private InscricaoRepository inscricaoRepository;
public Inscricao buscarInscricaoPorId(Long id) {
return inscricaoRepository.findOne(id);
}
public void save(Inscricao inscricao) {
inscricaoRepository.save(inscricao);
}
public List<Inscricao> findAll() {
return inscricaoRepository.findAll();
}
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Situacao.java
// public enum Situacao {
// PENDENTE(1, "Pendente de avaliação"),
// APROVADO(2, "Aprovado"),
// REPROVADO(3, "Reprovado");
//
// private int codigo;
// private String descricao;
//
// Situacao(int codigo, String descricao) {
// this.codigo = codigo;
// this.descricao = descricao;
// }
//
// public int getCodigo() {
// return codigo;
// }
//
// public String getDescricao() {
// return descricao;
// }
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/repository/InscricaoRepository.java
// @Repository
// public interface InscricaoRepository extends JpaRepository<Inscricao, Long> {
// }
// Path: treinamento_4/src/main/java/br/com/gamas/treinamento/service/InscricaoService.java
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.Situacao;
import br.com.gamas.treinamento.repository.InscricaoRepository;
package br.com.gamas.treinamento.service;
@Service
public class InscricaoService {
@Autowired
private InscricaoRepository inscricaoRepository;
public Inscricao buscarInscricaoPorId(Long id) {
return inscricaoRepository.findOne(id);
}
public void save(Inscricao inscricao) {
inscricaoRepository.save(inscricao);
}
public List<Inscricao> findAll() {
return inscricaoRepository.findAll();
}
|
public void alterarSituacao(Long id, Situacao situacao) {
|
alexgamas/treinamento-spring-boot
|
treinamento_1/src/main/java/br/com/gamas/treinamento/controller/AvaliacaoController.java
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/InscricaoData.java
// public class InscricaoData {
//
// public static List<Inscricao> inscricoes = new LinkedList<>();
//
// public static Inscricao buscarInscricaoPorId(Long id) {
// if (inscricoes != null && id != null) {
// for (Inscricao inscricao : inscricoes) {
// if (id.equals(inscricao.getId())){
// return inscricao;
// }
// }
// }
//
// return null;
// }
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Situacao.java
// public enum Situacao {
// PENDENTE(1, "Pendente de avaliação"),
// APROVADO(2, "Aprovado"),
// REPROVADO(3, "Reprovado");
//
// private int codigo;
// private String descricao;
//
// Situacao(int codigo, String descricao) {
// this.codigo = codigo;
// this.descricao = descricao;
// }
//
// public int getCodigo() {
// return codigo;
// }
//
// public String getDescricao() {
// return descricao;
// }
//
// }
|
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.InscricaoData;
import br.com.gamas.treinamento.model.Situacao;
|
package br.com.gamas.treinamento.controller;
@Controller
@RequestMapping("/avaliacao")
public class AvaliacaoController {
@RequestMapping(value = "/lista", method = RequestMethod.GET)
public ModelAndView view() {
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/InscricaoData.java
// public class InscricaoData {
//
// public static List<Inscricao> inscricoes = new LinkedList<>();
//
// public static Inscricao buscarInscricaoPorId(Long id) {
// if (inscricoes != null && id != null) {
// for (Inscricao inscricao : inscricoes) {
// if (id.equals(inscricao.getId())){
// return inscricao;
// }
// }
// }
//
// return null;
// }
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Situacao.java
// public enum Situacao {
// PENDENTE(1, "Pendente de avaliação"),
// APROVADO(2, "Aprovado"),
// REPROVADO(3, "Reprovado");
//
// private int codigo;
// private String descricao;
//
// Situacao(int codigo, String descricao) {
// this.codigo = codigo;
// this.descricao = descricao;
// }
//
// public int getCodigo() {
// return codigo;
// }
//
// public String getDescricao() {
// return descricao;
// }
//
// }
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/controller/AvaliacaoController.java
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.InscricaoData;
import br.com.gamas.treinamento.model.Situacao;
package br.com.gamas.treinamento.controller;
@Controller
@RequestMapping("/avaliacao")
public class AvaliacaoController {
@RequestMapping(value = "/lista", method = RequestMethod.GET)
public ModelAndView view() {
|
List<Inscricao> inscricoes = InscricaoData.inscricoes;
|
alexgamas/treinamento-spring-boot
|
treinamento_1/src/main/java/br/com/gamas/treinamento/controller/AvaliacaoController.java
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/InscricaoData.java
// public class InscricaoData {
//
// public static List<Inscricao> inscricoes = new LinkedList<>();
//
// public static Inscricao buscarInscricaoPorId(Long id) {
// if (inscricoes != null && id != null) {
// for (Inscricao inscricao : inscricoes) {
// if (id.equals(inscricao.getId())){
// return inscricao;
// }
// }
// }
//
// return null;
// }
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Situacao.java
// public enum Situacao {
// PENDENTE(1, "Pendente de avaliação"),
// APROVADO(2, "Aprovado"),
// REPROVADO(3, "Reprovado");
//
// private int codigo;
// private String descricao;
//
// Situacao(int codigo, String descricao) {
// this.codigo = codigo;
// this.descricao = descricao;
// }
//
// public int getCodigo() {
// return codigo;
// }
//
// public String getDescricao() {
// return descricao;
// }
//
// }
|
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.InscricaoData;
import br.com.gamas.treinamento.model.Situacao;
|
package br.com.gamas.treinamento.controller;
@Controller
@RequestMapping("/avaliacao")
public class AvaliacaoController {
@RequestMapping(value = "/lista", method = RequestMethod.GET)
public ModelAndView view() {
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/InscricaoData.java
// public class InscricaoData {
//
// public static List<Inscricao> inscricoes = new LinkedList<>();
//
// public static Inscricao buscarInscricaoPorId(Long id) {
// if (inscricoes != null && id != null) {
// for (Inscricao inscricao : inscricoes) {
// if (id.equals(inscricao.getId())){
// return inscricao;
// }
// }
// }
//
// return null;
// }
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Situacao.java
// public enum Situacao {
// PENDENTE(1, "Pendente de avaliação"),
// APROVADO(2, "Aprovado"),
// REPROVADO(3, "Reprovado");
//
// private int codigo;
// private String descricao;
//
// Situacao(int codigo, String descricao) {
// this.codigo = codigo;
// this.descricao = descricao;
// }
//
// public int getCodigo() {
// return codigo;
// }
//
// public String getDescricao() {
// return descricao;
// }
//
// }
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/controller/AvaliacaoController.java
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.InscricaoData;
import br.com.gamas.treinamento.model.Situacao;
package br.com.gamas.treinamento.controller;
@Controller
@RequestMapping("/avaliacao")
public class AvaliacaoController {
@RequestMapping(value = "/lista", method = RequestMethod.GET)
public ModelAndView view() {
|
List<Inscricao> inscricoes = InscricaoData.inscricoes;
|
alexgamas/treinamento-spring-boot
|
treinamento_1/src/main/java/br/com/gamas/treinamento/controller/AvaliacaoController.java
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/InscricaoData.java
// public class InscricaoData {
//
// public static List<Inscricao> inscricoes = new LinkedList<>();
//
// public static Inscricao buscarInscricaoPorId(Long id) {
// if (inscricoes != null && id != null) {
// for (Inscricao inscricao : inscricoes) {
// if (id.equals(inscricao.getId())){
// return inscricao;
// }
// }
// }
//
// return null;
// }
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Situacao.java
// public enum Situacao {
// PENDENTE(1, "Pendente de avaliação"),
// APROVADO(2, "Aprovado"),
// REPROVADO(3, "Reprovado");
//
// private int codigo;
// private String descricao;
//
// Situacao(int codigo, String descricao) {
// this.codigo = codigo;
// this.descricao = descricao;
// }
//
// public int getCodigo() {
// return codigo;
// }
//
// public String getDescricao() {
// return descricao;
// }
//
// }
|
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.InscricaoData;
import br.com.gamas.treinamento.model.Situacao;
|
package br.com.gamas.treinamento.controller;
@Controller
@RequestMapping("/avaliacao")
public class AvaliacaoController {
@RequestMapping(value = "/lista", method = RequestMethod.GET)
public ModelAndView view() {
List<Inscricao> inscricoes = InscricaoData.inscricoes;
return new ModelAndView("pages/lista").addObject("inscricoes", inscricoes);
}
@RequestMapping(value = "/aprovar/{id}", method = RequestMethod.GET)
public ModelAndView aprovar(@PathVariable("id") Long id) {
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/InscricaoData.java
// public class InscricaoData {
//
// public static List<Inscricao> inscricoes = new LinkedList<>();
//
// public static Inscricao buscarInscricaoPorId(Long id) {
// if (inscricoes != null && id != null) {
// for (Inscricao inscricao : inscricoes) {
// if (id.equals(inscricao.getId())){
// return inscricao;
// }
// }
// }
//
// return null;
// }
//
// }
//
// Path: treinamento_5/src/main/java/br/com/gamas/treinamento/model/Situacao.java
// public enum Situacao {
// PENDENTE(1, "Pendente de avaliação"),
// APROVADO(2, "Aprovado"),
// REPROVADO(3, "Reprovado");
//
// private int codigo;
// private String descricao;
//
// Situacao(int codigo, String descricao) {
// this.codigo = codigo;
// this.descricao = descricao;
// }
//
// public int getCodigo() {
// return codigo;
// }
//
// public String getDescricao() {
// return descricao;
// }
//
// }
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/controller/AvaliacaoController.java
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.InscricaoData;
import br.com.gamas.treinamento.model.Situacao;
package br.com.gamas.treinamento.controller;
@Controller
@RequestMapping("/avaliacao")
public class AvaliacaoController {
@RequestMapping(value = "/lista", method = RequestMethod.GET)
public ModelAndView view() {
List<Inscricao> inscricoes = InscricaoData.inscricoes;
return new ModelAndView("pages/lista").addObject("inscricoes", inscricoes);
}
@RequestMapping(value = "/aprovar/{id}", method = RequestMethod.GET)
public ModelAndView aprovar(@PathVariable("id") Long id) {
|
alterarSituacao(id, Situacao.APROVADO);
|
alexgamas/treinamento-spring-boot
|
treinamento_1/src/main/java/br/com/gamas/treinamento/controller/FormularioController.java
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/InscricaoData.java
// public class InscricaoData {
//
// public static List<Inscricao> inscricoes = new LinkedList<>();
//
// public static Inscricao buscarInscricaoPorId(Long id) {
// if (inscricoes != null && id != null) {
// for (Inscricao inscricao : inscricoes) {
// if (id.equals(inscricao.getId())){
// return inscricao;
// }
// }
// }
//
// return null;
// }
//
// }
|
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.InscricaoData;
|
package br.com.gamas.treinamento.controller;
@Controller
@RequestMapping("/formulario")
public class FormularioController {
@RequestMapping(value = "/inscricao", method = RequestMethod.GET)
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/InscricaoData.java
// public class InscricaoData {
//
// public static List<Inscricao> inscricoes = new LinkedList<>();
//
// public static Inscricao buscarInscricaoPorId(Long id) {
// if (inscricoes != null && id != null) {
// for (Inscricao inscricao : inscricoes) {
// if (id.equals(inscricao.getId())){
// return inscricao;
// }
// }
// }
//
// return null;
// }
//
// }
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/controller/FormularioController.java
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.InscricaoData;
package br.com.gamas.treinamento.controller;
@Controller
@RequestMapping("/formulario")
public class FormularioController {
@RequestMapping(value = "/inscricao", method = RequestMethod.GET)
|
public String root(@ModelAttribute Inscricao inscricao) {
|
alexgamas/treinamento-spring-boot
|
treinamento_1/src/main/java/br/com/gamas/treinamento/controller/FormularioController.java
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/InscricaoData.java
// public class InscricaoData {
//
// public static List<Inscricao> inscricoes = new LinkedList<>();
//
// public static Inscricao buscarInscricaoPorId(Long id) {
// if (inscricoes != null && id != null) {
// for (Inscricao inscricao : inscricoes) {
// if (id.equals(inscricao.getId())){
// return inscricao;
// }
// }
// }
//
// return null;
// }
//
// }
|
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.InscricaoData;
|
package br.com.gamas.treinamento.controller;
@Controller
@RequestMapping("/formulario")
public class FormularioController {
@RequestMapping(value = "/inscricao", method = RequestMethod.GET)
public String root(@ModelAttribute Inscricao inscricao) {
return "pages/formulario";
}
@RequestMapping(value = "/visualizar/{id}", method = RequestMethod.GET)
public ModelAndView view(@PathVariable("id") Long id) {
|
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/Inscricao.java
// public class Inscricao {
//
// private Long id;
//
// @NotNull
// @Size(max=30)
// private String nome;
//
// @NotNull
// @Size(max=30)
// private String email;
//
// @Min(18)
// @NotNull
// private Integer idade;
//
// private Date dataInscricao;
//
// private Situacao situacao;
//
// public Inscricao() {
// setSituacao(Situacao.PENDENTE);
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getIdade() {
// return idade;
// }
//
// public void setIdade(Integer idade) {
// this.idade = idade;
// }
//
// public Situacao getSituacao() {
// return situacao;
// }
//
// public void setSituacao(Situacao situacao) {
// this.situacao = situacao;
// }
//
// public Date getDataInscricao() {
// return dataInscricao;
// }
//
// public void setDataInscricao(Date dataInscricao) {
// this.dataInscricao = dataInscricao;
// }
// }
//
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/model/InscricaoData.java
// public class InscricaoData {
//
// public static List<Inscricao> inscricoes = new LinkedList<>();
//
// public static Inscricao buscarInscricaoPorId(Long id) {
// if (inscricoes != null && id != null) {
// for (Inscricao inscricao : inscricoes) {
// if (id.equals(inscricao.getId())){
// return inscricao;
// }
// }
// }
//
// return null;
// }
//
// }
// Path: treinamento_1/src/main/java/br/com/gamas/treinamento/controller/FormularioController.java
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import br.com.gamas.treinamento.model.Inscricao;
import br.com.gamas.treinamento.model.InscricaoData;
package br.com.gamas.treinamento.controller;
@Controller
@RequestMapping("/formulario")
public class FormularioController {
@RequestMapping(value = "/inscricao", method = RequestMethod.GET)
public String root(@ModelAttribute Inscricao inscricao) {
return "pages/formulario";
}
@RequestMapping(value = "/visualizar/{id}", method = RequestMethod.GET)
public ModelAndView view(@PathVariable("id") Long id) {
|
Inscricao inscricao = InscricaoData.buscarInscricaoPorId(id);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.