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 |
|---|---|---|---|---|---|---|
jDramaix/gss.gwt | src/main/java/com/google/gwt/resources/gss/EvalFunction.java | // Path: src/main/java/com/google/gwt/resources/gss/ast/CssJavaExpressionNode.java
// public class CssJavaExpressionNode extends CssValueNode {
//
// public CssJavaExpressionNode(String expression) {
// this(expression, null);
// }
//
// public CssJavaExpressionNode(String expression, SourceCodeLocation sourceCodeLocation) {
// super(expression, sourceCodeLocation);
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssJavaExpressionNode(getValue());
// }
//
// @Override
// public String toString() {
// return "Java expression : " + getValue();
// }
// }
| import com.google.common.collect.ImmutableList;
import com.google.common.css.compiler.ast.CssValueNode;
import com.google.common.css.compiler.ast.ErrorManager;
import com.google.common.css.compiler.ast.GssFunction;
import com.google.common.css.compiler.ast.GssFunctionException;
import com.google.gwt.resources.gss.ast.CssJavaExpressionNode;
import java.util.List; | /*
* Copyright 2013 Julien Dramaix.
*
* 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.gwt.resources.gss;
public class EvalFunction implements GssFunction {
public static String getName() {
return "eval";
}
@Override
public List<CssValueNode> getCallResultNodes(List<CssValueNode> args, ErrorManager errorManager)
throws GssFunctionException {
CssValueNode functionToEval = args.get(0);
//TODO check that the value of functionToEval match a certain pattern or exist ? | // Path: src/main/java/com/google/gwt/resources/gss/ast/CssJavaExpressionNode.java
// public class CssJavaExpressionNode extends CssValueNode {
//
// public CssJavaExpressionNode(String expression) {
// this(expression, null);
// }
//
// public CssJavaExpressionNode(String expression, SourceCodeLocation sourceCodeLocation) {
// super(expression, sourceCodeLocation);
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssJavaExpressionNode(getValue());
// }
//
// @Override
// public String toString() {
// return "Java expression : " + getValue();
// }
// }
// Path: src/main/java/com/google/gwt/resources/gss/EvalFunction.java
import com.google.common.collect.ImmutableList;
import com.google.common.css.compiler.ast.CssValueNode;
import com.google.common.css.compiler.ast.ErrorManager;
import com.google.common.css.compiler.ast.GssFunction;
import com.google.common.css.compiler.ast.GssFunctionException;
import com.google.gwt.resources.gss.ast.CssJavaExpressionNode;
import java.util.List;
/*
* Copyright 2013 Julien Dramaix.
*
* 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.gwt.resources.gss;
public class EvalFunction implements GssFunction {
public static String getName() {
return "eval";
}
@Override
public List<CssValueNode> getCallResultNodes(List<CssValueNode> args, ErrorManager errorManager)
throws GssFunctionException {
CssValueNode functionToEval = args.get(0);
//TODO check that the value of functionToEval match a certain pattern or exist ? | CssJavaExpressionNode result = new CssJavaExpressionNode(functionToEval.getValue()); |
jDramaix/gss.gwt | src/main/java/com/google/gwt/resources/gss/ResourceUrlFunction.java | // Path: src/main/java/com/google/gwt/resources/gss/ast/CssDotPathNode.java
// public class CssDotPathNode extends CssValueNode {
//
// public static String resolveExpression(String instance, String path, String prefix, String suffix) {
// String expression = path.replace(".", "().") + "()";
//
// if (!Strings.isNullOrEmpty(instance)) {
// expression = instance + "." + expression;
// }
//
// if (!Strings.isNullOrEmpty(prefix)) {
// expression = "\"" + Generator.escape(prefix) + "\" + " + expression;
// }
//
// if (!Strings.isNullOrEmpty(suffix)) {
// expression += " + \"" + Generator.escape(suffix) + "\"";
// }
//
// return expression;
// }
//
// private String suffix;
// private String prefix;
// private String path;
// private String instance;
//
// public CssDotPathNode(String dotPath, String prefix, String suffix, SourceCodeLocation sourceCodeLocation) {
// this(null, dotPath, prefix, suffix, sourceCodeLocation);
// }
//
// public CssDotPathNode(String instance, String dotPath, String prefix, String suffix,
// SourceCodeLocation sourceCodeLocation) {
// super(resolveExpression(instance, dotPath, prefix, suffix), sourceCodeLocation);
//
// this.prefix = prefix;
// this.suffix = suffix;
// this.path = dotPath;
// this.instance = instance;
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssDotPathNode(instance, path, prefix, suffix, getSourceCodeLocation());
// }
//
// public String getPath() {
// return path;
// }
//
// public String getSuffix() {
// return suffix;
// }
//
// public String getPrefix() {
// return prefix;
// }
//
// public String getInstance() {
// return instance;
// }
//
// public List<String> getPathElements() {
// return Arrays.asList(path.split("\\."));
// }
// }
//
// Path: src/main/java/com/google/gwt/resources/gss/ast/CssJavaExpressionNode.java
// public class CssJavaExpressionNode extends CssValueNode {
//
// public CssJavaExpressionNode(String expression) {
// this(expression, null);
// }
//
// public CssJavaExpressionNode(String expression, SourceCodeLocation sourceCodeLocation) {
// super(expression, sourceCodeLocation);
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssJavaExpressionNode(getValue());
// }
//
// @Override
// public String toString() {
// return "Java expression : " + getValue();
// }
// }
| import com.google.common.collect.ImmutableList;
import com.google.common.css.SourceCodeLocation;
import com.google.common.css.compiler.ast.CssFunctionArgumentsNode;
import com.google.common.css.compiler.ast.CssFunctionNode;
import com.google.common.css.compiler.ast.CssValueNode;
import com.google.common.css.compiler.ast.ErrorManager;
import com.google.common.css.compiler.ast.GssError;
import com.google.common.css.compiler.ast.GssFunction;
import com.google.common.css.compiler.ast.GssFunctionException;
import com.google.common.css.compiler.gssfunctions.GssFunctions;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.JType;
import com.google.gwt.core.ext.typeinfo.NotFoundException;
import com.google.gwt.resources.client.DataResource;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.resources.ext.ResourceContext;
import com.google.gwt.resources.ext.ResourceGeneratorUtil;
import com.google.gwt.resources.gss.ast.CssDotPathNode;
import com.google.gwt.resources.gss.ast.CssJavaExpressionNode;
import java.util.List; | public static String getName() {
return "resourceUrl";
}
@Override
public Integer getNumExpectedArguments() {
return 1;
}
@Override
public List<CssValueNode> getCallResultNodes(List<CssValueNode> cssValueNodes, ErrorManager errorManager)
throws GssFunctionException {
CssValueNode functionToEval = cssValueNodes.get(0);
String value = functionToEval.getValue();
SourceCodeLocation location = functionToEval.getSourceCodeLocation();
String javaExpression = buildJavaExpression(value, location, errorManager);
CssFunctionNode urlNode = buildUrlNode(javaExpression, location);
return ImmutableList.<CssValueNode>of(urlNode);
}
@Override
public String getCallResultString(List<String> strings) throws GssFunctionException {
return strings.get(0);
}
private String buildJavaExpression(String value, SourceCodeLocation location,
ErrorManager errorManager) throws GssFunctionException { | // Path: src/main/java/com/google/gwt/resources/gss/ast/CssDotPathNode.java
// public class CssDotPathNode extends CssValueNode {
//
// public static String resolveExpression(String instance, String path, String prefix, String suffix) {
// String expression = path.replace(".", "().") + "()";
//
// if (!Strings.isNullOrEmpty(instance)) {
// expression = instance + "." + expression;
// }
//
// if (!Strings.isNullOrEmpty(prefix)) {
// expression = "\"" + Generator.escape(prefix) + "\" + " + expression;
// }
//
// if (!Strings.isNullOrEmpty(suffix)) {
// expression += " + \"" + Generator.escape(suffix) + "\"";
// }
//
// return expression;
// }
//
// private String suffix;
// private String prefix;
// private String path;
// private String instance;
//
// public CssDotPathNode(String dotPath, String prefix, String suffix, SourceCodeLocation sourceCodeLocation) {
// this(null, dotPath, prefix, suffix, sourceCodeLocation);
// }
//
// public CssDotPathNode(String instance, String dotPath, String prefix, String suffix,
// SourceCodeLocation sourceCodeLocation) {
// super(resolveExpression(instance, dotPath, prefix, suffix), sourceCodeLocation);
//
// this.prefix = prefix;
// this.suffix = suffix;
// this.path = dotPath;
// this.instance = instance;
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssDotPathNode(instance, path, prefix, suffix, getSourceCodeLocation());
// }
//
// public String getPath() {
// return path;
// }
//
// public String getSuffix() {
// return suffix;
// }
//
// public String getPrefix() {
// return prefix;
// }
//
// public String getInstance() {
// return instance;
// }
//
// public List<String> getPathElements() {
// return Arrays.asList(path.split("\\."));
// }
// }
//
// Path: src/main/java/com/google/gwt/resources/gss/ast/CssJavaExpressionNode.java
// public class CssJavaExpressionNode extends CssValueNode {
//
// public CssJavaExpressionNode(String expression) {
// this(expression, null);
// }
//
// public CssJavaExpressionNode(String expression, SourceCodeLocation sourceCodeLocation) {
// super(expression, sourceCodeLocation);
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssJavaExpressionNode(getValue());
// }
//
// @Override
// public String toString() {
// return "Java expression : " + getValue();
// }
// }
// Path: src/main/java/com/google/gwt/resources/gss/ResourceUrlFunction.java
import com.google.common.collect.ImmutableList;
import com.google.common.css.SourceCodeLocation;
import com.google.common.css.compiler.ast.CssFunctionArgumentsNode;
import com.google.common.css.compiler.ast.CssFunctionNode;
import com.google.common.css.compiler.ast.CssValueNode;
import com.google.common.css.compiler.ast.ErrorManager;
import com.google.common.css.compiler.ast.GssError;
import com.google.common.css.compiler.ast.GssFunction;
import com.google.common.css.compiler.ast.GssFunctionException;
import com.google.common.css.compiler.gssfunctions.GssFunctions;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.JType;
import com.google.gwt.core.ext.typeinfo.NotFoundException;
import com.google.gwt.resources.client.DataResource;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.resources.ext.ResourceContext;
import com.google.gwt.resources.ext.ResourceGeneratorUtil;
import com.google.gwt.resources.gss.ast.CssDotPathNode;
import com.google.gwt.resources.gss.ast.CssJavaExpressionNode;
import java.util.List;
public static String getName() {
return "resourceUrl";
}
@Override
public Integer getNumExpectedArguments() {
return 1;
}
@Override
public List<CssValueNode> getCallResultNodes(List<CssValueNode> cssValueNodes, ErrorManager errorManager)
throws GssFunctionException {
CssValueNode functionToEval = cssValueNodes.get(0);
String value = functionToEval.getValue();
SourceCodeLocation location = functionToEval.getSourceCodeLocation();
String javaExpression = buildJavaExpression(value, location, errorManager);
CssFunctionNode urlNode = buildUrlNode(javaExpression, location);
return ImmutableList.<CssValueNode>of(urlNode);
}
@Override
public String getCallResultString(List<String> strings) throws GssFunctionException {
return strings.get(0);
}
private String buildJavaExpression(String value, SourceCodeLocation location,
ErrorManager errorManager) throws GssFunctionException { | CssDotPathNode dotPathValue = new CssDotPathNode(value, "", "", location); |
jDramaix/gss.gwt | src/main/java/com/google/gwt/resources/gss/ResourceUrlFunction.java | // Path: src/main/java/com/google/gwt/resources/gss/ast/CssDotPathNode.java
// public class CssDotPathNode extends CssValueNode {
//
// public static String resolveExpression(String instance, String path, String prefix, String suffix) {
// String expression = path.replace(".", "().") + "()";
//
// if (!Strings.isNullOrEmpty(instance)) {
// expression = instance + "." + expression;
// }
//
// if (!Strings.isNullOrEmpty(prefix)) {
// expression = "\"" + Generator.escape(prefix) + "\" + " + expression;
// }
//
// if (!Strings.isNullOrEmpty(suffix)) {
// expression += " + \"" + Generator.escape(suffix) + "\"";
// }
//
// return expression;
// }
//
// private String suffix;
// private String prefix;
// private String path;
// private String instance;
//
// public CssDotPathNode(String dotPath, String prefix, String suffix, SourceCodeLocation sourceCodeLocation) {
// this(null, dotPath, prefix, suffix, sourceCodeLocation);
// }
//
// public CssDotPathNode(String instance, String dotPath, String prefix, String suffix,
// SourceCodeLocation sourceCodeLocation) {
// super(resolveExpression(instance, dotPath, prefix, suffix), sourceCodeLocation);
//
// this.prefix = prefix;
// this.suffix = suffix;
// this.path = dotPath;
// this.instance = instance;
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssDotPathNode(instance, path, prefix, suffix, getSourceCodeLocation());
// }
//
// public String getPath() {
// return path;
// }
//
// public String getSuffix() {
// return suffix;
// }
//
// public String getPrefix() {
// return prefix;
// }
//
// public String getInstance() {
// return instance;
// }
//
// public List<String> getPathElements() {
// return Arrays.asList(path.split("\\."));
// }
// }
//
// Path: src/main/java/com/google/gwt/resources/gss/ast/CssJavaExpressionNode.java
// public class CssJavaExpressionNode extends CssValueNode {
//
// public CssJavaExpressionNode(String expression) {
// this(expression, null);
// }
//
// public CssJavaExpressionNode(String expression, SourceCodeLocation sourceCodeLocation) {
// super(expression, sourceCodeLocation);
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssJavaExpressionNode(getValue());
// }
//
// @Override
// public String toString() {
// return "Java expression : " + getValue();
// }
// }
| import com.google.common.collect.ImmutableList;
import com.google.common.css.SourceCodeLocation;
import com.google.common.css.compiler.ast.CssFunctionArgumentsNode;
import com.google.common.css.compiler.ast.CssFunctionNode;
import com.google.common.css.compiler.ast.CssValueNode;
import com.google.common.css.compiler.ast.ErrorManager;
import com.google.common.css.compiler.ast.GssError;
import com.google.common.css.compiler.ast.GssFunction;
import com.google.common.css.compiler.ast.GssFunctionException;
import com.google.common.css.compiler.gssfunctions.GssFunctions;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.JType;
import com.google.gwt.core.ext.typeinfo.NotFoundException;
import com.google.gwt.resources.client.DataResource;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.resources.ext.ResourceContext;
import com.google.gwt.resources.ext.ResourceGeneratorUtil;
import com.google.gwt.resources.gss.ast.CssDotPathNode;
import com.google.gwt.resources.gss.ast.CssJavaExpressionNode;
import java.util.List; | assertMethodIsValidResource(location, dotPathValue.getPathElements(), errorManager);
return context.getImplementationSimpleSourceName() + ".this."
+ dotPathValue.getValue() + ".getSafeUri().asString()";
}
private void assertMethodIsValidResource(SourceCodeLocation location, List<String> pathElements,
ErrorManager errorManager) throws GssFunctionException {
JType methodType;
try {
methodType = ResourceGeneratorUtil.getMethodByPath(context.getClientBundleType(),
pathElements, null).getReturnType();
} catch (NotFoundException e) {
String message = e.getMessage();
errorManager.report(new GssError(message, location));
throw new GssFunctionException(message, e);
}
if (!dataResourceType.isAssignableFrom((JClassType) methodType) &&
!imageResourceType.isAssignableFrom((JClassType) methodType)) {
String message = "Invalid method type for url substitution: " + methodType + ". " +
"Only DataResource and ImageResource are supported.";
errorManager.report(new GssError(message, location));
throw new GssFunctionException(message);
}
}
private CssFunctionNode buildUrlNode(String javaExpression, SourceCodeLocation location) {
CssFunctionNode urlNode = GssFunctions.createUrlNode("", location); | // Path: src/main/java/com/google/gwt/resources/gss/ast/CssDotPathNode.java
// public class CssDotPathNode extends CssValueNode {
//
// public static String resolveExpression(String instance, String path, String prefix, String suffix) {
// String expression = path.replace(".", "().") + "()";
//
// if (!Strings.isNullOrEmpty(instance)) {
// expression = instance + "." + expression;
// }
//
// if (!Strings.isNullOrEmpty(prefix)) {
// expression = "\"" + Generator.escape(prefix) + "\" + " + expression;
// }
//
// if (!Strings.isNullOrEmpty(suffix)) {
// expression += " + \"" + Generator.escape(suffix) + "\"";
// }
//
// return expression;
// }
//
// private String suffix;
// private String prefix;
// private String path;
// private String instance;
//
// public CssDotPathNode(String dotPath, String prefix, String suffix, SourceCodeLocation sourceCodeLocation) {
// this(null, dotPath, prefix, suffix, sourceCodeLocation);
// }
//
// public CssDotPathNode(String instance, String dotPath, String prefix, String suffix,
// SourceCodeLocation sourceCodeLocation) {
// super(resolveExpression(instance, dotPath, prefix, suffix), sourceCodeLocation);
//
// this.prefix = prefix;
// this.suffix = suffix;
// this.path = dotPath;
// this.instance = instance;
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssDotPathNode(instance, path, prefix, suffix, getSourceCodeLocation());
// }
//
// public String getPath() {
// return path;
// }
//
// public String getSuffix() {
// return suffix;
// }
//
// public String getPrefix() {
// return prefix;
// }
//
// public String getInstance() {
// return instance;
// }
//
// public List<String> getPathElements() {
// return Arrays.asList(path.split("\\."));
// }
// }
//
// Path: src/main/java/com/google/gwt/resources/gss/ast/CssJavaExpressionNode.java
// public class CssJavaExpressionNode extends CssValueNode {
//
// public CssJavaExpressionNode(String expression) {
// this(expression, null);
// }
//
// public CssJavaExpressionNode(String expression, SourceCodeLocation sourceCodeLocation) {
// super(expression, sourceCodeLocation);
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssJavaExpressionNode(getValue());
// }
//
// @Override
// public String toString() {
// return "Java expression : " + getValue();
// }
// }
// Path: src/main/java/com/google/gwt/resources/gss/ResourceUrlFunction.java
import com.google.common.collect.ImmutableList;
import com.google.common.css.SourceCodeLocation;
import com.google.common.css.compiler.ast.CssFunctionArgumentsNode;
import com.google.common.css.compiler.ast.CssFunctionNode;
import com.google.common.css.compiler.ast.CssValueNode;
import com.google.common.css.compiler.ast.ErrorManager;
import com.google.common.css.compiler.ast.GssError;
import com.google.common.css.compiler.ast.GssFunction;
import com.google.common.css.compiler.ast.GssFunctionException;
import com.google.common.css.compiler.gssfunctions.GssFunctions;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.JType;
import com.google.gwt.core.ext.typeinfo.NotFoundException;
import com.google.gwt.resources.client.DataResource;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.resources.ext.ResourceContext;
import com.google.gwt.resources.ext.ResourceGeneratorUtil;
import com.google.gwt.resources.gss.ast.CssDotPathNode;
import com.google.gwt.resources.gss.ast.CssJavaExpressionNode;
import java.util.List;
assertMethodIsValidResource(location, dotPathValue.getPathElements(), errorManager);
return context.getImplementationSimpleSourceName() + ".this."
+ dotPathValue.getValue() + ".getSafeUri().asString()";
}
private void assertMethodIsValidResource(SourceCodeLocation location, List<String> pathElements,
ErrorManager errorManager) throws GssFunctionException {
JType methodType;
try {
methodType = ResourceGeneratorUtil.getMethodByPath(context.getClientBundleType(),
pathElements, null).getReturnType();
} catch (NotFoundException e) {
String message = e.getMessage();
errorManager.report(new GssError(message, location));
throw new GssFunctionException(message, e);
}
if (!dataResourceType.isAssignableFrom((JClassType) methodType) &&
!imageResourceType.isAssignableFrom((JClassType) methodType)) {
String message = "Invalid method type for url substitution: " + methodType + ". " +
"Only DataResource and ImageResource are supported.";
errorManager.report(new GssError(message, location));
throw new GssFunctionException(message);
}
}
private CssFunctionNode buildUrlNode(String javaExpression, SourceCodeLocation location) {
CssFunctionNode urlNode = GssFunctions.createUrlNode("", location); | CssJavaExpressionNode cssJavaExpressionNode = new CssJavaExpressionNode(javaExpression); |
jDramaix/gss.gwt | src/test/java/com/google/gwt/resources/client/AutoConversionTest.java | // Path: src/test/java/com/google/gwt/resources/client/AutoConversionBundle.java
// interface ConstantConditional extends GssResource {
// String foo();
// String color();
// int width();
// int height();
// }
//
// Path: src/test/java/com/google/gwt/resources/client/AutoConversionBundle.java
// interface ConstantRenaming extends GssResource {
// int myConstant();
// String my_constant();
// int ie6();
// int gecko1_8();
// }
//
// Path: src/test/java/com/google/gwt/resources/client/AutoConversionBundle.java
// interface LenientExternal extends GssResource {
// String nonObfuscated();
// String nonObfuscated2();
// String nonObfuscated3();
// String obfuscated();
// }
| import com.google.gwt.core.client.GWT;
import com.google.gwt.junit.client.GWTTestCase;
import com.google.gwt.resources.client.AutoConversionBundle.ConstantConditional;
import com.google.gwt.resources.client.AutoConversionBundle.ConstantRenaming;
import com.google.gwt.resources.client.AutoConversionBundle.LenientExternal; | /*
* Copyright 2014 Julien Dramaix.
*
* 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.gwt.resources.client;
public class AutoConversionTest extends GWTTestCase {
@Override
public String getModuleName() {
return "com.google.gwt.resources.AutoConversion";
}
public void testConstantRenaming() { | // Path: src/test/java/com/google/gwt/resources/client/AutoConversionBundle.java
// interface ConstantConditional extends GssResource {
// String foo();
// String color();
// int width();
// int height();
// }
//
// Path: src/test/java/com/google/gwt/resources/client/AutoConversionBundle.java
// interface ConstantRenaming extends GssResource {
// int myConstant();
// String my_constant();
// int ie6();
// int gecko1_8();
// }
//
// Path: src/test/java/com/google/gwt/resources/client/AutoConversionBundle.java
// interface LenientExternal extends GssResource {
// String nonObfuscated();
// String nonObfuscated2();
// String nonObfuscated3();
// String obfuscated();
// }
// Path: src/test/java/com/google/gwt/resources/client/AutoConversionTest.java
import com.google.gwt.core.client.GWT;
import com.google.gwt.junit.client.GWTTestCase;
import com.google.gwt.resources.client.AutoConversionBundle.ConstantConditional;
import com.google.gwt.resources.client.AutoConversionBundle.ConstantRenaming;
import com.google.gwt.resources.client.AutoConversionBundle.LenientExternal;
/*
* Copyright 2014 Julien Dramaix.
*
* 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.gwt.resources.client;
public class AutoConversionTest extends GWTTestCase {
@Override
public String getModuleName() {
return "com.google.gwt.resources.AutoConversion";
}
public void testConstantRenaming() { | ConstantRenaming constantRenaming = res().constantRenaming(); |
jDramaix/gss.gwt | src/test/java/com/google/gwt/resources/client/AutoConversionTest.java | // Path: src/test/java/com/google/gwt/resources/client/AutoConversionBundle.java
// interface ConstantConditional extends GssResource {
// String foo();
// String color();
// int width();
// int height();
// }
//
// Path: src/test/java/com/google/gwt/resources/client/AutoConversionBundle.java
// interface ConstantRenaming extends GssResource {
// int myConstant();
// String my_constant();
// int ie6();
// int gecko1_8();
// }
//
// Path: src/test/java/com/google/gwt/resources/client/AutoConversionBundle.java
// interface LenientExternal extends GssResource {
// String nonObfuscated();
// String nonObfuscated2();
// String nonObfuscated3();
// String obfuscated();
// }
| import com.google.gwt.core.client.GWT;
import com.google.gwt.junit.client.GWTTestCase;
import com.google.gwt.resources.client.AutoConversionBundle.ConstantConditional;
import com.google.gwt.resources.client.AutoConversionBundle.ConstantRenaming;
import com.google.gwt.resources.client.AutoConversionBundle.LenientExternal; | /*
* Copyright 2014 Julien Dramaix.
*
* 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.gwt.resources.client;
public class AutoConversionTest extends GWTTestCase {
@Override
public String getModuleName() {
return "com.google.gwt.resources.AutoConversion";
}
public void testConstantRenaming() {
ConstantRenaming constantRenaming = res().constantRenaming();
assertEquals(45, constantRenaming.myConstant());
assertEquals("38px", constantRenaming.my_constant());
assertEquals(0, constantRenaming.ie6());
assertEquals(0, constantRenaming.gecko1_8());
}
public void testConstantConditional() { | // Path: src/test/java/com/google/gwt/resources/client/AutoConversionBundle.java
// interface ConstantConditional extends GssResource {
// String foo();
// String color();
// int width();
// int height();
// }
//
// Path: src/test/java/com/google/gwt/resources/client/AutoConversionBundle.java
// interface ConstantRenaming extends GssResource {
// int myConstant();
// String my_constant();
// int ie6();
// int gecko1_8();
// }
//
// Path: src/test/java/com/google/gwt/resources/client/AutoConversionBundle.java
// interface LenientExternal extends GssResource {
// String nonObfuscated();
// String nonObfuscated2();
// String nonObfuscated3();
// String obfuscated();
// }
// Path: src/test/java/com/google/gwt/resources/client/AutoConversionTest.java
import com.google.gwt.core.client.GWT;
import com.google.gwt.junit.client.GWTTestCase;
import com.google.gwt.resources.client.AutoConversionBundle.ConstantConditional;
import com.google.gwt.resources.client.AutoConversionBundle.ConstantRenaming;
import com.google.gwt.resources.client.AutoConversionBundle.LenientExternal;
/*
* Copyright 2014 Julien Dramaix.
*
* 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.gwt.resources.client;
public class AutoConversionTest extends GWTTestCase {
@Override
public String getModuleName() {
return "com.google.gwt.resources.AutoConversion";
}
public void testConstantRenaming() {
ConstantRenaming constantRenaming = res().constantRenaming();
assertEquals(45, constantRenaming.myConstant());
assertEquals("38px", constantRenaming.my_constant());
assertEquals(0, constantRenaming.ie6());
assertEquals(0, constantRenaming.gecko1_8());
}
public void testConstantConditional() { | ConstantConditional constantConditional = res().constantConditional(); |
jDramaix/gss.gwt | src/test/java/com/google/gwt/resources/client/AutoConversionTest.java | // Path: src/test/java/com/google/gwt/resources/client/AutoConversionBundle.java
// interface ConstantConditional extends GssResource {
// String foo();
// String color();
// int width();
// int height();
// }
//
// Path: src/test/java/com/google/gwt/resources/client/AutoConversionBundle.java
// interface ConstantRenaming extends GssResource {
// int myConstant();
// String my_constant();
// int ie6();
// int gecko1_8();
// }
//
// Path: src/test/java/com/google/gwt/resources/client/AutoConversionBundle.java
// interface LenientExternal extends GssResource {
// String nonObfuscated();
// String nonObfuscated2();
// String nonObfuscated3();
// String obfuscated();
// }
| import com.google.gwt.core.client.GWT;
import com.google.gwt.junit.client.GWTTestCase;
import com.google.gwt.resources.client.AutoConversionBundle.ConstantConditional;
import com.google.gwt.resources.client.AutoConversionBundle.ConstantRenaming;
import com.google.gwt.resources.client.AutoConversionBundle.LenientExternal; | /*
* Copyright 2014 Julien Dramaix.
*
* 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.gwt.resources.client;
public class AutoConversionTest extends GWTTestCase {
@Override
public String getModuleName() {
return "com.google.gwt.resources.AutoConversion";
}
public void testConstantRenaming() {
ConstantRenaming constantRenaming = res().constantRenaming();
assertEquals(45, constantRenaming.myConstant());
assertEquals("38px", constantRenaming.my_constant());
assertEquals(0, constantRenaming.ie6());
assertEquals(0, constantRenaming.gecko1_8());
}
public void testConstantConditional() {
ConstantConditional constantConditional = res().constantConditional();
String expectedCss = "." + constantConditional.foo() + "{width:15px;height:10px;color:black}";
assertEquals(expectedCss, constantConditional.getText());
assertEquals("black", constantConditional.color());
assertEquals(15, constantConditional.width());
assertEquals(10, constantConditional.height());
}
public void testLenientExternal() { | // Path: src/test/java/com/google/gwt/resources/client/AutoConversionBundle.java
// interface ConstantConditional extends GssResource {
// String foo();
// String color();
// int width();
// int height();
// }
//
// Path: src/test/java/com/google/gwt/resources/client/AutoConversionBundle.java
// interface ConstantRenaming extends GssResource {
// int myConstant();
// String my_constant();
// int ie6();
// int gecko1_8();
// }
//
// Path: src/test/java/com/google/gwt/resources/client/AutoConversionBundle.java
// interface LenientExternal extends GssResource {
// String nonObfuscated();
// String nonObfuscated2();
// String nonObfuscated3();
// String obfuscated();
// }
// Path: src/test/java/com/google/gwt/resources/client/AutoConversionTest.java
import com.google.gwt.core.client.GWT;
import com.google.gwt.junit.client.GWTTestCase;
import com.google.gwt.resources.client.AutoConversionBundle.ConstantConditional;
import com.google.gwt.resources.client.AutoConversionBundle.ConstantRenaming;
import com.google.gwt.resources.client.AutoConversionBundle.LenientExternal;
/*
* Copyright 2014 Julien Dramaix.
*
* 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.gwt.resources.client;
public class AutoConversionTest extends GWTTestCase {
@Override
public String getModuleName() {
return "com.google.gwt.resources.AutoConversion";
}
public void testConstantRenaming() {
ConstantRenaming constantRenaming = res().constantRenaming();
assertEquals(45, constantRenaming.myConstant());
assertEquals("38px", constantRenaming.my_constant());
assertEquals(0, constantRenaming.ie6());
assertEquals(0, constantRenaming.gecko1_8());
}
public void testConstantConditional() {
ConstantConditional constantConditional = res().constantConditional();
String expectedCss = "." + constantConditional.foo() + "{width:15px;height:10px;color:black}";
assertEquals(expectedCss, constantConditional.getText());
assertEquals("black", constantConditional.color());
assertEquals(15, constantConditional.width());
assertEquals(10, constantConditional.height());
}
public void testLenientExternal() { | LenientExternal lenientExternal = res().lenientExternal(); |
jDramaix/gss.gwt | src/test/java/com/google/gwt/resources/client/DebugObfuscationStyleTest.java | // Path: src/test/java/com/google/gwt/resources/client/TestResources.java
// interface ClassNameAnnotation extends GssResource {
// @ClassName("renamed-class")
// String renamedClass();
//
// String nonRenamedClass();
// }
| import com.google.gwt.resources.client.TestResources.ClassNameAnnotation; | /*
* Copyright 2014 Julien Dramaix.
*
* 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.gwt.resources.client;
public class DebugObfuscationStyleTest extends RenamingClassNameTest {
@Override
public String getModuleName() {
return "com.google.gwt.resources.Debug";
}
public void testClassesRenaming() { | // Path: src/test/java/com/google/gwt/resources/client/TestResources.java
// interface ClassNameAnnotation extends GssResource {
// @ClassName("renamed-class")
// String renamedClass();
//
// String nonRenamedClass();
// }
// Path: src/test/java/com/google/gwt/resources/client/DebugObfuscationStyleTest.java
import com.google.gwt.resources.client.TestResources.ClassNameAnnotation;
/*
* Copyright 2014 Julien Dramaix.
*
* 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.gwt.resources.client;
public class DebugObfuscationStyleTest extends RenamingClassNameTest {
@Override
public String getModuleName() {
return "com.google.gwt.resources.Debug";
}
public void testClassesRenaming() { | ClassNameAnnotation classNameAnnotation = res().classNameAnnotation(); |
jDramaix/gss.gwt | src/main/java/com/google/gwt/resources/gss/CssPrinter.java | // Path: src/main/java/com/google/gwt/resources/gss/ast/CssDotPathNode.java
// public class CssDotPathNode extends CssValueNode {
//
// public static String resolveExpression(String instance, String path, String prefix, String suffix) {
// String expression = path.replace(".", "().") + "()";
//
// if (!Strings.isNullOrEmpty(instance)) {
// expression = instance + "." + expression;
// }
//
// if (!Strings.isNullOrEmpty(prefix)) {
// expression = "\"" + Generator.escape(prefix) + "\" + " + expression;
// }
//
// if (!Strings.isNullOrEmpty(suffix)) {
// expression += " + \"" + Generator.escape(suffix) + "\"";
// }
//
// return expression;
// }
//
// private String suffix;
// private String prefix;
// private String path;
// private String instance;
//
// public CssDotPathNode(String dotPath, String prefix, String suffix, SourceCodeLocation sourceCodeLocation) {
// this(null, dotPath, prefix, suffix, sourceCodeLocation);
// }
//
// public CssDotPathNode(String instance, String dotPath, String prefix, String suffix,
// SourceCodeLocation sourceCodeLocation) {
// super(resolveExpression(instance, dotPath, prefix, suffix), sourceCodeLocation);
//
// this.prefix = prefix;
// this.suffix = suffix;
// this.path = dotPath;
// this.instance = instance;
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssDotPathNode(instance, path, prefix, suffix, getSourceCodeLocation());
// }
//
// public String getPath() {
// return path;
// }
//
// public String getSuffix() {
// return suffix;
// }
//
// public String getPrefix() {
// return prefix;
// }
//
// public String getInstance() {
// return instance;
// }
//
// public List<String> getPathElements() {
// return Arrays.asList(path.split("\\."));
// }
// }
//
// Path: src/main/java/com/google/gwt/resources/gss/ast/CssJavaExpressionNode.java
// public class CssJavaExpressionNode extends CssValueNode {
//
// public CssJavaExpressionNode(String expression) {
// this(expression, null);
// }
//
// public CssJavaExpressionNode(String expression, SourceCodeLocation sourceCodeLocation) {
// super(expression, sourceCodeLocation);
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssJavaExpressionNode(getValue());
// }
//
// @Override
// public String toString() {
// return "Java expression : " + getValue();
// }
// }
//
// Path: src/main/java/com/google/gwt/resources/gss/ast/CssRuntimeConditionalRuleNode.java
// public class CssRuntimeConditionalRuleNode extends CssConditionalRuleNode {
//
// public CssRuntimeConditionalRuleNode(CssConditionalRuleNode node,
// @Nullable CssJavaExpressionNode condition) {
// super(node.getType(), node.getName().deepCopy(), null,
// node.getBlock() != null ? node.getBlock().deepCopy() : null);
// setSourceCodeLocation(node.getSourceCodeLocation());
//
// if (condition != null) {
// setRuntimeCondition(condition);
// }
// }
//
// /**
// * Copy constructor.
// *
// * @param node
// */
// public CssRuntimeConditionalRuleNode(CssRuntimeConditionalRuleNode node) {
// this(node, node.getRuntimeCondition());
// }
//
// /**
// * Can only be called after the node is completely built (meaning it has
// * the condition set).
// */
// public CssJavaExpressionNode getRuntimeCondition() {
// if (getType() == Type.ELSE) {
// Preconditions.checkState(getParametersCount() == 0);
// return null;
// }
//
// Preconditions.checkState(getParametersCount() == 1);
// return (CssJavaExpressionNode) this.getParameters().get(0);
// }
//
// void setRuntimeCondition(CssJavaExpressionNode condition) {
// Preconditions.checkState(getType() != Type.ELSE);
// Preconditions.checkState(getParametersCount() <= 1);
// this.setParameters(ImmutableList.<CssValueNode>of(condition));
// }
//
// @Override
// public CssConditionalRuleNode deepCopy() {
// return new CssRuntimeConditionalRuleNode(this);
// }
// }
| import java.util.Stack;
import com.google.common.css.compiler.ast.CssAtRuleNode.Type;
import com.google.common.css.compiler.ast.CssConditionalBlockNode;
import com.google.common.css.compiler.ast.CssConditionalRuleNode;
import com.google.common.css.compiler.ast.CssNode;
import com.google.common.css.compiler.ast.CssRootNode;
import com.google.common.css.compiler.ast.CssTree;
import com.google.common.css.compiler.ast.CssUnknownAtRuleNode;
import com.google.common.css.compiler.ast.CssValueNode;
import com.google.common.css.compiler.passes.CompactPrinter;
import com.google.gwt.core.ext.Generator;
import com.google.gwt.resources.gss.ast.CssDotPathNode;
import com.google.gwt.resources.gss.ast.CssJavaExpressionNode;
import com.google.gwt.resources.gss.ast.CssRuntimeConditionalRuleNode; | @Override
public boolean enterConditionalBlock(CssConditionalBlockNode node) {
masterStringBuilder.append(flushInternalStringBuilder());
masterStringBuilder.append(CONTATENATION_BLOCK);
elseNodeFound.push(false);
return true;
}
@Override
public void leaveConditionalBlock(CssConditionalBlockNode block) {
if (!elseNodeFound.pop()) {
masterStringBuilder.append("\"\"");
}
masterStringBuilder.append(CONTATENATION_BLOCK);
// reset concatenation counter
concatenationNumber = 0;
}
@Override
public boolean enterConditionalRule(CssConditionalRuleNode node) {
if (node.getType() == Type.ELSE) {
elseNodeFound.pop();
elseNodeFound.push(true);
masterStringBuilder.append(LEFT_BRACKET);
} else { | // Path: src/main/java/com/google/gwt/resources/gss/ast/CssDotPathNode.java
// public class CssDotPathNode extends CssValueNode {
//
// public static String resolveExpression(String instance, String path, String prefix, String suffix) {
// String expression = path.replace(".", "().") + "()";
//
// if (!Strings.isNullOrEmpty(instance)) {
// expression = instance + "." + expression;
// }
//
// if (!Strings.isNullOrEmpty(prefix)) {
// expression = "\"" + Generator.escape(prefix) + "\" + " + expression;
// }
//
// if (!Strings.isNullOrEmpty(suffix)) {
// expression += " + \"" + Generator.escape(suffix) + "\"";
// }
//
// return expression;
// }
//
// private String suffix;
// private String prefix;
// private String path;
// private String instance;
//
// public CssDotPathNode(String dotPath, String prefix, String suffix, SourceCodeLocation sourceCodeLocation) {
// this(null, dotPath, prefix, suffix, sourceCodeLocation);
// }
//
// public CssDotPathNode(String instance, String dotPath, String prefix, String suffix,
// SourceCodeLocation sourceCodeLocation) {
// super(resolveExpression(instance, dotPath, prefix, suffix), sourceCodeLocation);
//
// this.prefix = prefix;
// this.suffix = suffix;
// this.path = dotPath;
// this.instance = instance;
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssDotPathNode(instance, path, prefix, suffix, getSourceCodeLocation());
// }
//
// public String getPath() {
// return path;
// }
//
// public String getSuffix() {
// return suffix;
// }
//
// public String getPrefix() {
// return prefix;
// }
//
// public String getInstance() {
// return instance;
// }
//
// public List<String> getPathElements() {
// return Arrays.asList(path.split("\\."));
// }
// }
//
// Path: src/main/java/com/google/gwt/resources/gss/ast/CssJavaExpressionNode.java
// public class CssJavaExpressionNode extends CssValueNode {
//
// public CssJavaExpressionNode(String expression) {
// this(expression, null);
// }
//
// public CssJavaExpressionNode(String expression, SourceCodeLocation sourceCodeLocation) {
// super(expression, sourceCodeLocation);
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssJavaExpressionNode(getValue());
// }
//
// @Override
// public String toString() {
// return "Java expression : " + getValue();
// }
// }
//
// Path: src/main/java/com/google/gwt/resources/gss/ast/CssRuntimeConditionalRuleNode.java
// public class CssRuntimeConditionalRuleNode extends CssConditionalRuleNode {
//
// public CssRuntimeConditionalRuleNode(CssConditionalRuleNode node,
// @Nullable CssJavaExpressionNode condition) {
// super(node.getType(), node.getName().deepCopy(), null,
// node.getBlock() != null ? node.getBlock().deepCopy() : null);
// setSourceCodeLocation(node.getSourceCodeLocation());
//
// if (condition != null) {
// setRuntimeCondition(condition);
// }
// }
//
// /**
// * Copy constructor.
// *
// * @param node
// */
// public CssRuntimeConditionalRuleNode(CssRuntimeConditionalRuleNode node) {
// this(node, node.getRuntimeCondition());
// }
//
// /**
// * Can only be called after the node is completely built (meaning it has
// * the condition set).
// */
// public CssJavaExpressionNode getRuntimeCondition() {
// if (getType() == Type.ELSE) {
// Preconditions.checkState(getParametersCount() == 0);
// return null;
// }
//
// Preconditions.checkState(getParametersCount() == 1);
// return (CssJavaExpressionNode) this.getParameters().get(0);
// }
//
// void setRuntimeCondition(CssJavaExpressionNode condition) {
// Preconditions.checkState(getType() != Type.ELSE);
// Preconditions.checkState(getParametersCount() <= 1);
// this.setParameters(ImmutableList.<CssValueNode>of(condition));
// }
//
// @Override
// public CssConditionalRuleNode deepCopy() {
// return new CssRuntimeConditionalRuleNode(this);
// }
// }
// Path: src/main/java/com/google/gwt/resources/gss/CssPrinter.java
import java.util.Stack;
import com.google.common.css.compiler.ast.CssAtRuleNode.Type;
import com.google.common.css.compiler.ast.CssConditionalBlockNode;
import com.google.common.css.compiler.ast.CssConditionalRuleNode;
import com.google.common.css.compiler.ast.CssNode;
import com.google.common.css.compiler.ast.CssRootNode;
import com.google.common.css.compiler.ast.CssTree;
import com.google.common.css.compiler.ast.CssUnknownAtRuleNode;
import com.google.common.css.compiler.ast.CssValueNode;
import com.google.common.css.compiler.passes.CompactPrinter;
import com.google.gwt.core.ext.Generator;
import com.google.gwt.resources.gss.ast.CssDotPathNode;
import com.google.gwt.resources.gss.ast.CssJavaExpressionNode;
import com.google.gwt.resources.gss.ast.CssRuntimeConditionalRuleNode;
@Override
public boolean enterConditionalBlock(CssConditionalBlockNode node) {
masterStringBuilder.append(flushInternalStringBuilder());
masterStringBuilder.append(CONTATENATION_BLOCK);
elseNodeFound.push(false);
return true;
}
@Override
public void leaveConditionalBlock(CssConditionalBlockNode block) {
if (!elseNodeFound.pop()) {
masterStringBuilder.append("\"\"");
}
masterStringBuilder.append(CONTATENATION_BLOCK);
// reset concatenation counter
concatenationNumber = 0;
}
@Override
public boolean enterConditionalRule(CssConditionalRuleNode node) {
if (node.getType() == Type.ELSE) {
elseNodeFound.pop();
elseNodeFound.push(true);
masterStringBuilder.append(LEFT_BRACKET);
} else { | CssRuntimeConditionalRuleNode conditionalRuleNode = (CssRuntimeConditionalRuleNode) node; |
jDramaix/gss.gwt | src/main/java/com/google/gwt/resources/gss/CssPrinter.java | // Path: src/main/java/com/google/gwt/resources/gss/ast/CssDotPathNode.java
// public class CssDotPathNode extends CssValueNode {
//
// public static String resolveExpression(String instance, String path, String prefix, String suffix) {
// String expression = path.replace(".", "().") + "()";
//
// if (!Strings.isNullOrEmpty(instance)) {
// expression = instance + "." + expression;
// }
//
// if (!Strings.isNullOrEmpty(prefix)) {
// expression = "\"" + Generator.escape(prefix) + "\" + " + expression;
// }
//
// if (!Strings.isNullOrEmpty(suffix)) {
// expression += " + \"" + Generator.escape(suffix) + "\"";
// }
//
// return expression;
// }
//
// private String suffix;
// private String prefix;
// private String path;
// private String instance;
//
// public CssDotPathNode(String dotPath, String prefix, String suffix, SourceCodeLocation sourceCodeLocation) {
// this(null, dotPath, prefix, suffix, sourceCodeLocation);
// }
//
// public CssDotPathNode(String instance, String dotPath, String prefix, String suffix,
// SourceCodeLocation sourceCodeLocation) {
// super(resolveExpression(instance, dotPath, prefix, suffix), sourceCodeLocation);
//
// this.prefix = prefix;
// this.suffix = suffix;
// this.path = dotPath;
// this.instance = instance;
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssDotPathNode(instance, path, prefix, suffix, getSourceCodeLocation());
// }
//
// public String getPath() {
// return path;
// }
//
// public String getSuffix() {
// return suffix;
// }
//
// public String getPrefix() {
// return prefix;
// }
//
// public String getInstance() {
// return instance;
// }
//
// public List<String> getPathElements() {
// return Arrays.asList(path.split("\\."));
// }
// }
//
// Path: src/main/java/com/google/gwt/resources/gss/ast/CssJavaExpressionNode.java
// public class CssJavaExpressionNode extends CssValueNode {
//
// public CssJavaExpressionNode(String expression) {
// this(expression, null);
// }
//
// public CssJavaExpressionNode(String expression, SourceCodeLocation sourceCodeLocation) {
// super(expression, sourceCodeLocation);
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssJavaExpressionNode(getValue());
// }
//
// @Override
// public String toString() {
// return "Java expression : " + getValue();
// }
// }
//
// Path: src/main/java/com/google/gwt/resources/gss/ast/CssRuntimeConditionalRuleNode.java
// public class CssRuntimeConditionalRuleNode extends CssConditionalRuleNode {
//
// public CssRuntimeConditionalRuleNode(CssConditionalRuleNode node,
// @Nullable CssJavaExpressionNode condition) {
// super(node.getType(), node.getName().deepCopy(), null,
// node.getBlock() != null ? node.getBlock().deepCopy() : null);
// setSourceCodeLocation(node.getSourceCodeLocation());
//
// if (condition != null) {
// setRuntimeCondition(condition);
// }
// }
//
// /**
// * Copy constructor.
// *
// * @param node
// */
// public CssRuntimeConditionalRuleNode(CssRuntimeConditionalRuleNode node) {
// this(node, node.getRuntimeCondition());
// }
//
// /**
// * Can only be called after the node is completely built (meaning it has
// * the condition set).
// */
// public CssJavaExpressionNode getRuntimeCondition() {
// if (getType() == Type.ELSE) {
// Preconditions.checkState(getParametersCount() == 0);
// return null;
// }
//
// Preconditions.checkState(getParametersCount() == 1);
// return (CssJavaExpressionNode) this.getParameters().get(0);
// }
//
// void setRuntimeCondition(CssJavaExpressionNode condition) {
// Preconditions.checkState(getType() != Type.ELSE);
// Preconditions.checkState(getParametersCount() <= 1);
// this.setParameters(ImmutableList.<CssValueNode>of(condition));
// }
//
// @Override
// public CssConditionalRuleNode deepCopy() {
// return new CssRuntimeConditionalRuleNode(this);
// }
// }
| import java.util.Stack;
import com.google.common.css.compiler.ast.CssAtRuleNode.Type;
import com.google.common.css.compiler.ast.CssConditionalBlockNode;
import com.google.common.css.compiler.ast.CssConditionalRuleNode;
import com.google.common.css.compiler.ast.CssNode;
import com.google.common.css.compiler.ast.CssRootNode;
import com.google.common.css.compiler.ast.CssTree;
import com.google.common.css.compiler.ast.CssUnknownAtRuleNode;
import com.google.common.css.compiler.ast.CssValueNode;
import com.google.common.css.compiler.passes.CompactPrinter;
import com.google.gwt.core.ext.Generator;
import com.google.gwt.resources.gss.ast.CssDotPathNode;
import com.google.gwt.resources.gss.ast.CssJavaExpressionNode;
import com.google.gwt.resources.gss.ast.CssRuntimeConditionalRuleNode; | masterStringBuilder.append(conditionalRuleNode.getRuntimeCondition().getValue());
masterStringBuilder.append(") ? (");
// reset concatenation counter
concatenationNumber = 0;
}
return true;
}
@Override
public void leaveConditionalRule(CssConditionalRuleNode node) {
masterStringBuilder.append(flushInternalStringBuilder()).append(RIGHT_BRACKET);
if (node.getType() != Type.ELSE) {
masterStringBuilder.append(" : ");
}
}
@Override
public boolean enterUnknownAtRule(CssUnknownAtRuleNode node) {
if (EXTERNAL.equals(node.getName().getValue())) {
// Don't print external at-rule
return false;
}
return super.enterUnknownAtRule(node);
}
@Override
protected void appendValueNode(CssValueNode node) { | // Path: src/main/java/com/google/gwt/resources/gss/ast/CssDotPathNode.java
// public class CssDotPathNode extends CssValueNode {
//
// public static String resolveExpression(String instance, String path, String prefix, String suffix) {
// String expression = path.replace(".", "().") + "()";
//
// if (!Strings.isNullOrEmpty(instance)) {
// expression = instance + "." + expression;
// }
//
// if (!Strings.isNullOrEmpty(prefix)) {
// expression = "\"" + Generator.escape(prefix) + "\" + " + expression;
// }
//
// if (!Strings.isNullOrEmpty(suffix)) {
// expression += " + \"" + Generator.escape(suffix) + "\"";
// }
//
// return expression;
// }
//
// private String suffix;
// private String prefix;
// private String path;
// private String instance;
//
// public CssDotPathNode(String dotPath, String prefix, String suffix, SourceCodeLocation sourceCodeLocation) {
// this(null, dotPath, prefix, suffix, sourceCodeLocation);
// }
//
// public CssDotPathNode(String instance, String dotPath, String prefix, String suffix,
// SourceCodeLocation sourceCodeLocation) {
// super(resolveExpression(instance, dotPath, prefix, suffix), sourceCodeLocation);
//
// this.prefix = prefix;
// this.suffix = suffix;
// this.path = dotPath;
// this.instance = instance;
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssDotPathNode(instance, path, prefix, suffix, getSourceCodeLocation());
// }
//
// public String getPath() {
// return path;
// }
//
// public String getSuffix() {
// return suffix;
// }
//
// public String getPrefix() {
// return prefix;
// }
//
// public String getInstance() {
// return instance;
// }
//
// public List<String> getPathElements() {
// return Arrays.asList(path.split("\\."));
// }
// }
//
// Path: src/main/java/com/google/gwt/resources/gss/ast/CssJavaExpressionNode.java
// public class CssJavaExpressionNode extends CssValueNode {
//
// public CssJavaExpressionNode(String expression) {
// this(expression, null);
// }
//
// public CssJavaExpressionNode(String expression, SourceCodeLocation sourceCodeLocation) {
// super(expression, sourceCodeLocation);
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssJavaExpressionNode(getValue());
// }
//
// @Override
// public String toString() {
// return "Java expression : " + getValue();
// }
// }
//
// Path: src/main/java/com/google/gwt/resources/gss/ast/CssRuntimeConditionalRuleNode.java
// public class CssRuntimeConditionalRuleNode extends CssConditionalRuleNode {
//
// public CssRuntimeConditionalRuleNode(CssConditionalRuleNode node,
// @Nullable CssJavaExpressionNode condition) {
// super(node.getType(), node.getName().deepCopy(), null,
// node.getBlock() != null ? node.getBlock().deepCopy() : null);
// setSourceCodeLocation(node.getSourceCodeLocation());
//
// if (condition != null) {
// setRuntimeCondition(condition);
// }
// }
//
// /**
// * Copy constructor.
// *
// * @param node
// */
// public CssRuntimeConditionalRuleNode(CssRuntimeConditionalRuleNode node) {
// this(node, node.getRuntimeCondition());
// }
//
// /**
// * Can only be called after the node is completely built (meaning it has
// * the condition set).
// */
// public CssJavaExpressionNode getRuntimeCondition() {
// if (getType() == Type.ELSE) {
// Preconditions.checkState(getParametersCount() == 0);
// return null;
// }
//
// Preconditions.checkState(getParametersCount() == 1);
// return (CssJavaExpressionNode) this.getParameters().get(0);
// }
//
// void setRuntimeCondition(CssJavaExpressionNode condition) {
// Preconditions.checkState(getType() != Type.ELSE);
// Preconditions.checkState(getParametersCount() <= 1);
// this.setParameters(ImmutableList.<CssValueNode>of(condition));
// }
//
// @Override
// public CssConditionalRuleNode deepCopy() {
// return new CssRuntimeConditionalRuleNode(this);
// }
// }
// Path: src/main/java/com/google/gwt/resources/gss/CssPrinter.java
import java.util.Stack;
import com.google.common.css.compiler.ast.CssAtRuleNode.Type;
import com.google.common.css.compiler.ast.CssConditionalBlockNode;
import com.google.common.css.compiler.ast.CssConditionalRuleNode;
import com.google.common.css.compiler.ast.CssNode;
import com.google.common.css.compiler.ast.CssRootNode;
import com.google.common.css.compiler.ast.CssTree;
import com.google.common.css.compiler.ast.CssUnknownAtRuleNode;
import com.google.common.css.compiler.ast.CssValueNode;
import com.google.common.css.compiler.passes.CompactPrinter;
import com.google.gwt.core.ext.Generator;
import com.google.gwt.resources.gss.ast.CssDotPathNode;
import com.google.gwt.resources.gss.ast.CssJavaExpressionNode;
import com.google.gwt.resources.gss.ast.CssRuntimeConditionalRuleNode;
masterStringBuilder.append(conditionalRuleNode.getRuntimeCondition().getValue());
masterStringBuilder.append(") ? (");
// reset concatenation counter
concatenationNumber = 0;
}
return true;
}
@Override
public void leaveConditionalRule(CssConditionalRuleNode node) {
masterStringBuilder.append(flushInternalStringBuilder()).append(RIGHT_BRACKET);
if (node.getType() != Type.ELSE) {
masterStringBuilder.append(" : ");
}
}
@Override
public boolean enterUnknownAtRule(CssUnknownAtRuleNode node) {
if (EXTERNAL.equals(node.getName().getValue())) {
// Don't print external at-rule
return false;
}
return super.enterUnknownAtRule(node);
}
@Override
protected void appendValueNode(CssValueNode node) { | if (node instanceof CssJavaExpressionNode || node instanceof CssDotPathNode) { |
jDramaix/gss.gwt | src/main/java/com/google/gwt/resources/gss/CssPrinter.java | // Path: src/main/java/com/google/gwt/resources/gss/ast/CssDotPathNode.java
// public class CssDotPathNode extends CssValueNode {
//
// public static String resolveExpression(String instance, String path, String prefix, String suffix) {
// String expression = path.replace(".", "().") + "()";
//
// if (!Strings.isNullOrEmpty(instance)) {
// expression = instance + "." + expression;
// }
//
// if (!Strings.isNullOrEmpty(prefix)) {
// expression = "\"" + Generator.escape(prefix) + "\" + " + expression;
// }
//
// if (!Strings.isNullOrEmpty(suffix)) {
// expression += " + \"" + Generator.escape(suffix) + "\"";
// }
//
// return expression;
// }
//
// private String suffix;
// private String prefix;
// private String path;
// private String instance;
//
// public CssDotPathNode(String dotPath, String prefix, String suffix, SourceCodeLocation sourceCodeLocation) {
// this(null, dotPath, prefix, suffix, sourceCodeLocation);
// }
//
// public CssDotPathNode(String instance, String dotPath, String prefix, String suffix,
// SourceCodeLocation sourceCodeLocation) {
// super(resolveExpression(instance, dotPath, prefix, suffix), sourceCodeLocation);
//
// this.prefix = prefix;
// this.suffix = suffix;
// this.path = dotPath;
// this.instance = instance;
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssDotPathNode(instance, path, prefix, suffix, getSourceCodeLocation());
// }
//
// public String getPath() {
// return path;
// }
//
// public String getSuffix() {
// return suffix;
// }
//
// public String getPrefix() {
// return prefix;
// }
//
// public String getInstance() {
// return instance;
// }
//
// public List<String> getPathElements() {
// return Arrays.asList(path.split("\\."));
// }
// }
//
// Path: src/main/java/com/google/gwt/resources/gss/ast/CssJavaExpressionNode.java
// public class CssJavaExpressionNode extends CssValueNode {
//
// public CssJavaExpressionNode(String expression) {
// this(expression, null);
// }
//
// public CssJavaExpressionNode(String expression, SourceCodeLocation sourceCodeLocation) {
// super(expression, sourceCodeLocation);
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssJavaExpressionNode(getValue());
// }
//
// @Override
// public String toString() {
// return "Java expression : " + getValue();
// }
// }
//
// Path: src/main/java/com/google/gwt/resources/gss/ast/CssRuntimeConditionalRuleNode.java
// public class CssRuntimeConditionalRuleNode extends CssConditionalRuleNode {
//
// public CssRuntimeConditionalRuleNode(CssConditionalRuleNode node,
// @Nullable CssJavaExpressionNode condition) {
// super(node.getType(), node.getName().deepCopy(), null,
// node.getBlock() != null ? node.getBlock().deepCopy() : null);
// setSourceCodeLocation(node.getSourceCodeLocation());
//
// if (condition != null) {
// setRuntimeCondition(condition);
// }
// }
//
// /**
// * Copy constructor.
// *
// * @param node
// */
// public CssRuntimeConditionalRuleNode(CssRuntimeConditionalRuleNode node) {
// this(node, node.getRuntimeCondition());
// }
//
// /**
// * Can only be called after the node is completely built (meaning it has
// * the condition set).
// */
// public CssJavaExpressionNode getRuntimeCondition() {
// if (getType() == Type.ELSE) {
// Preconditions.checkState(getParametersCount() == 0);
// return null;
// }
//
// Preconditions.checkState(getParametersCount() == 1);
// return (CssJavaExpressionNode) this.getParameters().get(0);
// }
//
// void setRuntimeCondition(CssJavaExpressionNode condition) {
// Preconditions.checkState(getType() != Type.ELSE);
// Preconditions.checkState(getParametersCount() <= 1);
// this.setParameters(ImmutableList.<CssValueNode>of(condition));
// }
//
// @Override
// public CssConditionalRuleNode deepCopy() {
// return new CssRuntimeConditionalRuleNode(this);
// }
// }
| import java.util.Stack;
import com.google.common.css.compiler.ast.CssAtRuleNode.Type;
import com.google.common.css.compiler.ast.CssConditionalBlockNode;
import com.google.common.css.compiler.ast.CssConditionalRuleNode;
import com.google.common.css.compiler.ast.CssNode;
import com.google.common.css.compiler.ast.CssRootNode;
import com.google.common.css.compiler.ast.CssTree;
import com.google.common.css.compiler.ast.CssUnknownAtRuleNode;
import com.google.common.css.compiler.ast.CssValueNode;
import com.google.common.css.compiler.passes.CompactPrinter;
import com.google.gwt.core.ext.Generator;
import com.google.gwt.resources.gss.ast.CssDotPathNode;
import com.google.gwt.resources.gss.ast.CssJavaExpressionNode;
import com.google.gwt.resources.gss.ast.CssRuntimeConditionalRuleNode; | masterStringBuilder.append(conditionalRuleNode.getRuntimeCondition().getValue());
masterStringBuilder.append(") ? (");
// reset concatenation counter
concatenationNumber = 0;
}
return true;
}
@Override
public void leaveConditionalRule(CssConditionalRuleNode node) {
masterStringBuilder.append(flushInternalStringBuilder()).append(RIGHT_BRACKET);
if (node.getType() != Type.ELSE) {
masterStringBuilder.append(" : ");
}
}
@Override
public boolean enterUnknownAtRule(CssUnknownAtRuleNode node) {
if (EXTERNAL.equals(node.getName().getValue())) {
// Don't print external at-rule
return false;
}
return super.enterUnknownAtRule(node);
}
@Override
protected void appendValueNode(CssValueNode node) { | // Path: src/main/java/com/google/gwt/resources/gss/ast/CssDotPathNode.java
// public class CssDotPathNode extends CssValueNode {
//
// public static String resolveExpression(String instance, String path, String prefix, String suffix) {
// String expression = path.replace(".", "().") + "()";
//
// if (!Strings.isNullOrEmpty(instance)) {
// expression = instance + "." + expression;
// }
//
// if (!Strings.isNullOrEmpty(prefix)) {
// expression = "\"" + Generator.escape(prefix) + "\" + " + expression;
// }
//
// if (!Strings.isNullOrEmpty(suffix)) {
// expression += " + \"" + Generator.escape(suffix) + "\"";
// }
//
// return expression;
// }
//
// private String suffix;
// private String prefix;
// private String path;
// private String instance;
//
// public CssDotPathNode(String dotPath, String prefix, String suffix, SourceCodeLocation sourceCodeLocation) {
// this(null, dotPath, prefix, suffix, sourceCodeLocation);
// }
//
// public CssDotPathNode(String instance, String dotPath, String prefix, String suffix,
// SourceCodeLocation sourceCodeLocation) {
// super(resolveExpression(instance, dotPath, prefix, suffix), sourceCodeLocation);
//
// this.prefix = prefix;
// this.suffix = suffix;
// this.path = dotPath;
// this.instance = instance;
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssDotPathNode(instance, path, prefix, suffix, getSourceCodeLocation());
// }
//
// public String getPath() {
// return path;
// }
//
// public String getSuffix() {
// return suffix;
// }
//
// public String getPrefix() {
// return prefix;
// }
//
// public String getInstance() {
// return instance;
// }
//
// public List<String> getPathElements() {
// return Arrays.asList(path.split("\\."));
// }
// }
//
// Path: src/main/java/com/google/gwt/resources/gss/ast/CssJavaExpressionNode.java
// public class CssJavaExpressionNode extends CssValueNode {
//
// public CssJavaExpressionNode(String expression) {
// this(expression, null);
// }
//
// public CssJavaExpressionNode(String expression, SourceCodeLocation sourceCodeLocation) {
// super(expression, sourceCodeLocation);
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssJavaExpressionNode(getValue());
// }
//
// @Override
// public String toString() {
// return "Java expression : " + getValue();
// }
// }
//
// Path: src/main/java/com/google/gwt/resources/gss/ast/CssRuntimeConditionalRuleNode.java
// public class CssRuntimeConditionalRuleNode extends CssConditionalRuleNode {
//
// public CssRuntimeConditionalRuleNode(CssConditionalRuleNode node,
// @Nullable CssJavaExpressionNode condition) {
// super(node.getType(), node.getName().deepCopy(), null,
// node.getBlock() != null ? node.getBlock().deepCopy() : null);
// setSourceCodeLocation(node.getSourceCodeLocation());
//
// if (condition != null) {
// setRuntimeCondition(condition);
// }
// }
//
// /**
// * Copy constructor.
// *
// * @param node
// */
// public CssRuntimeConditionalRuleNode(CssRuntimeConditionalRuleNode node) {
// this(node, node.getRuntimeCondition());
// }
//
// /**
// * Can only be called after the node is completely built (meaning it has
// * the condition set).
// */
// public CssJavaExpressionNode getRuntimeCondition() {
// if (getType() == Type.ELSE) {
// Preconditions.checkState(getParametersCount() == 0);
// return null;
// }
//
// Preconditions.checkState(getParametersCount() == 1);
// return (CssJavaExpressionNode) this.getParameters().get(0);
// }
//
// void setRuntimeCondition(CssJavaExpressionNode condition) {
// Preconditions.checkState(getType() != Type.ELSE);
// Preconditions.checkState(getParametersCount() <= 1);
// this.setParameters(ImmutableList.<CssValueNode>of(condition));
// }
//
// @Override
// public CssConditionalRuleNode deepCopy() {
// return new CssRuntimeConditionalRuleNode(this);
// }
// }
// Path: src/main/java/com/google/gwt/resources/gss/CssPrinter.java
import java.util.Stack;
import com.google.common.css.compiler.ast.CssAtRuleNode.Type;
import com.google.common.css.compiler.ast.CssConditionalBlockNode;
import com.google.common.css.compiler.ast.CssConditionalRuleNode;
import com.google.common.css.compiler.ast.CssNode;
import com.google.common.css.compiler.ast.CssRootNode;
import com.google.common.css.compiler.ast.CssTree;
import com.google.common.css.compiler.ast.CssUnknownAtRuleNode;
import com.google.common.css.compiler.ast.CssValueNode;
import com.google.common.css.compiler.passes.CompactPrinter;
import com.google.gwt.core.ext.Generator;
import com.google.gwt.resources.gss.ast.CssDotPathNode;
import com.google.gwt.resources.gss.ast.CssJavaExpressionNode;
import com.google.gwt.resources.gss.ast.CssRuntimeConditionalRuleNode;
masterStringBuilder.append(conditionalRuleNode.getRuntimeCondition().getValue());
masterStringBuilder.append(") ? (");
// reset concatenation counter
concatenationNumber = 0;
}
return true;
}
@Override
public void leaveConditionalRule(CssConditionalRuleNode node) {
masterStringBuilder.append(flushInternalStringBuilder()).append(RIGHT_BRACKET);
if (node.getType() != Type.ELSE) {
masterStringBuilder.append(" : ");
}
}
@Override
public boolean enterUnknownAtRule(CssUnknownAtRuleNode node) {
if (EXTERNAL.equals(node.getName().getValue())) {
// Don't print external at-rule
return false;
}
return super.enterUnknownAtRule(node);
}
@Override
protected void appendValueNode(CssValueNode node) { | if (node instanceof CssJavaExpressionNode || node instanceof CssDotPathNode) { |
jDramaix/gss.gwt | src/main/java/com/google/gwt/resources/gss/ImageSpriteCreator.java | // Path: src/main/java/com/google/gwt/resources/gss/ast/CssDotPathNode.java
// public class CssDotPathNode extends CssValueNode {
//
// public static String resolveExpression(String instance, String path, String prefix, String suffix) {
// String expression = path.replace(".", "().") + "()";
//
// if (!Strings.isNullOrEmpty(instance)) {
// expression = instance + "." + expression;
// }
//
// if (!Strings.isNullOrEmpty(prefix)) {
// expression = "\"" + Generator.escape(prefix) + "\" + " + expression;
// }
//
// if (!Strings.isNullOrEmpty(suffix)) {
// expression += " + \"" + Generator.escape(suffix) + "\"";
// }
//
// return expression;
// }
//
// private String suffix;
// private String prefix;
// private String path;
// private String instance;
//
// public CssDotPathNode(String dotPath, String prefix, String suffix, SourceCodeLocation sourceCodeLocation) {
// this(null, dotPath, prefix, suffix, sourceCodeLocation);
// }
//
// public CssDotPathNode(String instance, String dotPath, String prefix, String suffix,
// SourceCodeLocation sourceCodeLocation) {
// super(resolveExpression(instance, dotPath, prefix, suffix), sourceCodeLocation);
//
// this.prefix = prefix;
// this.suffix = suffix;
// this.path = dotPath;
// this.instance = instance;
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssDotPathNode(instance, path, prefix, suffix, getSourceCodeLocation());
// }
//
// public String getPath() {
// return path;
// }
//
// public String getSuffix() {
// return suffix;
// }
//
// public String getPrefix() {
// return prefix;
// }
//
// public String getInstance() {
// return instance;
// }
//
// public List<String> getPathElements() {
// return Arrays.asList(path.split("\\."));
// }
// }
| import static com.google.common.css.compiler.passes.PassUtil.ALTERNATE;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import com.google.common.collect.Lists;
import com.google.common.css.SourceCodeLocation;
import com.google.common.css.compiler.ast.CssCommentNode;
import com.google.common.css.compiler.ast.CssCompilerPass;
import com.google.common.css.compiler.ast.CssDeclarationNode;
import com.google.common.css.compiler.ast.CssFunctionArgumentsNode;
import com.google.common.css.compiler.ast.CssFunctionNode;
import com.google.common.css.compiler.ast.CssFunctionNode.Function;
import com.google.common.css.compiler.ast.CssLiteralNode;
import com.google.common.css.compiler.ast.CssPropertyNode;
import com.google.common.css.compiler.ast.CssPropertyValueNode;
import com.google.common.css.compiler.ast.CssValueNode;
import com.google.common.css.compiler.ast.DefaultTreeVisitor;
import com.google.common.css.compiler.ast.ErrorManager;
import com.google.common.css.compiler.ast.GssError;
import com.google.common.css.compiler.ast.MutatingVisitController;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.JMethod;
import com.google.gwt.core.ext.typeinfo.NotFoundException;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.resources.client.ImageResource.ImageOptions;
import com.google.gwt.resources.client.ImageResource.RepeatStyle;
import com.google.gwt.resources.ext.ResourceContext;
import com.google.gwt.resources.ext.ResourceGeneratorUtil;
import com.google.gwt.resources.gss.ast.CssDotPathNode;
import java.util.List; | this.errorManager = errorManager;
this.context = context;
this.imageResourceType = context.getGeneratorContext().getTypeOracle().findType(
ImageResource.class.getName());
this.resourceThisPrefix = context.getImplementationSimpleSourceName() + ".this";
}
@Override
public boolean enterDeclaration(CssDeclarationNode declaration) {
String propertyName = declaration.getPropertyName().getPropertyName();
if (SPRITE_PROPERTY_NAME.equals(propertyName)) {
createSprite(declaration);
return true;
}
return super.enterDeclaration(declaration);
}
@Override
public void runPass() {
assert imageResourceType != null;
visitController.startVisit(this);
}
private CssDeclarationNode buildBackgroundDeclaration(String imageResource, String repeatText,
SourceCodeLocation location) {
// build the url function
CssFunctionNode urlFunction = new CssFunctionNode(Function.byName("url"), location); | // Path: src/main/java/com/google/gwt/resources/gss/ast/CssDotPathNode.java
// public class CssDotPathNode extends CssValueNode {
//
// public static String resolveExpression(String instance, String path, String prefix, String suffix) {
// String expression = path.replace(".", "().") + "()";
//
// if (!Strings.isNullOrEmpty(instance)) {
// expression = instance + "." + expression;
// }
//
// if (!Strings.isNullOrEmpty(prefix)) {
// expression = "\"" + Generator.escape(prefix) + "\" + " + expression;
// }
//
// if (!Strings.isNullOrEmpty(suffix)) {
// expression += " + \"" + Generator.escape(suffix) + "\"";
// }
//
// return expression;
// }
//
// private String suffix;
// private String prefix;
// private String path;
// private String instance;
//
// public CssDotPathNode(String dotPath, String prefix, String suffix, SourceCodeLocation sourceCodeLocation) {
// this(null, dotPath, prefix, suffix, sourceCodeLocation);
// }
//
// public CssDotPathNode(String instance, String dotPath, String prefix, String suffix,
// SourceCodeLocation sourceCodeLocation) {
// super(resolveExpression(instance, dotPath, prefix, suffix), sourceCodeLocation);
//
// this.prefix = prefix;
// this.suffix = suffix;
// this.path = dotPath;
// this.instance = instance;
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssDotPathNode(instance, path, prefix, suffix, getSourceCodeLocation());
// }
//
// public String getPath() {
// return path;
// }
//
// public String getSuffix() {
// return suffix;
// }
//
// public String getPrefix() {
// return prefix;
// }
//
// public String getInstance() {
// return instance;
// }
//
// public List<String> getPathElements() {
// return Arrays.asList(path.split("\\."));
// }
// }
// Path: src/main/java/com/google/gwt/resources/gss/ImageSpriteCreator.java
import static com.google.common.css.compiler.passes.PassUtil.ALTERNATE;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import com.google.common.collect.Lists;
import com.google.common.css.SourceCodeLocation;
import com.google.common.css.compiler.ast.CssCommentNode;
import com.google.common.css.compiler.ast.CssCompilerPass;
import com.google.common.css.compiler.ast.CssDeclarationNode;
import com.google.common.css.compiler.ast.CssFunctionArgumentsNode;
import com.google.common.css.compiler.ast.CssFunctionNode;
import com.google.common.css.compiler.ast.CssFunctionNode.Function;
import com.google.common.css.compiler.ast.CssLiteralNode;
import com.google.common.css.compiler.ast.CssPropertyNode;
import com.google.common.css.compiler.ast.CssPropertyValueNode;
import com.google.common.css.compiler.ast.CssValueNode;
import com.google.common.css.compiler.ast.DefaultTreeVisitor;
import com.google.common.css.compiler.ast.ErrorManager;
import com.google.common.css.compiler.ast.GssError;
import com.google.common.css.compiler.ast.MutatingVisitController;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.JMethod;
import com.google.gwt.core.ext.typeinfo.NotFoundException;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.resources.client.ImageResource.ImageOptions;
import com.google.gwt.resources.client.ImageResource.RepeatStyle;
import com.google.gwt.resources.ext.ResourceContext;
import com.google.gwt.resources.ext.ResourceGeneratorUtil;
import com.google.gwt.resources.gss.ast.CssDotPathNode;
import java.util.List;
this.errorManager = errorManager;
this.context = context;
this.imageResourceType = context.getGeneratorContext().getTypeOracle().findType(
ImageResource.class.getName());
this.resourceThisPrefix = context.getImplementationSimpleSourceName() + ".this";
}
@Override
public boolean enterDeclaration(CssDeclarationNode declaration) {
String propertyName = declaration.getPropertyName().getPropertyName();
if (SPRITE_PROPERTY_NAME.equals(propertyName)) {
createSprite(declaration);
return true;
}
return super.enterDeclaration(declaration);
}
@Override
public void runPass() {
assert imageResourceType != null;
visitController.startVisit(this);
}
private CssDeclarationNode buildBackgroundDeclaration(String imageResource, String repeatText,
SourceCodeLocation location) {
// build the url function
CssFunctionNode urlFunction = new CssFunctionNode(Function.byName("url"), location); | CssDotPathNode imageUrl = new CssDotPathNode(resourceThisPrefix, imageResource + ".getSafeUri" + |
jDramaix/gss.gwt | src/main/java/com/google/gwt/resources/gss/CreateRuntimeConditionalNodes.java | // Path: src/main/java/com/google/gwt/resources/gss/ast/CssJavaExpressionNode.java
// public class CssJavaExpressionNode extends CssValueNode {
//
// public CssJavaExpressionNode(String expression) {
// this(expression, null);
// }
//
// public CssJavaExpressionNode(String expression, SourceCodeLocation sourceCodeLocation) {
// super(expression, sourceCodeLocation);
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssJavaExpressionNode(getValue());
// }
//
// @Override
// public String toString() {
// return "Java expression : " + getValue();
// }
// }
//
// Path: src/main/java/com/google/gwt/resources/gss/ast/CssRuntimeConditionalRuleNode.java
// public class CssRuntimeConditionalRuleNode extends CssConditionalRuleNode {
//
// public CssRuntimeConditionalRuleNode(CssConditionalRuleNode node,
// @Nullable CssJavaExpressionNode condition) {
// super(node.getType(), node.getName().deepCopy(), null,
// node.getBlock() != null ? node.getBlock().deepCopy() : null);
// setSourceCodeLocation(node.getSourceCodeLocation());
//
// if (condition != null) {
// setRuntimeCondition(condition);
// }
// }
//
// /**
// * Copy constructor.
// *
// * @param node
// */
// public CssRuntimeConditionalRuleNode(CssRuntimeConditionalRuleNode node) {
// this(node, node.getRuntimeCondition());
// }
//
// /**
// * Can only be called after the node is completely built (meaning it has
// * the condition set).
// */
// public CssJavaExpressionNode getRuntimeCondition() {
// if (getType() == Type.ELSE) {
// Preconditions.checkState(getParametersCount() == 0);
// return null;
// }
//
// Preconditions.checkState(getParametersCount() == 1);
// return (CssJavaExpressionNode) this.getParameters().get(0);
// }
//
// void setRuntimeCondition(CssJavaExpressionNode condition) {
// Preconditions.checkState(getType() != Type.ELSE);
// Preconditions.checkState(getParametersCount() <= 1);
// this.setParameters(ImmutableList.<CssValueNode>of(condition));
// }
//
// @Override
// public CssConditionalRuleNode deepCopy() {
// return new CssRuntimeConditionalRuleNode(this);
// }
// }
| import java.util.regex.Pattern;
import com.google.common.collect.Lists;
import com.google.common.css.compiler.ast.CssAtRuleNode.Type;
import com.google.common.css.compiler.ast.CssBooleanExpressionNode;
import com.google.common.css.compiler.ast.CssCompilerPass;
import com.google.common.css.compiler.ast.CssConditionalBlockNode;
import com.google.common.css.compiler.ast.CssConditionalRuleNode;
import com.google.common.css.compiler.ast.CssValueNode;
import com.google.common.css.compiler.ast.DefaultTreeVisitor;
import com.google.common.css.compiler.ast.MutatingVisitController;
import com.google.gwt.resources.gss.ast.CssJavaExpressionNode;
import com.google.gwt.resources.gss.ast.CssRuntimeConditionalRuleNode;
import java.util.List;
import java.util.regex.Matcher; | /*
* Copyright 2014 Julien Dramaix.
*
* 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.gwt.resources.gss;
public class CreateRuntimeConditionalNodes extends DefaultTreeVisitor implements CssCompilerPass {
private static final Pattern EVAL_FUNCTION = Pattern.compile("^eval\\([\"']([^\"']*)[\"']\\)$");
private final MutatingVisitController visitController;
public CreateRuntimeConditionalNodes(MutatingVisitController visitController) {
this.visitController = visitController;
}
@Override
public boolean enterConditionalBlock(CssConditionalBlockNode block) {
// we have to visit all the CssConditionalRuleNode when we visit the CssConditionalBlockNode
// parent node because we are going to replace CssConditionalRuleNode by another node and
// unfortunately the visitController doesn't support to replace a CssConditionalRuleNode and
// we have to do it manually. That implies that the new nodes won't be visited by the
// visitor if we do that during the visit of the CssConditionalRuleNodes.
// make a copy in order to avoid ConcurrentModificationException
List<CssConditionalRuleNode> children = Lists.newArrayList(block.getChildren());
for (CssConditionalRuleNode ruleNode : children) {
manuallyVisitConditionalRule(ruleNode, block);
}
return true;
}
private void manuallyVisitConditionalRule(CssConditionalRuleNode node,
CssConditionalBlockNode parent) {
if (node.getType() != Type.ELSE) {
CssBooleanExpressionNode nodeCondition = node.getCondition();
String condition = extractRuntimeCondition(nodeCondition);
if (condition != null) { | // Path: src/main/java/com/google/gwt/resources/gss/ast/CssJavaExpressionNode.java
// public class CssJavaExpressionNode extends CssValueNode {
//
// public CssJavaExpressionNode(String expression) {
// this(expression, null);
// }
//
// public CssJavaExpressionNode(String expression, SourceCodeLocation sourceCodeLocation) {
// super(expression, sourceCodeLocation);
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssJavaExpressionNode(getValue());
// }
//
// @Override
// public String toString() {
// return "Java expression : " + getValue();
// }
// }
//
// Path: src/main/java/com/google/gwt/resources/gss/ast/CssRuntimeConditionalRuleNode.java
// public class CssRuntimeConditionalRuleNode extends CssConditionalRuleNode {
//
// public CssRuntimeConditionalRuleNode(CssConditionalRuleNode node,
// @Nullable CssJavaExpressionNode condition) {
// super(node.getType(), node.getName().deepCopy(), null,
// node.getBlock() != null ? node.getBlock().deepCopy() : null);
// setSourceCodeLocation(node.getSourceCodeLocation());
//
// if (condition != null) {
// setRuntimeCondition(condition);
// }
// }
//
// /**
// * Copy constructor.
// *
// * @param node
// */
// public CssRuntimeConditionalRuleNode(CssRuntimeConditionalRuleNode node) {
// this(node, node.getRuntimeCondition());
// }
//
// /**
// * Can only be called after the node is completely built (meaning it has
// * the condition set).
// */
// public CssJavaExpressionNode getRuntimeCondition() {
// if (getType() == Type.ELSE) {
// Preconditions.checkState(getParametersCount() == 0);
// return null;
// }
//
// Preconditions.checkState(getParametersCount() == 1);
// return (CssJavaExpressionNode) this.getParameters().get(0);
// }
//
// void setRuntimeCondition(CssJavaExpressionNode condition) {
// Preconditions.checkState(getType() != Type.ELSE);
// Preconditions.checkState(getParametersCount() <= 1);
// this.setParameters(ImmutableList.<CssValueNode>of(condition));
// }
//
// @Override
// public CssConditionalRuleNode deepCopy() {
// return new CssRuntimeConditionalRuleNode(this);
// }
// }
// Path: src/main/java/com/google/gwt/resources/gss/CreateRuntimeConditionalNodes.java
import java.util.regex.Pattern;
import com.google.common.collect.Lists;
import com.google.common.css.compiler.ast.CssAtRuleNode.Type;
import com.google.common.css.compiler.ast.CssBooleanExpressionNode;
import com.google.common.css.compiler.ast.CssCompilerPass;
import com.google.common.css.compiler.ast.CssConditionalBlockNode;
import com.google.common.css.compiler.ast.CssConditionalRuleNode;
import com.google.common.css.compiler.ast.CssValueNode;
import com.google.common.css.compiler.ast.DefaultTreeVisitor;
import com.google.common.css.compiler.ast.MutatingVisitController;
import com.google.gwt.resources.gss.ast.CssJavaExpressionNode;
import com.google.gwt.resources.gss.ast.CssRuntimeConditionalRuleNode;
import java.util.List;
import java.util.regex.Matcher;
/*
* Copyright 2014 Julien Dramaix.
*
* 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.gwt.resources.gss;
public class CreateRuntimeConditionalNodes extends DefaultTreeVisitor implements CssCompilerPass {
private static final Pattern EVAL_FUNCTION = Pattern.compile("^eval\\([\"']([^\"']*)[\"']\\)$");
private final MutatingVisitController visitController;
public CreateRuntimeConditionalNodes(MutatingVisitController visitController) {
this.visitController = visitController;
}
@Override
public boolean enterConditionalBlock(CssConditionalBlockNode block) {
// we have to visit all the CssConditionalRuleNode when we visit the CssConditionalBlockNode
// parent node because we are going to replace CssConditionalRuleNode by another node and
// unfortunately the visitController doesn't support to replace a CssConditionalRuleNode and
// we have to do it manually. That implies that the new nodes won't be visited by the
// visitor if we do that during the visit of the CssConditionalRuleNodes.
// make a copy in order to avoid ConcurrentModificationException
List<CssConditionalRuleNode> children = Lists.newArrayList(block.getChildren());
for (CssConditionalRuleNode ruleNode : children) {
manuallyVisitConditionalRule(ruleNode, block);
}
return true;
}
private void manuallyVisitConditionalRule(CssConditionalRuleNode node,
CssConditionalBlockNode parent) {
if (node.getType() != Type.ELSE) {
CssBooleanExpressionNode nodeCondition = node.getCondition();
String condition = extractRuntimeCondition(nodeCondition);
if (condition != null) { | CssJavaExpressionNode newNode = new CssJavaExpressionNode(condition, |
jDramaix/gss.gwt | src/main/java/com/google/gwt/resources/gss/CreateRuntimeConditionalNodes.java | // Path: src/main/java/com/google/gwt/resources/gss/ast/CssJavaExpressionNode.java
// public class CssJavaExpressionNode extends CssValueNode {
//
// public CssJavaExpressionNode(String expression) {
// this(expression, null);
// }
//
// public CssJavaExpressionNode(String expression, SourceCodeLocation sourceCodeLocation) {
// super(expression, sourceCodeLocation);
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssJavaExpressionNode(getValue());
// }
//
// @Override
// public String toString() {
// return "Java expression : " + getValue();
// }
// }
//
// Path: src/main/java/com/google/gwt/resources/gss/ast/CssRuntimeConditionalRuleNode.java
// public class CssRuntimeConditionalRuleNode extends CssConditionalRuleNode {
//
// public CssRuntimeConditionalRuleNode(CssConditionalRuleNode node,
// @Nullable CssJavaExpressionNode condition) {
// super(node.getType(), node.getName().deepCopy(), null,
// node.getBlock() != null ? node.getBlock().deepCopy() : null);
// setSourceCodeLocation(node.getSourceCodeLocation());
//
// if (condition != null) {
// setRuntimeCondition(condition);
// }
// }
//
// /**
// * Copy constructor.
// *
// * @param node
// */
// public CssRuntimeConditionalRuleNode(CssRuntimeConditionalRuleNode node) {
// this(node, node.getRuntimeCondition());
// }
//
// /**
// * Can only be called after the node is completely built (meaning it has
// * the condition set).
// */
// public CssJavaExpressionNode getRuntimeCondition() {
// if (getType() == Type.ELSE) {
// Preconditions.checkState(getParametersCount() == 0);
// return null;
// }
//
// Preconditions.checkState(getParametersCount() == 1);
// return (CssJavaExpressionNode) this.getParameters().get(0);
// }
//
// void setRuntimeCondition(CssJavaExpressionNode condition) {
// Preconditions.checkState(getType() != Type.ELSE);
// Preconditions.checkState(getParametersCount() <= 1);
// this.setParameters(ImmutableList.<CssValueNode>of(condition));
// }
//
// @Override
// public CssConditionalRuleNode deepCopy() {
// return new CssRuntimeConditionalRuleNode(this);
// }
// }
| import java.util.regex.Pattern;
import com.google.common.collect.Lists;
import com.google.common.css.compiler.ast.CssAtRuleNode.Type;
import com.google.common.css.compiler.ast.CssBooleanExpressionNode;
import com.google.common.css.compiler.ast.CssCompilerPass;
import com.google.common.css.compiler.ast.CssConditionalBlockNode;
import com.google.common.css.compiler.ast.CssConditionalRuleNode;
import com.google.common.css.compiler.ast.CssValueNode;
import com.google.common.css.compiler.ast.DefaultTreeVisitor;
import com.google.common.css.compiler.ast.MutatingVisitController;
import com.google.gwt.resources.gss.ast.CssJavaExpressionNode;
import com.google.gwt.resources.gss.ast.CssRuntimeConditionalRuleNode;
import java.util.List;
import java.util.regex.Matcher; | /*
* Copyright 2014 Julien Dramaix.
*
* 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.gwt.resources.gss;
public class CreateRuntimeConditionalNodes extends DefaultTreeVisitor implements CssCompilerPass {
private static final Pattern EVAL_FUNCTION = Pattern.compile("^eval\\([\"']([^\"']*)[\"']\\)$");
private final MutatingVisitController visitController;
public CreateRuntimeConditionalNodes(MutatingVisitController visitController) {
this.visitController = visitController;
}
@Override
public boolean enterConditionalBlock(CssConditionalBlockNode block) {
// we have to visit all the CssConditionalRuleNode when we visit the CssConditionalBlockNode
// parent node because we are going to replace CssConditionalRuleNode by another node and
// unfortunately the visitController doesn't support to replace a CssConditionalRuleNode and
// we have to do it manually. That implies that the new nodes won't be visited by the
// visitor if we do that during the visit of the CssConditionalRuleNodes.
// make a copy in order to avoid ConcurrentModificationException
List<CssConditionalRuleNode> children = Lists.newArrayList(block.getChildren());
for (CssConditionalRuleNode ruleNode : children) {
manuallyVisitConditionalRule(ruleNode, block);
}
return true;
}
private void manuallyVisitConditionalRule(CssConditionalRuleNode node,
CssConditionalBlockNode parent) {
if (node.getType() != Type.ELSE) {
CssBooleanExpressionNode nodeCondition = node.getCondition();
String condition = extractRuntimeCondition(nodeCondition);
if (condition != null) {
CssJavaExpressionNode newNode = new CssJavaExpressionNode(condition,
nodeCondition.getSourceCodeLocation());
| // Path: src/main/java/com/google/gwt/resources/gss/ast/CssJavaExpressionNode.java
// public class CssJavaExpressionNode extends CssValueNode {
//
// public CssJavaExpressionNode(String expression) {
// this(expression, null);
// }
//
// public CssJavaExpressionNode(String expression, SourceCodeLocation sourceCodeLocation) {
// super(expression, sourceCodeLocation);
// }
//
// @Override
// public CssValueNode deepCopy() {
// return new CssJavaExpressionNode(getValue());
// }
//
// @Override
// public String toString() {
// return "Java expression : " + getValue();
// }
// }
//
// Path: src/main/java/com/google/gwt/resources/gss/ast/CssRuntimeConditionalRuleNode.java
// public class CssRuntimeConditionalRuleNode extends CssConditionalRuleNode {
//
// public CssRuntimeConditionalRuleNode(CssConditionalRuleNode node,
// @Nullable CssJavaExpressionNode condition) {
// super(node.getType(), node.getName().deepCopy(), null,
// node.getBlock() != null ? node.getBlock().deepCopy() : null);
// setSourceCodeLocation(node.getSourceCodeLocation());
//
// if (condition != null) {
// setRuntimeCondition(condition);
// }
// }
//
// /**
// * Copy constructor.
// *
// * @param node
// */
// public CssRuntimeConditionalRuleNode(CssRuntimeConditionalRuleNode node) {
// this(node, node.getRuntimeCondition());
// }
//
// /**
// * Can only be called after the node is completely built (meaning it has
// * the condition set).
// */
// public CssJavaExpressionNode getRuntimeCondition() {
// if (getType() == Type.ELSE) {
// Preconditions.checkState(getParametersCount() == 0);
// return null;
// }
//
// Preconditions.checkState(getParametersCount() == 1);
// return (CssJavaExpressionNode) this.getParameters().get(0);
// }
//
// void setRuntimeCondition(CssJavaExpressionNode condition) {
// Preconditions.checkState(getType() != Type.ELSE);
// Preconditions.checkState(getParametersCount() <= 1);
// this.setParameters(ImmutableList.<CssValueNode>of(condition));
// }
//
// @Override
// public CssConditionalRuleNode deepCopy() {
// return new CssRuntimeConditionalRuleNode(this);
// }
// }
// Path: src/main/java/com/google/gwt/resources/gss/CreateRuntimeConditionalNodes.java
import java.util.regex.Pattern;
import com.google.common.collect.Lists;
import com.google.common.css.compiler.ast.CssAtRuleNode.Type;
import com.google.common.css.compiler.ast.CssBooleanExpressionNode;
import com.google.common.css.compiler.ast.CssCompilerPass;
import com.google.common.css.compiler.ast.CssConditionalBlockNode;
import com.google.common.css.compiler.ast.CssConditionalRuleNode;
import com.google.common.css.compiler.ast.CssValueNode;
import com.google.common.css.compiler.ast.DefaultTreeVisitor;
import com.google.common.css.compiler.ast.MutatingVisitController;
import com.google.gwt.resources.gss.ast.CssJavaExpressionNode;
import com.google.gwt.resources.gss.ast.CssRuntimeConditionalRuleNode;
import java.util.List;
import java.util.regex.Matcher;
/*
* Copyright 2014 Julien Dramaix.
*
* 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.gwt.resources.gss;
public class CreateRuntimeConditionalNodes extends DefaultTreeVisitor implements CssCompilerPass {
private static final Pattern EVAL_FUNCTION = Pattern.compile("^eval\\([\"']([^\"']*)[\"']\\)$");
private final MutatingVisitController visitController;
public CreateRuntimeConditionalNodes(MutatingVisitController visitController) {
this.visitController = visitController;
}
@Override
public boolean enterConditionalBlock(CssConditionalBlockNode block) {
// we have to visit all the CssConditionalRuleNode when we visit the CssConditionalBlockNode
// parent node because we are going to replace CssConditionalRuleNode by another node and
// unfortunately the visitController doesn't support to replace a CssConditionalRuleNode and
// we have to do it manually. That implies that the new nodes won't be visited by the
// visitor if we do that during the visit of the CssConditionalRuleNodes.
// make a copy in order to avoid ConcurrentModificationException
List<CssConditionalRuleNode> children = Lists.newArrayList(block.getChildren());
for (CssConditionalRuleNode ruleNode : children) {
manuallyVisitConditionalRule(ruleNode, block);
}
return true;
}
private void manuallyVisitConditionalRule(CssConditionalRuleNode node,
CssConditionalBlockNode parent) {
if (node.getType() != Type.ELSE) {
CssBooleanExpressionNode nodeCondition = node.getCondition();
String condition = extractRuntimeCondition(nodeCondition);
if (condition != null) {
CssJavaExpressionNode newNode = new CssJavaExpressionNode(condition,
nodeCondition.getSourceCodeLocation());
| CssRuntimeConditionalRuleNode newRuleNode = new CssRuntimeConditionalRuleNode(node, |
jDramaix/gss.gwt | src/test/java/com/google/gwt/resources/client/StableShortTypeObfuscationStyleTest.java | // Path: src/test/java/com/google/gwt/resources/client/TestResources.java
// interface ClassNameAnnotation extends GssResource {
// @ClassName("renamed-class")
// String renamedClass();
//
// String nonRenamedClass();
// }
| import com.google.gwt.resources.client.TestResources.ClassNameAnnotation; | /*
* Copyright 2014 Julien Dramaix.
*
* 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.gwt.resources.client;
public class StableShortTypeObfuscationStyleTest extends RenamingClassNameTest {
@Override
public String getModuleName() {
return "com.google.gwt.resources.StableShortType";
}
public void testClassesRenaming() { | // Path: src/test/java/com/google/gwt/resources/client/TestResources.java
// interface ClassNameAnnotation extends GssResource {
// @ClassName("renamed-class")
// String renamedClass();
//
// String nonRenamedClass();
// }
// Path: src/test/java/com/google/gwt/resources/client/StableShortTypeObfuscationStyleTest.java
import com.google.gwt.resources.client.TestResources.ClassNameAnnotation;
/*
* Copyright 2014 Julien Dramaix.
*
* 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.gwt.resources.client;
public class StableShortTypeObfuscationStyleTest extends RenamingClassNameTest {
@Override
public String getModuleName() {
return "com.google.gwt.resources.StableShortType";
}
public void testClassesRenaming() { | ClassNameAnnotation classNameAnnotation = res().classNameAnnotation(); |
gillius/jagnet | jagnet-examples/src/main/java/org/gillius/jagnet/examples/chat/ChatClient.java | // Path: jagnet-core/src/main/java/org/gillius/jagnet/netty/NettyClient.java
// public class NettyClient implements Client {
// private static final Logger log = LoggerFactory.getLogger(NettyClient.class);
//
// private final ConnectionParams params;
//
// private NettyConnection connection;
// private final CompletableFuture<Connection> connFuture = new CompletableFuture<>();
// private EventLoopGroup group;
//
// public NettyClient(ConnectionParams params) {
// this.params = params.clone();
// }
//
// @Override
// public void close() {
// if (connection != null)
// connection.close();
// if (group != null)
// group.shutdownGracefully();
// connection = null;
// group = null;
// }
//
// public void start() {
// //TODO: prevent starting more than once (race conditions on close/failure)
//
// Kryo kryo = KryoBuilder.build(params.getMessageTypes());
//
// group = new NioEventLoopGroup();
// Bootstrap b = new Bootstrap();
// b.group(group)
// .channel(NioSocketChannel.class)
// .option(ChannelOption.TCP_NODELAY, true)
// .handler(new ChannelInitializer<SocketChannel>() {
// @Override
// public void initChannel(SocketChannel ch) throws Exception {
// connection = new NettyConnection(ch);
// connection.getCloseFuture().thenRun(NettyClient.this::close);
// if (params.getProtocol() == Protocol.WS)
// NettyUtils.configurePipelineForWebsocketClient(ch, params);
//
// NettyUtils.setupClientPipeline(ch, params.getProxyTag(), kryo, params, getConnectionStateListener());
// }
// });
//
// // Start the client.
// b.connect(params.getRemoteAddress(), params.getLocalAddress()).addListener(future -> {
// if (!future.isSuccess()) {
// connFuture.completeExceptionally(future.cause());
// close();
// }
// });
// }
//
// @Override
// public CompletableFuture<Connection> getConnection() {
// return connFuture;
// }
//
// private ConnectionStateListener getConnectionStateListener() {
// return new ConnectionStateListener() {
// @Override
// public void onConnected(ConnectionListenerContext ctx) {
// connFuture.complete(connection);
// }
// };
// }
// }
//
// Path: jagnet-examples/src/main/java/org/gillius/jagnet/examples/ExampleUtil.java
// public static String getUri(String args[]) {
// if (args.length > 1) {
// return args[0];
// } else {
// String uri = "tcp://localhost:54555";
// //alternative uri = "proxy+ws://localhost:56238/websocket?ServerExample"
// log.info("Using default URI parameter {}", uri);
// return uri;
// }
// }
| import org.gillius.jagnet.*;
import org.gillius.jagnet.netty.NettyClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import static org.gillius.jagnet.examples.ExampleUtil.getUri; | package org.gillius.jagnet.examples.chat;
public class ChatClient {
public static void main(String[] args) throws Exception {
ConnectionParams params = new ConnectionParams() | // Path: jagnet-core/src/main/java/org/gillius/jagnet/netty/NettyClient.java
// public class NettyClient implements Client {
// private static final Logger log = LoggerFactory.getLogger(NettyClient.class);
//
// private final ConnectionParams params;
//
// private NettyConnection connection;
// private final CompletableFuture<Connection> connFuture = new CompletableFuture<>();
// private EventLoopGroup group;
//
// public NettyClient(ConnectionParams params) {
// this.params = params.clone();
// }
//
// @Override
// public void close() {
// if (connection != null)
// connection.close();
// if (group != null)
// group.shutdownGracefully();
// connection = null;
// group = null;
// }
//
// public void start() {
// //TODO: prevent starting more than once (race conditions on close/failure)
//
// Kryo kryo = KryoBuilder.build(params.getMessageTypes());
//
// group = new NioEventLoopGroup();
// Bootstrap b = new Bootstrap();
// b.group(group)
// .channel(NioSocketChannel.class)
// .option(ChannelOption.TCP_NODELAY, true)
// .handler(new ChannelInitializer<SocketChannel>() {
// @Override
// public void initChannel(SocketChannel ch) throws Exception {
// connection = new NettyConnection(ch);
// connection.getCloseFuture().thenRun(NettyClient.this::close);
// if (params.getProtocol() == Protocol.WS)
// NettyUtils.configurePipelineForWebsocketClient(ch, params);
//
// NettyUtils.setupClientPipeline(ch, params.getProxyTag(), kryo, params, getConnectionStateListener());
// }
// });
//
// // Start the client.
// b.connect(params.getRemoteAddress(), params.getLocalAddress()).addListener(future -> {
// if (!future.isSuccess()) {
// connFuture.completeExceptionally(future.cause());
// close();
// }
// });
// }
//
// @Override
// public CompletableFuture<Connection> getConnection() {
// return connFuture;
// }
//
// private ConnectionStateListener getConnectionStateListener() {
// return new ConnectionStateListener() {
// @Override
// public void onConnected(ConnectionListenerContext ctx) {
// connFuture.complete(connection);
// }
// };
// }
// }
//
// Path: jagnet-examples/src/main/java/org/gillius/jagnet/examples/ExampleUtil.java
// public static String getUri(String args[]) {
// if (args.length > 1) {
// return args[0];
// } else {
// String uri = "tcp://localhost:54555";
// //alternative uri = "proxy+ws://localhost:56238/websocket?ServerExample"
// log.info("Using default URI parameter {}", uri);
// return uri;
// }
// }
// Path: jagnet-examples/src/main/java/org/gillius/jagnet/examples/chat/ChatClient.java
import org.gillius.jagnet.*;
import org.gillius.jagnet.netty.NettyClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import static org.gillius.jagnet.examples.ExampleUtil.getUri;
package org.gillius.jagnet.examples.chat;
public class ChatClient {
public static void main(String[] args) throws Exception {
ConnectionParams params = new ConnectionParams() | .setByURI(getUri(args), false) |
gillius/jagnet | jagnet-examples/src/main/java/org/gillius/jagnet/examples/chat/ChatClient.java | // Path: jagnet-core/src/main/java/org/gillius/jagnet/netty/NettyClient.java
// public class NettyClient implements Client {
// private static final Logger log = LoggerFactory.getLogger(NettyClient.class);
//
// private final ConnectionParams params;
//
// private NettyConnection connection;
// private final CompletableFuture<Connection> connFuture = new CompletableFuture<>();
// private EventLoopGroup group;
//
// public NettyClient(ConnectionParams params) {
// this.params = params.clone();
// }
//
// @Override
// public void close() {
// if (connection != null)
// connection.close();
// if (group != null)
// group.shutdownGracefully();
// connection = null;
// group = null;
// }
//
// public void start() {
// //TODO: prevent starting more than once (race conditions on close/failure)
//
// Kryo kryo = KryoBuilder.build(params.getMessageTypes());
//
// group = new NioEventLoopGroup();
// Bootstrap b = new Bootstrap();
// b.group(group)
// .channel(NioSocketChannel.class)
// .option(ChannelOption.TCP_NODELAY, true)
// .handler(new ChannelInitializer<SocketChannel>() {
// @Override
// public void initChannel(SocketChannel ch) throws Exception {
// connection = new NettyConnection(ch);
// connection.getCloseFuture().thenRun(NettyClient.this::close);
// if (params.getProtocol() == Protocol.WS)
// NettyUtils.configurePipelineForWebsocketClient(ch, params);
//
// NettyUtils.setupClientPipeline(ch, params.getProxyTag(), kryo, params, getConnectionStateListener());
// }
// });
//
// // Start the client.
// b.connect(params.getRemoteAddress(), params.getLocalAddress()).addListener(future -> {
// if (!future.isSuccess()) {
// connFuture.completeExceptionally(future.cause());
// close();
// }
// });
// }
//
// @Override
// public CompletableFuture<Connection> getConnection() {
// return connFuture;
// }
//
// private ConnectionStateListener getConnectionStateListener() {
// return new ConnectionStateListener() {
// @Override
// public void onConnected(ConnectionListenerContext ctx) {
// connFuture.complete(connection);
// }
// };
// }
// }
//
// Path: jagnet-examples/src/main/java/org/gillius/jagnet/examples/ExampleUtil.java
// public static String getUri(String args[]) {
// if (args.length > 1) {
// return args[0];
// } else {
// String uri = "tcp://localhost:54555";
// //alternative uri = "proxy+ws://localhost:56238/websocket?ServerExample"
// log.info("Using default URI parameter {}", uri);
// return uri;
// }
// }
| import org.gillius.jagnet.*;
import org.gillius.jagnet.netty.NettyClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import static org.gillius.jagnet.examples.ExampleUtil.getUri; | package org.gillius.jagnet.examples.chat;
public class ChatClient {
public static void main(String[] args) throws Exception {
ConnectionParams params = new ConnectionParams()
.setByURI(getUri(args), false)
.registerMessages(ChatServer.MESSAGE_CLASSES);
params.setListener(new TypedConnectionListener()
.setListener(ChatMessage.class, (ctx, chatMessage) ->
System.out.format("%20s: %s%n", chatMessage.name, chatMessage.message)));
| // Path: jagnet-core/src/main/java/org/gillius/jagnet/netty/NettyClient.java
// public class NettyClient implements Client {
// private static final Logger log = LoggerFactory.getLogger(NettyClient.class);
//
// private final ConnectionParams params;
//
// private NettyConnection connection;
// private final CompletableFuture<Connection> connFuture = new CompletableFuture<>();
// private EventLoopGroup group;
//
// public NettyClient(ConnectionParams params) {
// this.params = params.clone();
// }
//
// @Override
// public void close() {
// if (connection != null)
// connection.close();
// if (group != null)
// group.shutdownGracefully();
// connection = null;
// group = null;
// }
//
// public void start() {
// //TODO: prevent starting more than once (race conditions on close/failure)
//
// Kryo kryo = KryoBuilder.build(params.getMessageTypes());
//
// group = new NioEventLoopGroup();
// Bootstrap b = new Bootstrap();
// b.group(group)
// .channel(NioSocketChannel.class)
// .option(ChannelOption.TCP_NODELAY, true)
// .handler(new ChannelInitializer<SocketChannel>() {
// @Override
// public void initChannel(SocketChannel ch) throws Exception {
// connection = new NettyConnection(ch);
// connection.getCloseFuture().thenRun(NettyClient.this::close);
// if (params.getProtocol() == Protocol.WS)
// NettyUtils.configurePipelineForWebsocketClient(ch, params);
//
// NettyUtils.setupClientPipeline(ch, params.getProxyTag(), kryo, params, getConnectionStateListener());
// }
// });
//
// // Start the client.
// b.connect(params.getRemoteAddress(), params.getLocalAddress()).addListener(future -> {
// if (!future.isSuccess()) {
// connFuture.completeExceptionally(future.cause());
// close();
// }
// });
// }
//
// @Override
// public CompletableFuture<Connection> getConnection() {
// return connFuture;
// }
//
// private ConnectionStateListener getConnectionStateListener() {
// return new ConnectionStateListener() {
// @Override
// public void onConnected(ConnectionListenerContext ctx) {
// connFuture.complete(connection);
// }
// };
// }
// }
//
// Path: jagnet-examples/src/main/java/org/gillius/jagnet/examples/ExampleUtil.java
// public static String getUri(String args[]) {
// if (args.length > 1) {
// return args[0];
// } else {
// String uri = "tcp://localhost:54555";
// //alternative uri = "proxy+ws://localhost:56238/websocket?ServerExample"
// log.info("Using default URI parameter {}", uri);
// return uri;
// }
// }
// Path: jagnet-examples/src/main/java/org/gillius/jagnet/examples/chat/ChatClient.java
import org.gillius.jagnet.*;
import org.gillius.jagnet.netty.NettyClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import static org.gillius.jagnet.examples.ExampleUtil.getUri;
package org.gillius.jagnet.examples.chat;
public class ChatClient {
public static void main(String[] args) throws Exception {
ConnectionParams params = new ConnectionParams()
.setByURI(getUri(args), false)
.registerMessages(ChatServer.MESSAGE_CLASSES);
params.setListener(new TypedConnectionListener()
.setListener(ChatMessage.class, (ctx, chatMessage) ->
System.out.format("%20s: %s%n", chatMessage.name, chatMessage.message)));
| NettyClient client = new NettyClient(params); |
gillius/jagnet | attic/kryonet/KryonetClient.java | // Path: jagnet-core/src/main/java/org/gillius/jagnet/Client.java
// public interface Client extends ConnectionSource, AutoCloseable {
// void start();
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/Connection.java
// public interface Connection extends AutoCloseable {
// void sendReliable(Object message);
//
// void sendFast(Object message);
//
// SocketAddress getLocalAddress();
//
// SocketAddress getRemoteAddress();
//
// boolean isOpen();
//
// /**
// * Request that the connection shut down. This does not actually block until the connection is closed, use
// * {@link #getCloseFuture()} to determine that.
// */
// @Override
// void close();
//
// /**
// * Returns a future completed when the connection closes.
// */
// CompletableFuture<Connection> getCloseFuture();
//
// /**
// * Submits a task to run on this connection's event loop -- such a task will not run concurrently with the
// * {@link ConnectionListener}.
// */
// void execute(Runnable task);
// /**
// * Submits a task to run on this connection's event loop -- such a task will not run concurrently with the
// * {@link ConnectionListener}.
// */
// <T> Future<T> submit(Callable<T> task);
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/ConnectionListener.java
// public interface ConnectionListener<T> extends ConnectionStateListener, ReceivedMessageListener<T> {
// @Override
// default void onReceive(ConnectionListenerContext ctx, T message) {}
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/FrameworkMessages.java
// public class FrameworkMessages {
// public static List<Class<?>> getMessageTypes() {
// return asList(
// ChatMessage.class,
// TimeSyncRequest.class,
// TimeSyncResponse.class,
// ObjectCreateMessage.class,
// ObjectUpdateMessage.class
// );
// }
//
// public static void register(Kryo kryo) {
// for (Class<?> clazz : getMessageTypes()) {
// kryo.register(clazz);
// }
// }
// }
| import com.esotericsoftware.kryonet.EndPoint;
import org.gillius.jagnet.Client;
import org.gillius.jagnet.Connection;
import org.gillius.jagnet.ConnectionListener;
import org.gillius.jagnet.FrameworkMessages;
import java.io.IOException; | package org.gillius.jagnet.kryonet;
public class KryonetClient extends KryonetClientServerBase implements Client {
private final com.esotericsoftware.kryonet.Client kryonetClient = new com.esotericsoftware.kryonet.Client(); | // Path: jagnet-core/src/main/java/org/gillius/jagnet/Client.java
// public interface Client extends ConnectionSource, AutoCloseable {
// void start();
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/Connection.java
// public interface Connection extends AutoCloseable {
// void sendReliable(Object message);
//
// void sendFast(Object message);
//
// SocketAddress getLocalAddress();
//
// SocketAddress getRemoteAddress();
//
// boolean isOpen();
//
// /**
// * Request that the connection shut down. This does not actually block until the connection is closed, use
// * {@link #getCloseFuture()} to determine that.
// */
// @Override
// void close();
//
// /**
// * Returns a future completed when the connection closes.
// */
// CompletableFuture<Connection> getCloseFuture();
//
// /**
// * Submits a task to run on this connection's event loop -- such a task will not run concurrently with the
// * {@link ConnectionListener}.
// */
// void execute(Runnable task);
// /**
// * Submits a task to run on this connection's event loop -- such a task will not run concurrently with the
// * {@link ConnectionListener}.
// */
// <T> Future<T> submit(Callable<T> task);
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/ConnectionListener.java
// public interface ConnectionListener<T> extends ConnectionStateListener, ReceivedMessageListener<T> {
// @Override
// default void onReceive(ConnectionListenerContext ctx, T message) {}
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/FrameworkMessages.java
// public class FrameworkMessages {
// public static List<Class<?>> getMessageTypes() {
// return asList(
// ChatMessage.class,
// TimeSyncRequest.class,
// TimeSyncResponse.class,
// ObjectCreateMessage.class,
// ObjectUpdateMessage.class
// );
// }
//
// public static void register(Kryo kryo) {
// for (Class<?> clazz : getMessageTypes()) {
// kryo.register(clazz);
// }
// }
// }
// Path: attic/kryonet/KryonetClient.java
import com.esotericsoftware.kryonet.EndPoint;
import org.gillius.jagnet.Client;
import org.gillius.jagnet.Connection;
import org.gillius.jagnet.ConnectionListener;
import org.gillius.jagnet.FrameworkMessages;
import java.io.IOException;
package org.gillius.jagnet.kryonet;
public class KryonetClient extends KryonetClientServerBase implements Client {
private final com.esotericsoftware.kryonet.Client kryonetClient = new com.esotericsoftware.kryonet.Client(); | private final Connection connection = new KryonetConnectionAdapter(kryonetClient); |
gillius/jagnet | attic/kryonet/KryonetClient.java | // Path: jagnet-core/src/main/java/org/gillius/jagnet/Client.java
// public interface Client extends ConnectionSource, AutoCloseable {
// void start();
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/Connection.java
// public interface Connection extends AutoCloseable {
// void sendReliable(Object message);
//
// void sendFast(Object message);
//
// SocketAddress getLocalAddress();
//
// SocketAddress getRemoteAddress();
//
// boolean isOpen();
//
// /**
// * Request that the connection shut down. This does not actually block until the connection is closed, use
// * {@link #getCloseFuture()} to determine that.
// */
// @Override
// void close();
//
// /**
// * Returns a future completed when the connection closes.
// */
// CompletableFuture<Connection> getCloseFuture();
//
// /**
// * Submits a task to run on this connection's event loop -- such a task will not run concurrently with the
// * {@link ConnectionListener}.
// */
// void execute(Runnable task);
// /**
// * Submits a task to run on this connection's event loop -- such a task will not run concurrently with the
// * {@link ConnectionListener}.
// */
// <T> Future<T> submit(Callable<T> task);
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/ConnectionListener.java
// public interface ConnectionListener<T> extends ConnectionStateListener, ReceivedMessageListener<T> {
// @Override
// default void onReceive(ConnectionListenerContext ctx, T message) {}
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/FrameworkMessages.java
// public class FrameworkMessages {
// public static List<Class<?>> getMessageTypes() {
// return asList(
// ChatMessage.class,
// TimeSyncRequest.class,
// TimeSyncResponse.class,
// ObjectCreateMessage.class,
// ObjectUpdateMessage.class
// );
// }
//
// public static void register(Kryo kryo) {
// for (Class<?> clazz : getMessageTypes()) {
// kryo.register(clazz);
// }
// }
// }
| import com.esotericsoftware.kryonet.EndPoint;
import org.gillius.jagnet.Client;
import org.gillius.jagnet.Connection;
import org.gillius.jagnet.ConnectionListener;
import org.gillius.jagnet.FrameworkMessages;
import java.io.IOException; | package org.gillius.jagnet.kryonet;
public class KryonetClient extends KryonetClientServerBase implements Client {
private final com.esotericsoftware.kryonet.Client kryonetClient = new com.esotericsoftware.kryonet.Client();
private final Connection connection = new KryonetConnectionAdapter(kryonetClient);
private String host = null;
public KryonetClient() { | // Path: jagnet-core/src/main/java/org/gillius/jagnet/Client.java
// public interface Client extends ConnectionSource, AutoCloseable {
// void start();
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/Connection.java
// public interface Connection extends AutoCloseable {
// void sendReliable(Object message);
//
// void sendFast(Object message);
//
// SocketAddress getLocalAddress();
//
// SocketAddress getRemoteAddress();
//
// boolean isOpen();
//
// /**
// * Request that the connection shut down. This does not actually block until the connection is closed, use
// * {@link #getCloseFuture()} to determine that.
// */
// @Override
// void close();
//
// /**
// * Returns a future completed when the connection closes.
// */
// CompletableFuture<Connection> getCloseFuture();
//
// /**
// * Submits a task to run on this connection's event loop -- such a task will not run concurrently with the
// * {@link ConnectionListener}.
// */
// void execute(Runnable task);
// /**
// * Submits a task to run on this connection's event loop -- such a task will not run concurrently with the
// * {@link ConnectionListener}.
// */
// <T> Future<T> submit(Callable<T> task);
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/ConnectionListener.java
// public interface ConnectionListener<T> extends ConnectionStateListener, ReceivedMessageListener<T> {
// @Override
// default void onReceive(ConnectionListenerContext ctx, T message) {}
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/FrameworkMessages.java
// public class FrameworkMessages {
// public static List<Class<?>> getMessageTypes() {
// return asList(
// ChatMessage.class,
// TimeSyncRequest.class,
// TimeSyncResponse.class,
// ObjectCreateMessage.class,
// ObjectUpdateMessage.class
// );
// }
//
// public static void register(Kryo kryo) {
// for (Class<?> clazz : getMessageTypes()) {
// kryo.register(clazz);
// }
// }
// }
// Path: attic/kryonet/KryonetClient.java
import com.esotericsoftware.kryonet.EndPoint;
import org.gillius.jagnet.Client;
import org.gillius.jagnet.Connection;
import org.gillius.jagnet.ConnectionListener;
import org.gillius.jagnet.FrameworkMessages;
import java.io.IOException;
package org.gillius.jagnet.kryonet;
public class KryonetClient extends KryonetClientServerBase implements Client {
private final com.esotericsoftware.kryonet.Client kryonetClient = new com.esotericsoftware.kryonet.Client();
private final Connection connection = new KryonetConnectionAdapter(kryonetClient);
private String host = null;
public KryonetClient() { | FrameworkMessages.register(kryonetClient.getKryo()); |
gillius/jagnet | attic/kryonet/KryonetClient.java | // Path: jagnet-core/src/main/java/org/gillius/jagnet/Client.java
// public interface Client extends ConnectionSource, AutoCloseable {
// void start();
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/Connection.java
// public interface Connection extends AutoCloseable {
// void sendReliable(Object message);
//
// void sendFast(Object message);
//
// SocketAddress getLocalAddress();
//
// SocketAddress getRemoteAddress();
//
// boolean isOpen();
//
// /**
// * Request that the connection shut down. This does not actually block until the connection is closed, use
// * {@link #getCloseFuture()} to determine that.
// */
// @Override
// void close();
//
// /**
// * Returns a future completed when the connection closes.
// */
// CompletableFuture<Connection> getCloseFuture();
//
// /**
// * Submits a task to run on this connection's event loop -- such a task will not run concurrently with the
// * {@link ConnectionListener}.
// */
// void execute(Runnable task);
// /**
// * Submits a task to run on this connection's event loop -- such a task will not run concurrently with the
// * {@link ConnectionListener}.
// */
// <T> Future<T> submit(Callable<T> task);
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/ConnectionListener.java
// public interface ConnectionListener<T> extends ConnectionStateListener, ReceivedMessageListener<T> {
// @Override
// default void onReceive(ConnectionListenerContext ctx, T message) {}
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/FrameworkMessages.java
// public class FrameworkMessages {
// public static List<Class<?>> getMessageTypes() {
// return asList(
// ChatMessage.class,
// TimeSyncRequest.class,
// TimeSyncResponse.class,
// ObjectCreateMessage.class,
// ObjectUpdateMessage.class
// );
// }
//
// public static void register(Kryo kryo) {
// for (Class<?> clazz : getMessageTypes()) {
// kryo.register(clazz);
// }
// }
// }
| import com.esotericsoftware.kryonet.EndPoint;
import org.gillius.jagnet.Client;
import org.gillius.jagnet.Connection;
import org.gillius.jagnet.ConnectionListener;
import org.gillius.jagnet.FrameworkMessages;
import java.io.IOException; | package org.gillius.jagnet.kryonet;
public class KryonetClient extends KryonetClientServerBase implements Client {
private final com.esotericsoftware.kryonet.Client kryonetClient = new com.esotericsoftware.kryonet.Client();
private final Connection connection = new KryonetConnectionAdapter(kryonetClient);
private String host = null;
public KryonetClient() {
FrameworkMessages.register(kryonetClient.getKryo());
}
protected EndPoint getEndPoint() {
return kryonetClient;
}
@Override
public void setHost(String host) {
this.host = host;
}
@Override | // Path: jagnet-core/src/main/java/org/gillius/jagnet/Client.java
// public interface Client extends ConnectionSource, AutoCloseable {
// void start();
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/Connection.java
// public interface Connection extends AutoCloseable {
// void sendReliable(Object message);
//
// void sendFast(Object message);
//
// SocketAddress getLocalAddress();
//
// SocketAddress getRemoteAddress();
//
// boolean isOpen();
//
// /**
// * Request that the connection shut down. This does not actually block until the connection is closed, use
// * {@link #getCloseFuture()} to determine that.
// */
// @Override
// void close();
//
// /**
// * Returns a future completed when the connection closes.
// */
// CompletableFuture<Connection> getCloseFuture();
//
// /**
// * Submits a task to run on this connection's event loop -- such a task will not run concurrently with the
// * {@link ConnectionListener}.
// */
// void execute(Runnable task);
// /**
// * Submits a task to run on this connection's event loop -- such a task will not run concurrently with the
// * {@link ConnectionListener}.
// */
// <T> Future<T> submit(Callable<T> task);
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/ConnectionListener.java
// public interface ConnectionListener<T> extends ConnectionStateListener, ReceivedMessageListener<T> {
// @Override
// default void onReceive(ConnectionListenerContext ctx, T message) {}
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/FrameworkMessages.java
// public class FrameworkMessages {
// public static List<Class<?>> getMessageTypes() {
// return asList(
// ChatMessage.class,
// TimeSyncRequest.class,
// TimeSyncResponse.class,
// ObjectCreateMessage.class,
// ObjectUpdateMessage.class
// );
// }
//
// public static void register(Kryo kryo) {
// for (Class<?> clazz : getMessageTypes()) {
// kryo.register(clazz);
// }
// }
// }
// Path: attic/kryonet/KryonetClient.java
import com.esotericsoftware.kryonet.EndPoint;
import org.gillius.jagnet.Client;
import org.gillius.jagnet.Connection;
import org.gillius.jagnet.ConnectionListener;
import org.gillius.jagnet.FrameworkMessages;
import java.io.IOException;
package org.gillius.jagnet.kryonet;
public class KryonetClient extends KryonetClientServerBase implements Client {
private final com.esotericsoftware.kryonet.Client kryonetClient = new com.esotericsoftware.kryonet.Client();
private final Connection connection = new KryonetConnectionAdapter(kryonetClient);
private String host = null;
public KryonetClient() {
FrameworkMessages.register(kryonetClient.getKryo());
}
protected EndPoint getEndPoint() {
return kryonetClient;
}
@Override
public void setHost(String host) {
this.host = host;
}
@Override | public void setListener(ConnectionListener listener) { |
gillius/jagnet | jagnet-core/src/main/java/org/gillius/jagnet/netty/NettyHandler.java | // Path: jagnet-core/src/main/java/org/gillius/jagnet/ConnectionListener.java
// public interface ConnectionListener<T> extends ConnectionStateListener, ReceivedMessageListener<T> {
// @Override
// default void onReceive(ConnectionListenerContext ctx, T message) {}
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/ConnectionStateListener.java
// public interface ConnectionStateListener {
// default void onConnected(ConnectionListenerContext ctx) {}
//
// default void onDisconnected(ConnectionListenerContext ctx) {}
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/SingleConnectionListenerContext.java
// public class SingleConnectionListenerContext implements ConnectionListenerContext {
// private final Connection connection;
//
// public SingleConnectionListenerContext(Connection connection) {
// this.connection = connection;
// }
//
// @Override
// public Connection getConnection() {
// return connection;
// }
//
// @Override
// public void consumeCurrentEvent() {
// //do nothing as this is not a listener chain
// }
// }
| import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.gillius.jagnet.ConnectionListener;
import org.gillius.jagnet.ConnectionStateListener;
import org.gillius.jagnet.SingleConnectionListenerContext; | package org.gillius.jagnet.netty;
class NettyHandler extends ChannelInboundHandlerAdapter {
private final SingleConnectionListenerContext clc; | // Path: jagnet-core/src/main/java/org/gillius/jagnet/ConnectionListener.java
// public interface ConnectionListener<T> extends ConnectionStateListener, ReceivedMessageListener<T> {
// @Override
// default void onReceive(ConnectionListenerContext ctx, T message) {}
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/ConnectionStateListener.java
// public interface ConnectionStateListener {
// default void onConnected(ConnectionListenerContext ctx) {}
//
// default void onDisconnected(ConnectionListenerContext ctx) {}
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/SingleConnectionListenerContext.java
// public class SingleConnectionListenerContext implements ConnectionListenerContext {
// private final Connection connection;
//
// public SingleConnectionListenerContext(Connection connection) {
// this.connection = connection;
// }
//
// @Override
// public Connection getConnection() {
// return connection;
// }
//
// @Override
// public void consumeCurrentEvent() {
// //do nothing as this is not a listener chain
// }
// }
// Path: jagnet-core/src/main/java/org/gillius/jagnet/netty/NettyHandler.java
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.gillius.jagnet.ConnectionListener;
import org.gillius.jagnet.ConnectionStateListener;
import org.gillius.jagnet.SingleConnectionListenerContext;
package org.gillius.jagnet.netty;
class NettyHandler extends ChannelInboundHandlerAdapter {
private final SingleConnectionListenerContext clc; | private final ConnectionListener listener; |
gillius/jagnet | jagnet-core/src/main/java/org/gillius/jagnet/netty/NettyHandler.java | // Path: jagnet-core/src/main/java/org/gillius/jagnet/ConnectionListener.java
// public interface ConnectionListener<T> extends ConnectionStateListener, ReceivedMessageListener<T> {
// @Override
// default void onReceive(ConnectionListenerContext ctx, T message) {}
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/ConnectionStateListener.java
// public interface ConnectionStateListener {
// default void onConnected(ConnectionListenerContext ctx) {}
//
// default void onDisconnected(ConnectionListenerContext ctx) {}
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/SingleConnectionListenerContext.java
// public class SingleConnectionListenerContext implements ConnectionListenerContext {
// private final Connection connection;
//
// public SingleConnectionListenerContext(Connection connection) {
// this.connection = connection;
// }
//
// @Override
// public Connection getConnection() {
// return connection;
// }
//
// @Override
// public void consumeCurrentEvent() {
// //do nothing as this is not a listener chain
// }
// }
| import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.gillius.jagnet.ConnectionListener;
import org.gillius.jagnet.ConnectionStateListener;
import org.gillius.jagnet.SingleConnectionListenerContext; | package org.gillius.jagnet.netty;
class NettyHandler extends ChannelInboundHandlerAdapter {
private final SingleConnectionListenerContext clc;
private final ConnectionListener listener; | // Path: jagnet-core/src/main/java/org/gillius/jagnet/ConnectionListener.java
// public interface ConnectionListener<T> extends ConnectionStateListener, ReceivedMessageListener<T> {
// @Override
// default void onReceive(ConnectionListenerContext ctx, T message) {}
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/ConnectionStateListener.java
// public interface ConnectionStateListener {
// default void onConnected(ConnectionListenerContext ctx) {}
//
// default void onDisconnected(ConnectionListenerContext ctx) {}
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/SingleConnectionListenerContext.java
// public class SingleConnectionListenerContext implements ConnectionListenerContext {
// private final Connection connection;
//
// public SingleConnectionListenerContext(Connection connection) {
// this.connection = connection;
// }
//
// @Override
// public Connection getConnection() {
// return connection;
// }
//
// @Override
// public void consumeCurrentEvent() {
// //do nothing as this is not a listener chain
// }
// }
// Path: jagnet-core/src/main/java/org/gillius/jagnet/netty/NettyHandler.java
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.gillius.jagnet.ConnectionListener;
import org.gillius.jagnet.ConnectionStateListener;
import org.gillius.jagnet.SingleConnectionListenerContext;
package org.gillius.jagnet.netty;
class NettyHandler extends ChannelInboundHandlerAdapter {
private final SingleConnectionListenerContext clc;
private final ConnectionListener listener; | private final ConnectionStateListener connectionStateListener; |
gillius/jagnet | attic/kryonet/KryonetClientConnectionListenerAdapter.java | // Path: jagnet-core/src/main/java/org/gillius/jagnet/Connection.java
// public interface Connection extends AutoCloseable {
// void sendReliable(Object message);
//
// void sendFast(Object message);
//
// SocketAddress getLocalAddress();
//
// SocketAddress getRemoteAddress();
//
// boolean isOpen();
//
// /**
// * Request that the connection shut down. This does not actually block until the connection is closed, use
// * {@link #getCloseFuture()} to determine that.
// */
// @Override
// void close();
//
// /**
// * Returns a future completed when the connection closes.
// */
// CompletableFuture<Connection> getCloseFuture();
//
// /**
// * Submits a task to run on this connection's event loop -- such a task will not run concurrently with the
// * {@link ConnectionListener}.
// */
// void execute(Runnable task);
// /**
// * Submits a task to run on this connection's event loop -- such a task will not run concurrently with the
// * {@link ConnectionListener}.
// */
// <T> Future<T> submit(Callable<T> task);
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/ConnectionListener.java
// public interface ConnectionListener<T> extends ConnectionStateListener, ReceivedMessageListener<T> {
// @Override
// default void onReceive(ConnectionListenerContext ctx, T message) {}
// }
| import com.esotericsoftware.kryonet.Listener;
import org.gillius.jagnet.Connection;
import org.gillius.jagnet.ConnectionListener; | package org.gillius.jagnet.kryonet;
public class KryonetClientConnectionListenerAdapter extends Listener {
private final ConnectionListener listener; | // Path: jagnet-core/src/main/java/org/gillius/jagnet/Connection.java
// public interface Connection extends AutoCloseable {
// void sendReliable(Object message);
//
// void sendFast(Object message);
//
// SocketAddress getLocalAddress();
//
// SocketAddress getRemoteAddress();
//
// boolean isOpen();
//
// /**
// * Request that the connection shut down. This does not actually block until the connection is closed, use
// * {@link #getCloseFuture()} to determine that.
// */
// @Override
// void close();
//
// /**
// * Returns a future completed when the connection closes.
// */
// CompletableFuture<Connection> getCloseFuture();
//
// /**
// * Submits a task to run on this connection's event loop -- such a task will not run concurrently with the
// * {@link ConnectionListener}.
// */
// void execute(Runnable task);
// /**
// * Submits a task to run on this connection's event loop -- such a task will not run concurrently with the
// * {@link ConnectionListener}.
// */
// <T> Future<T> submit(Callable<T> task);
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/ConnectionListener.java
// public interface ConnectionListener<T> extends ConnectionStateListener, ReceivedMessageListener<T> {
// @Override
// default void onReceive(ConnectionListenerContext ctx, T message) {}
// }
// Path: attic/kryonet/KryonetClientConnectionListenerAdapter.java
import com.esotericsoftware.kryonet.Listener;
import org.gillius.jagnet.Connection;
import org.gillius.jagnet.ConnectionListener;
package org.gillius.jagnet.kryonet;
public class KryonetClientConnectionListenerAdapter extends Listener {
private final ConnectionListener listener; | private final Connection connection; |
gillius/jagnet | jagnet-proxy-server/src/main/java/org/gillius/jagnet/proxy/server/ProxyMap.java | // Path: jagnet-core/src/main/java/org/gillius/jagnet/proxy/ProxyConstants.java
// public class ProxyConstants {
// public static final String INTRO_HEADER = "jagnet proxy";
// public static final String INTRO_HEADER_SERVICE = "jagnet proxy service";
// public static final String SERVICE_TAKEN = "Service taken";
// public static final String NO_SUCH_SERVICE = "No such service";
// public static final String INVALID_TAG = "Invalid tag";
// public static final String WAITING_FOR_REMOTE = "Waiting for remote";
// public static final String CONNECTED = "Connected";
//
// public static final String SERVICE_PREFIX = "service:";
// public static final String DYNAMIC_PREFIX = "dynamic:";
// }
| import io.netty.channel.Channel;
import io.netty.util.concurrent.Promise;
import org.gillius.jagnet.proxy.ProxyConstants;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.function.BiConsumer; | package org.gillius.jagnet.proxy.server;
public class ProxyMap {
private final Map<String, Service> services = new HashMap<>();
private final Map<String, Waiter> waiters = new HashMap<>();
private final Random random = new Random();
public synchronized boolean matchService(String id, Channel channel, Promise<Channel> otherChannel) {
Service service = services.get(id);
if (service != null) {
//Select a new, unused tag slot
String newtag = "";
while (newtag.isEmpty() || waiters.containsKey(newtag)) | // Path: jagnet-core/src/main/java/org/gillius/jagnet/proxy/ProxyConstants.java
// public class ProxyConstants {
// public static final String INTRO_HEADER = "jagnet proxy";
// public static final String INTRO_HEADER_SERVICE = "jagnet proxy service";
// public static final String SERVICE_TAKEN = "Service taken";
// public static final String NO_SUCH_SERVICE = "No such service";
// public static final String INVALID_TAG = "Invalid tag";
// public static final String WAITING_FOR_REMOTE = "Waiting for remote";
// public static final String CONNECTED = "Connected";
//
// public static final String SERVICE_PREFIX = "service:";
// public static final String DYNAMIC_PREFIX = "dynamic:";
// }
// Path: jagnet-proxy-server/src/main/java/org/gillius/jagnet/proxy/server/ProxyMap.java
import io.netty.channel.Channel;
import io.netty.util.concurrent.Promise;
import org.gillius.jagnet.proxy.ProxyConstants;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.function.BiConsumer;
package org.gillius.jagnet.proxy.server;
public class ProxyMap {
private final Map<String, Service> services = new HashMap<>();
private final Map<String, Waiter> waiters = new HashMap<>();
private final Random random = new Random();
public synchronized boolean matchService(String id, Channel channel, Promise<Channel> otherChannel) {
Service service = services.get(id);
if (service != null) {
//Select a new, unused tag slot
String newtag = "";
while (newtag.isEmpty() || waiters.containsKey(newtag)) | newtag = ProxyConstants.DYNAMIC_PREFIX + random.nextLong(); |
gillius/jagnet | jagnet-proxy-server/src/main/java/org/gillius/jagnet/proxy/server/ProxyServer.java | // Path: jagnet-core/src/main/java/org/gillius/jagnet/netty/WebsocketServerFrameHandler.java
// public class WebsocketServerFrameHandler extends ChannelDuplexHandler {
// @Override
// public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
// if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
// ctx.pipeline().addAfter(ctx.executor(), ctx.name(), null, new WebsocketBinaryFrameCodec());
// ctx.pipeline().remove(this);
// }
// super.userEventTriggered(ctx, evt);
// }
// }
| import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.gillius.jagnet.netty.WebsocketServerFrameHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; |
private static class TcpProxyChannelInitializer extends ChannelInitializer<SocketChannel> {
private final ProxyMap proxyMap;
public TcpProxyChannelInitializer(ProxyMap proxyMap) {
this.proxyMap = proxyMap;
}
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline()
.addLast(new LineBasedFrameDecoder(512, true, true))
.addLast(new ProxyServerHandler(proxyMap))
;
}
}
private static class WebsocketProxyChannelInitializer extends ChannelInitializer<SocketChannel> {
private final ProxyMap proxyMap;
public WebsocketProxyChannelInitializer(ProxyMap proxyMap) {
this.proxyMap = proxyMap;
}
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline()
.addLast(new HttpServerCodec())
.addLast(new HttpObjectAggregator(65536))
.addLast(new WebSocketServerProtocolHandler("/websocket", null, true)) | // Path: jagnet-core/src/main/java/org/gillius/jagnet/netty/WebsocketServerFrameHandler.java
// public class WebsocketServerFrameHandler extends ChannelDuplexHandler {
// @Override
// public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
// if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
// ctx.pipeline().addAfter(ctx.executor(), ctx.name(), null, new WebsocketBinaryFrameCodec());
// ctx.pipeline().remove(this);
// }
// super.userEventTriggered(ctx, evt);
// }
// }
// Path: jagnet-proxy-server/src/main/java/org/gillius/jagnet/proxy/server/ProxyServer.java
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.gillius.jagnet.netty.WebsocketServerFrameHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static class TcpProxyChannelInitializer extends ChannelInitializer<SocketChannel> {
private final ProxyMap proxyMap;
public TcpProxyChannelInitializer(ProxyMap proxyMap) {
this.proxyMap = proxyMap;
}
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline()
.addLast(new LineBasedFrameDecoder(512, true, true))
.addLast(new ProxyServerHandler(proxyMap))
;
}
}
private static class WebsocketProxyChannelInitializer extends ChannelInitializer<SocketChannel> {
private final ProxyMap proxyMap;
public WebsocketProxyChannelInitializer(ProxyMap proxyMap) {
this.proxyMap = proxyMap;
}
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline()
.addLast(new HttpServerCodec())
.addLast(new HttpObjectAggregator(65536))
.addLast(new WebSocketServerProtocolHandler("/websocket", null, true)) | .addLast(new WebsocketServerFrameHandler()) |
gillius/jagnet | attic/kryonet/KryonetServer.java | // Path: jagnet-core/src/main/java/org/gillius/jagnet/ConnectionListener.java
// public interface ConnectionListener<T> extends ConnectionStateListener, ReceivedMessageListener<T> {
// @Override
// default void onReceive(ConnectionListenerContext ctx, T message) {}
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/FrameworkMessages.java
// public class FrameworkMessages {
// public static List<Class<?>> getMessageTypes() {
// return asList(
// ChatMessage.class,
// TimeSyncRequest.class,
// TimeSyncResponse.class,
// ObjectCreateMessage.class,
// ObjectUpdateMessage.class
// );
// }
//
// public static void register(Kryo kryo) {
// for (Class<?> clazz : getMessageTypes()) {
// kryo.register(clazz);
// }
// }
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/Server.java
// public interface Server extends AutoCloseable {
// AcceptPolicy getAcceptPolicy();
//
// void setAcceptPolicy(AcceptPolicy acceptPolicy);
//
// ConnectionStateListener getConnectionStateListener();
//
// void setConnectionStateListener(ConnectionStateListener connectionStateListener);
//
// void start(ConnectionParams params);
//
// void stopAcceptingNewConnections();
//
// @Override
// void close();
// }
| import com.esotericsoftware.kryonet.EndPoint;
import org.gillius.jagnet.ConnectionListener;
import org.gillius.jagnet.FrameworkMessages;
import org.gillius.jagnet.Server;
import java.io.IOException; | package org.gillius.jagnet.kryonet;
public class KryonetServer extends KryonetClientServerBase implements Server {
private com.esotericsoftware.kryonet.Server kryonetServer = new com.esotericsoftware.kryonet.Server();
public KryonetServer() { | // Path: jagnet-core/src/main/java/org/gillius/jagnet/ConnectionListener.java
// public interface ConnectionListener<T> extends ConnectionStateListener, ReceivedMessageListener<T> {
// @Override
// default void onReceive(ConnectionListenerContext ctx, T message) {}
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/FrameworkMessages.java
// public class FrameworkMessages {
// public static List<Class<?>> getMessageTypes() {
// return asList(
// ChatMessage.class,
// TimeSyncRequest.class,
// TimeSyncResponse.class,
// ObjectCreateMessage.class,
// ObjectUpdateMessage.class
// );
// }
//
// public static void register(Kryo kryo) {
// for (Class<?> clazz : getMessageTypes()) {
// kryo.register(clazz);
// }
// }
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/Server.java
// public interface Server extends AutoCloseable {
// AcceptPolicy getAcceptPolicy();
//
// void setAcceptPolicy(AcceptPolicy acceptPolicy);
//
// ConnectionStateListener getConnectionStateListener();
//
// void setConnectionStateListener(ConnectionStateListener connectionStateListener);
//
// void start(ConnectionParams params);
//
// void stopAcceptingNewConnections();
//
// @Override
// void close();
// }
// Path: attic/kryonet/KryonetServer.java
import com.esotericsoftware.kryonet.EndPoint;
import org.gillius.jagnet.ConnectionListener;
import org.gillius.jagnet.FrameworkMessages;
import org.gillius.jagnet.Server;
import java.io.IOException;
package org.gillius.jagnet.kryonet;
public class KryonetServer extends KryonetClientServerBase implements Server {
private com.esotericsoftware.kryonet.Server kryonetServer = new com.esotericsoftware.kryonet.Server();
public KryonetServer() { | FrameworkMessages.register(kryonetServer.getKryo()); |
gillius/jagnet | attic/kryonet/KryonetServer.java | // Path: jagnet-core/src/main/java/org/gillius/jagnet/ConnectionListener.java
// public interface ConnectionListener<T> extends ConnectionStateListener, ReceivedMessageListener<T> {
// @Override
// default void onReceive(ConnectionListenerContext ctx, T message) {}
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/FrameworkMessages.java
// public class FrameworkMessages {
// public static List<Class<?>> getMessageTypes() {
// return asList(
// ChatMessage.class,
// TimeSyncRequest.class,
// TimeSyncResponse.class,
// ObjectCreateMessage.class,
// ObjectUpdateMessage.class
// );
// }
//
// public static void register(Kryo kryo) {
// for (Class<?> clazz : getMessageTypes()) {
// kryo.register(clazz);
// }
// }
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/Server.java
// public interface Server extends AutoCloseable {
// AcceptPolicy getAcceptPolicy();
//
// void setAcceptPolicy(AcceptPolicy acceptPolicy);
//
// ConnectionStateListener getConnectionStateListener();
//
// void setConnectionStateListener(ConnectionStateListener connectionStateListener);
//
// void start(ConnectionParams params);
//
// void stopAcceptingNewConnections();
//
// @Override
// void close();
// }
| import com.esotericsoftware.kryonet.EndPoint;
import org.gillius.jagnet.ConnectionListener;
import org.gillius.jagnet.FrameworkMessages;
import org.gillius.jagnet.Server;
import java.io.IOException; | package org.gillius.jagnet.kryonet;
public class KryonetServer extends KryonetClientServerBase implements Server {
private com.esotericsoftware.kryonet.Server kryonetServer = new com.esotericsoftware.kryonet.Server();
public KryonetServer() {
FrameworkMessages.register(kryonetServer.getKryo());
}
@Override
protected EndPoint getEndPoint() {
return kryonetServer;
}
@Override | // Path: jagnet-core/src/main/java/org/gillius/jagnet/ConnectionListener.java
// public interface ConnectionListener<T> extends ConnectionStateListener, ReceivedMessageListener<T> {
// @Override
// default void onReceive(ConnectionListenerContext ctx, T message) {}
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/FrameworkMessages.java
// public class FrameworkMessages {
// public static List<Class<?>> getMessageTypes() {
// return asList(
// ChatMessage.class,
// TimeSyncRequest.class,
// TimeSyncResponse.class,
// ObjectCreateMessage.class,
// ObjectUpdateMessage.class
// );
// }
//
// public static void register(Kryo kryo) {
// for (Class<?> clazz : getMessageTypes()) {
// kryo.register(clazz);
// }
// }
// }
//
// Path: jagnet-core/src/main/java/org/gillius/jagnet/Server.java
// public interface Server extends AutoCloseable {
// AcceptPolicy getAcceptPolicy();
//
// void setAcceptPolicy(AcceptPolicy acceptPolicy);
//
// ConnectionStateListener getConnectionStateListener();
//
// void setConnectionStateListener(ConnectionStateListener connectionStateListener);
//
// void start(ConnectionParams params);
//
// void stopAcceptingNewConnections();
//
// @Override
// void close();
// }
// Path: attic/kryonet/KryonetServer.java
import com.esotericsoftware.kryonet.EndPoint;
import org.gillius.jagnet.ConnectionListener;
import org.gillius.jagnet.FrameworkMessages;
import org.gillius.jagnet.Server;
import java.io.IOException;
package org.gillius.jagnet.kryonet;
public class KryonetServer extends KryonetClientServerBase implements Server {
private com.esotericsoftware.kryonet.Server kryonetServer = new com.esotericsoftware.kryonet.Server();
public KryonetServer() {
FrameworkMessages.register(kryonetServer.getKryo());
}
@Override
protected EndPoint getEndPoint() {
return kryonetServer;
}
@Override | public void setListener(ConnectionListener listener) { |
gillius/jagnet | jagnet-core/src/main/java/org/gillius/jagnet/netty/NettyServer.java | // Path: jagnet-core/src/main/java/org/gillius/jagnet/proxy/ProxyRemoteServerHandler.java
// public class ProxyRemoteServerHandler extends ByteToMessageDecoder {
// private static final Logger log = LoggerFactory.getLogger(ProxyRemoteServerHandler.class);
//
// private final String tag;
// private final Consumer<String> onIncomingConnection;
// private final CompletableFuture<?> registeredFuture;
//
// private BiConsumer<ChannelHandlerContext, String> state = this::waitForAck;
//
// public ProxyRemoteServerHandler(String tag, Consumer<String> onIncomingConnection, CompletableFuture<?> registeredFuture) {
// this.tag = tag;
// this.onIncomingConnection = onIncomingConnection;
// this.registeredFuture = registeredFuture;
// }
//
// @Override
// public void channelActive(ChannelHandlerContext ctx) throws Exception {
// super.channelActive(ctx);
// ctx.writeAndFlush(Unpooled.copiedBuffer(ProxyConstants.INTRO_HEADER_SERVICE + "\n" +
// ProxyConstants.SERVICE_PREFIX + tag + "\n",
// CharsetUtil.UTF_8));
// }
//
// @Override
// protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
// int len = in.readableBytes();
// String line = in.readCharSequence(len, CharsetUtil.UTF_8).toString();
// state.accept(ctx, line);
// }
//
// private void waitForAck(ChannelHandlerContext ctx, String line) {
// switch (line) {
// case ProxyConstants.WAITING_FOR_REMOTE:
// log.info("Service {} registered, waiting", tag);
// registeredFuture.complete(null);
// state = this::waitConnections;
// break;
//
// case ProxyConstants.SERVICE_TAKEN:
// String msg = "Service " + tag + " already registered on remote";
// log.warn(msg);
// registeredFuture.completeExceptionally(new IllegalStateException(msg));
// ctx.close();
// break;
//
// default:
// log.error("Bad response {}", line);
// ctx.close();
// break;
// }
// }
//
// @SuppressWarnings("unused")
// private void waitConnections(ChannelHandlerContext ctx, String line) {
// onIncomingConnection.accept(line);
// }
// }
| import com.esotericsoftware.kryo.Kryo;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.gillius.jagnet.*;
import org.gillius.jagnet.proxy.ProxyRemoteServerHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.CompletableFuture; | NettyUtils.setupPipeline(ch, KryoBuilder.build(params.getMessageTypes()), params.getListenerFactory(), connectionStateListener);
}
})
.childOption(ChannelOption.TCP_NODELAY, true)
.childOption(ChannelOption.SO_KEEPALIVE, true);
listeningFuture.thenRun(() -> log.info("Server listening on {}", params.getLocalAddress()));
ChannelFuture future = b.bind(params.getLocalAddress());
future.addListener(f -> {
if (f.isSuccess())
listeningFuture.complete(null);
else
listeningFuture.completeExceptionally(f.cause());
});
return future;
}
public ChannelFuture startRemoteListening() {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
if (params.getProtocol() == Protocol.WS)
NettyUtils.configurePipelineForWebsocketClient(ch, params);
ch.pipeline()
.addLast(new LineBasedFrameDecoder(512, true, true)) | // Path: jagnet-core/src/main/java/org/gillius/jagnet/proxy/ProxyRemoteServerHandler.java
// public class ProxyRemoteServerHandler extends ByteToMessageDecoder {
// private static final Logger log = LoggerFactory.getLogger(ProxyRemoteServerHandler.class);
//
// private final String tag;
// private final Consumer<String> onIncomingConnection;
// private final CompletableFuture<?> registeredFuture;
//
// private BiConsumer<ChannelHandlerContext, String> state = this::waitForAck;
//
// public ProxyRemoteServerHandler(String tag, Consumer<String> onIncomingConnection, CompletableFuture<?> registeredFuture) {
// this.tag = tag;
// this.onIncomingConnection = onIncomingConnection;
// this.registeredFuture = registeredFuture;
// }
//
// @Override
// public void channelActive(ChannelHandlerContext ctx) throws Exception {
// super.channelActive(ctx);
// ctx.writeAndFlush(Unpooled.copiedBuffer(ProxyConstants.INTRO_HEADER_SERVICE + "\n" +
// ProxyConstants.SERVICE_PREFIX + tag + "\n",
// CharsetUtil.UTF_8));
// }
//
// @Override
// protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
// int len = in.readableBytes();
// String line = in.readCharSequence(len, CharsetUtil.UTF_8).toString();
// state.accept(ctx, line);
// }
//
// private void waitForAck(ChannelHandlerContext ctx, String line) {
// switch (line) {
// case ProxyConstants.WAITING_FOR_REMOTE:
// log.info("Service {} registered, waiting", tag);
// registeredFuture.complete(null);
// state = this::waitConnections;
// break;
//
// case ProxyConstants.SERVICE_TAKEN:
// String msg = "Service " + tag + " already registered on remote";
// log.warn(msg);
// registeredFuture.completeExceptionally(new IllegalStateException(msg));
// ctx.close();
// break;
//
// default:
// log.error("Bad response {}", line);
// ctx.close();
// break;
// }
// }
//
// @SuppressWarnings("unused")
// private void waitConnections(ChannelHandlerContext ctx, String line) {
// onIncomingConnection.accept(line);
// }
// }
// Path: jagnet-core/src/main/java/org/gillius/jagnet/netty/NettyServer.java
import com.esotericsoftware.kryo.Kryo;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.gillius.jagnet.*;
import org.gillius.jagnet.proxy.ProxyRemoteServerHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.CompletableFuture;
NettyUtils.setupPipeline(ch, KryoBuilder.build(params.getMessageTypes()), params.getListenerFactory(), connectionStateListener);
}
})
.childOption(ChannelOption.TCP_NODELAY, true)
.childOption(ChannelOption.SO_KEEPALIVE, true);
listeningFuture.thenRun(() -> log.info("Server listening on {}", params.getLocalAddress()));
ChannelFuture future = b.bind(params.getLocalAddress());
future.addListener(f -> {
if (f.isSuccess())
listeningFuture.complete(null);
else
listeningFuture.completeExceptionally(f.cause());
});
return future;
}
public ChannelFuture startRemoteListening() {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
if (params.getProtocol() == Protocol.WS)
NettyUtils.configurePipelineForWebsocketClient(ch, params);
ch.pipeline()
.addLast(new LineBasedFrameDecoder(512, true, true)) | .addLast(new ProxyRemoteServerHandler(params.getProxyTag(), NettyServer.this::addClient, listeningFuture)); |
gillius/jagnet | jagnet-proxy-server/src/main/java/org/gillius/jagnet/proxy/server/ProxyServerHandler.java | // Path: jagnet-core/src/main/java/org/gillius/jagnet/proxy/ProxyConstants.java
// public class ProxyConstants {
// public static final String INTRO_HEADER = "jagnet proxy";
// public static final String INTRO_HEADER_SERVICE = "jagnet proxy service";
// public static final String SERVICE_TAKEN = "Service taken";
// public static final String NO_SUCH_SERVICE = "No such service";
// public static final String INVALID_TAG = "Invalid tag";
// public static final String WAITING_FOR_REMOTE = "Waiting for remote";
// public static final String CONNECTED = "Connected";
//
// public static final String SERVICE_PREFIX = "service:";
// public static final String DYNAMIC_PREFIX = "dynamic:";
// }
| import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundInvoker;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.Promise;
import org.gillius.jagnet.proxy.ProxyConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.function.BiConsumer; | package org.gillius.jagnet.proxy.server;
class ProxyServerHandler extends ByteToMessageDecoder {
private static final Logger log = LoggerFactory.getLogger(ProxyServerHandler.class);
private BiConsumer<ChannelHandlerContext, String> state = this::headerState;
private final ProxyMap proxyMap;
ProxyServerHandler(ProxyMap proxyMap) {
this.proxyMap = proxyMap;
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
int len = in.readableBytes();
String line = in.readCharSequence(len, CharsetUtil.UTF_8).toString();
state.accept(ctx, line);
}
private void headerState(ChannelHandlerContext ctx, String line) { | // Path: jagnet-core/src/main/java/org/gillius/jagnet/proxy/ProxyConstants.java
// public class ProxyConstants {
// public static final String INTRO_HEADER = "jagnet proxy";
// public static final String INTRO_HEADER_SERVICE = "jagnet proxy service";
// public static final String SERVICE_TAKEN = "Service taken";
// public static final String NO_SUCH_SERVICE = "No such service";
// public static final String INVALID_TAG = "Invalid tag";
// public static final String WAITING_FOR_REMOTE = "Waiting for remote";
// public static final String CONNECTED = "Connected";
//
// public static final String SERVICE_PREFIX = "service:";
// public static final String DYNAMIC_PREFIX = "dynamic:";
// }
// Path: jagnet-proxy-server/src/main/java/org/gillius/jagnet/proxy/server/ProxyServerHandler.java
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundInvoker;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.Promise;
import org.gillius.jagnet.proxy.ProxyConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.function.BiConsumer;
package org.gillius.jagnet.proxy.server;
class ProxyServerHandler extends ByteToMessageDecoder {
private static final Logger log = LoggerFactory.getLogger(ProxyServerHandler.class);
private BiConsumer<ChannelHandlerContext, String> state = this::headerState;
private final ProxyMap proxyMap;
ProxyServerHandler(ProxyMap proxyMap) {
this.proxyMap = proxyMap;
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
int len = in.readableBytes();
String line = in.readCharSequence(len, CharsetUtil.UTF_8).toString();
state.accept(ctx, line);
}
private void headerState(ChannelHandlerContext ctx, String line) { | if (ProxyConstants.INTRO_HEADER.equals(line)) { |
gillius/jagnet | jagnet-examples/src/main/java/org/gillius/jagnet/examples/ClientExample.java | // Path: jagnet-core/src/main/java/org/gillius/jagnet/netty/NettyClient.java
// public class NettyClient implements Client {
// private static final Logger log = LoggerFactory.getLogger(NettyClient.class);
//
// private final ConnectionParams params;
//
// private NettyConnection connection;
// private final CompletableFuture<Connection> connFuture = new CompletableFuture<>();
// private EventLoopGroup group;
//
// public NettyClient(ConnectionParams params) {
// this.params = params.clone();
// }
//
// @Override
// public void close() {
// if (connection != null)
// connection.close();
// if (group != null)
// group.shutdownGracefully();
// connection = null;
// group = null;
// }
//
// public void start() {
// //TODO: prevent starting more than once (race conditions on close/failure)
//
// Kryo kryo = KryoBuilder.build(params.getMessageTypes());
//
// group = new NioEventLoopGroup();
// Bootstrap b = new Bootstrap();
// b.group(group)
// .channel(NioSocketChannel.class)
// .option(ChannelOption.TCP_NODELAY, true)
// .handler(new ChannelInitializer<SocketChannel>() {
// @Override
// public void initChannel(SocketChannel ch) throws Exception {
// connection = new NettyConnection(ch);
// connection.getCloseFuture().thenRun(NettyClient.this::close);
// if (params.getProtocol() == Protocol.WS)
// NettyUtils.configurePipelineForWebsocketClient(ch, params);
//
// NettyUtils.setupClientPipeline(ch, params.getProxyTag(), kryo, params, getConnectionStateListener());
// }
// });
//
// // Start the client.
// b.connect(params.getRemoteAddress(), params.getLocalAddress()).addListener(future -> {
// if (!future.isSuccess()) {
// connFuture.completeExceptionally(future.cause());
// close();
// }
// });
// }
//
// @Override
// public CompletableFuture<Connection> getConnection() {
// return connFuture;
// }
//
// private ConnectionStateListener getConnectionStateListener() {
// return new ConnectionStateListener() {
// @Override
// public void onConnected(ConnectionListenerContext ctx) {
// connFuture.complete(connection);
// }
// };
// }
// }
//
// Path: jagnet-examples/src/main/java/org/gillius/jagnet/examples/ExampleUtil.java
// public static String getUri(String args[]) {
// if (args.length > 1) {
// return args[0];
// } else {
// String uri = "tcp://localhost:54555";
// //alternative uri = "proxy+ws://localhost:56238/websocket?ServerExample"
// log.info("Using default URI parameter {}", uri);
// return uri;
// }
// }
| import org.gillius.jagnet.*;
import org.gillius.jagnet.netty.NettyClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.gillius.jagnet.examples.ExampleUtil.getUri; | package org.gillius.jagnet.examples;
public class ClientExample {
private static final Logger log = LoggerFactory.getLogger(ClientExample.class);
public static void main(String[] args) throws Exception {
ConditionConnectionListener listener = new ConditionConnectionListener();
ConnectionParams params = new ConnectionParams() | // Path: jagnet-core/src/main/java/org/gillius/jagnet/netty/NettyClient.java
// public class NettyClient implements Client {
// private static final Logger log = LoggerFactory.getLogger(NettyClient.class);
//
// private final ConnectionParams params;
//
// private NettyConnection connection;
// private final CompletableFuture<Connection> connFuture = new CompletableFuture<>();
// private EventLoopGroup group;
//
// public NettyClient(ConnectionParams params) {
// this.params = params.clone();
// }
//
// @Override
// public void close() {
// if (connection != null)
// connection.close();
// if (group != null)
// group.shutdownGracefully();
// connection = null;
// group = null;
// }
//
// public void start() {
// //TODO: prevent starting more than once (race conditions on close/failure)
//
// Kryo kryo = KryoBuilder.build(params.getMessageTypes());
//
// group = new NioEventLoopGroup();
// Bootstrap b = new Bootstrap();
// b.group(group)
// .channel(NioSocketChannel.class)
// .option(ChannelOption.TCP_NODELAY, true)
// .handler(new ChannelInitializer<SocketChannel>() {
// @Override
// public void initChannel(SocketChannel ch) throws Exception {
// connection = new NettyConnection(ch);
// connection.getCloseFuture().thenRun(NettyClient.this::close);
// if (params.getProtocol() == Protocol.WS)
// NettyUtils.configurePipelineForWebsocketClient(ch, params);
//
// NettyUtils.setupClientPipeline(ch, params.getProxyTag(), kryo, params, getConnectionStateListener());
// }
// });
//
// // Start the client.
// b.connect(params.getRemoteAddress(), params.getLocalAddress()).addListener(future -> {
// if (!future.isSuccess()) {
// connFuture.completeExceptionally(future.cause());
// close();
// }
// });
// }
//
// @Override
// public CompletableFuture<Connection> getConnection() {
// return connFuture;
// }
//
// private ConnectionStateListener getConnectionStateListener() {
// return new ConnectionStateListener() {
// @Override
// public void onConnected(ConnectionListenerContext ctx) {
// connFuture.complete(connection);
// }
// };
// }
// }
//
// Path: jagnet-examples/src/main/java/org/gillius/jagnet/examples/ExampleUtil.java
// public static String getUri(String args[]) {
// if (args.length > 1) {
// return args[0];
// } else {
// String uri = "tcp://localhost:54555";
// //alternative uri = "proxy+ws://localhost:56238/websocket?ServerExample"
// log.info("Using default URI parameter {}", uri);
// return uri;
// }
// }
// Path: jagnet-examples/src/main/java/org/gillius/jagnet/examples/ClientExample.java
import org.gillius.jagnet.*;
import org.gillius.jagnet.netty.NettyClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.gillius.jagnet.examples.ExampleUtil.getUri;
package org.gillius.jagnet.examples;
public class ClientExample {
private static final Logger log = LoggerFactory.getLogger(ClientExample.class);
public static void main(String[] args) throws Exception {
ConditionConnectionListener listener = new ConditionConnectionListener();
ConnectionParams params = new ConnectionParams() | .setByURI(getUri(args), false) |
gillius/jagnet | jagnet-examples/src/main/java/org/gillius/jagnet/examples/ClientExample.java | // Path: jagnet-core/src/main/java/org/gillius/jagnet/netty/NettyClient.java
// public class NettyClient implements Client {
// private static final Logger log = LoggerFactory.getLogger(NettyClient.class);
//
// private final ConnectionParams params;
//
// private NettyConnection connection;
// private final CompletableFuture<Connection> connFuture = new CompletableFuture<>();
// private EventLoopGroup group;
//
// public NettyClient(ConnectionParams params) {
// this.params = params.clone();
// }
//
// @Override
// public void close() {
// if (connection != null)
// connection.close();
// if (group != null)
// group.shutdownGracefully();
// connection = null;
// group = null;
// }
//
// public void start() {
// //TODO: prevent starting more than once (race conditions on close/failure)
//
// Kryo kryo = KryoBuilder.build(params.getMessageTypes());
//
// group = new NioEventLoopGroup();
// Bootstrap b = new Bootstrap();
// b.group(group)
// .channel(NioSocketChannel.class)
// .option(ChannelOption.TCP_NODELAY, true)
// .handler(new ChannelInitializer<SocketChannel>() {
// @Override
// public void initChannel(SocketChannel ch) throws Exception {
// connection = new NettyConnection(ch);
// connection.getCloseFuture().thenRun(NettyClient.this::close);
// if (params.getProtocol() == Protocol.WS)
// NettyUtils.configurePipelineForWebsocketClient(ch, params);
//
// NettyUtils.setupClientPipeline(ch, params.getProxyTag(), kryo, params, getConnectionStateListener());
// }
// });
//
// // Start the client.
// b.connect(params.getRemoteAddress(), params.getLocalAddress()).addListener(future -> {
// if (!future.isSuccess()) {
// connFuture.completeExceptionally(future.cause());
// close();
// }
// });
// }
//
// @Override
// public CompletableFuture<Connection> getConnection() {
// return connFuture;
// }
//
// private ConnectionStateListener getConnectionStateListener() {
// return new ConnectionStateListener() {
// @Override
// public void onConnected(ConnectionListenerContext ctx) {
// connFuture.complete(connection);
// }
// };
// }
// }
//
// Path: jagnet-examples/src/main/java/org/gillius/jagnet/examples/ExampleUtil.java
// public static String getUri(String args[]) {
// if (args.length > 1) {
// return args[0];
// } else {
// String uri = "tcp://localhost:54555";
// //alternative uri = "proxy+ws://localhost:56238/websocket?ServerExample"
// log.info("Using default URI parameter {}", uri);
// return uri;
// }
// }
| import org.gillius.jagnet.*;
import org.gillius.jagnet.netty.NettyClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.gillius.jagnet.examples.ExampleUtil.getUri; | package org.gillius.jagnet.examples;
public class ClientExample {
private static final Logger log = LoggerFactory.getLogger(ClientExample.class);
public static void main(String[] args) throws Exception {
ConditionConnectionListener listener = new ConditionConnectionListener();
ConnectionParams params = new ConnectionParams()
.setByURI(getUri(args), false)
.setListener(listener);
| // Path: jagnet-core/src/main/java/org/gillius/jagnet/netty/NettyClient.java
// public class NettyClient implements Client {
// private static final Logger log = LoggerFactory.getLogger(NettyClient.class);
//
// private final ConnectionParams params;
//
// private NettyConnection connection;
// private final CompletableFuture<Connection> connFuture = new CompletableFuture<>();
// private EventLoopGroup group;
//
// public NettyClient(ConnectionParams params) {
// this.params = params.clone();
// }
//
// @Override
// public void close() {
// if (connection != null)
// connection.close();
// if (group != null)
// group.shutdownGracefully();
// connection = null;
// group = null;
// }
//
// public void start() {
// //TODO: prevent starting more than once (race conditions on close/failure)
//
// Kryo kryo = KryoBuilder.build(params.getMessageTypes());
//
// group = new NioEventLoopGroup();
// Bootstrap b = new Bootstrap();
// b.group(group)
// .channel(NioSocketChannel.class)
// .option(ChannelOption.TCP_NODELAY, true)
// .handler(new ChannelInitializer<SocketChannel>() {
// @Override
// public void initChannel(SocketChannel ch) throws Exception {
// connection = new NettyConnection(ch);
// connection.getCloseFuture().thenRun(NettyClient.this::close);
// if (params.getProtocol() == Protocol.WS)
// NettyUtils.configurePipelineForWebsocketClient(ch, params);
//
// NettyUtils.setupClientPipeline(ch, params.getProxyTag(), kryo, params, getConnectionStateListener());
// }
// });
//
// // Start the client.
// b.connect(params.getRemoteAddress(), params.getLocalAddress()).addListener(future -> {
// if (!future.isSuccess()) {
// connFuture.completeExceptionally(future.cause());
// close();
// }
// });
// }
//
// @Override
// public CompletableFuture<Connection> getConnection() {
// return connFuture;
// }
//
// private ConnectionStateListener getConnectionStateListener() {
// return new ConnectionStateListener() {
// @Override
// public void onConnected(ConnectionListenerContext ctx) {
// connFuture.complete(connection);
// }
// };
// }
// }
//
// Path: jagnet-examples/src/main/java/org/gillius/jagnet/examples/ExampleUtil.java
// public static String getUri(String args[]) {
// if (args.length > 1) {
// return args[0];
// } else {
// String uri = "tcp://localhost:54555";
// //alternative uri = "proxy+ws://localhost:56238/websocket?ServerExample"
// log.info("Using default URI parameter {}", uri);
// return uri;
// }
// }
// Path: jagnet-examples/src/main/java/org/gillius/jagnet/examples/ClientExample.java
import org.gillius.jagnet.*;
import org.gillius.jagnet.netty.NettyClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.gillius.jagnet.examples.ExampleUtil.getUri;
package org.gillius.jagnet.examples;
public class ClientExample {
private static final Logger log = LoggerFactory.getLogger(ClientExample.class);
public static void main(String[] args) throws Exception {
ConditionConnectionListener listener = new ConditionConnectionListener();
ConnectionParams params = new ConnectionParams()
.setByURI(getUri(args), false)
.setListener(listener);
| Client client = new NettyClient(params); |
gillius/jagnet | jagnet-core/src/main/java/org/gillius/jagnet/netty/KryoBuilder.java | // Path: jagnet-core/src/main/java/org/gillius/jagnet/FrameworkMessages.java
// public class FrameworkMessages {
// public static List<Class<?>> getMessageTypes() {
// return asList(
// ChatMessage.class,
// TimeSyncRequest.class,
// TimeSyncResponse.class,
// ObjectCreateMessage.class,
// ObjectUpdateMessage.class
// );
// }
//
// public static void register(Kryo kryo) {
// for (Class<?> clazz : getMessageTypes()) {
// kryo.register(clazz);
// }
// }
// }
| import com.esotericsoftware.kryo.Kryo;
import org.gillius.jagnet.FrameworkMessages;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Supplier; | package org.gillius.jagnet.netty;
public class KryoBuilder implements Supplier<Kryo> {
private final List<Class<?>> messageTypes = new ArrayList<>();
public void registerMessages(Iterable<Class<?>> messageTypes) {
for (Class<?> messageType : messageTypes) {
this.messageTypes.add(messageType);
}
}
public void registerMessages(Class<?>... messageTypes) {
Collections.addAll(this.messageTypes, messageTypes);
}
@Override
public Kryo get() {
return build(messageTypes);
}
public static Kryo build(Iterable<Class<?>> messageTypes) {
Kryo ret = new Kryo();
ret.setReferences(false);
ret.setRegistrationRequired(true); | // Path: jagnet-core/src/main/java/org/gillius/jagnet/FrameworkMessages.java
// public class FrameworkMessages {
// public static List<Class<?>> getMessageTypes() {
// return asList(
// ChatMessage.class,
// TimeSyncRequest.class,
// TimeSyncResponse.class,
// ObjectCreateMessage.class,
// ObjectUpdateMessage.class
// );
// }
//
// public static void register(Kryo kryo) {
// for (Class<?> clazz : getMessageTypes()) {
// kryo.register(clazz);
// }
// }
// }
// Path: jagnet-core/src/main/java/org/gillius/jagnet/netty/KryoBuilder.java
import com.esotericsoftware.kryo.Kryo;
import org.gillius.jagnet.FrameworkMessages;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Supplier;
package org.gillius.jagnet.netty;
public class KryoBuilder implements Supplier<Kryo> {
private final List<Class<?>> messageTypes = new ArrayList<>();
public void registerMessages(Iterable<Class<?>> messageTypes) {
for (Class<?> messageType : messageTypes) {
this.messageTypes.add(messageType);
}
}
public void registerMessages(Class<?>... messageTypes) {
Collections.addAll(this.messageTypes, messageTypes);
}
@Override
public Kryo get() {
return build(messageTypes);
}
public static Kryo build(Iterable<Class<?>> messageTypes) {
Kryo ret = new Kryo();
ret.setReferences(false);
ret.setRegistrationRequired(true); | FrameworkMessages.register(ret); |
gillius/jagnet | jagnet-core/src/main/java/org/gillius/jagnet/proxy/client/ProxyClientHandler.java | // Path: jagnet-core/src/main/java/org/gillius/jagnet/proxy/ProxyConstants.java
// public class ProxyConstants {
// public static final String INTRO_HEADER = "jagnet proxy";
// public static final String INTRO_HEADER_SERVICE = "jagnet proxy service";
// public static final String SERVICE_TAKEN = "Service taken";
// public static final String NO_SUCH_SERVICE = "No such service";
// public static final String INVALID_TAG = "Invalid tag";
// public static final String WAITING_FOR_REMOTE = "Waiting for remote";
// public static final String CONNECTED = "Connected";
//
// public static final String SERVICE_PREFIX = "service:";
// public static final String DYNAMIC_PREFIX = "dynamic:";
// }
| import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.CharsetUtil;
import org.gillius.jagnet.proxy.ProxyConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.function.Consumer; | package org.gillius.jagnet.proxy.client;
public class ProxyClientHandler extends ByteToMessageDecoder {
private static final Logger log = LoggerFactory.getLogger(ProxyClientHandler.class);
private final String tag;
private final Consumer<ChannelHandlerContext> onConnected;
public ProxyClientHandler(String tag, Consumer<ChannelHandlerContext> onConnected) {
this.tag = tag;
this.onConnected = onConnected;
}
private State state = State.WAIT_ACK;
private enum State {
WAIT_ACK, WAIT_START
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
ctx.writeAndFlush( | // Path: jagnet-core/src/main/java/org/gillius/jagnet/proxy/ProxyConstants.java
// public class ProxyConstants {
// public static final String INTRO_HEADER = "jagnet proxy";
// public static final String INTRO_HEADER_SERVICE = "jagnet proxy service";
// public static final String SERVICE_TAKEN = "Service taken";
// public static final String NO_SUCH_SERVICE = "No such service";
// public static final String INVALID_TAG = "Invalid tag";
// public static final String WAITING_FOR_REMOTE = "Waiting for remote";
// public static final String CONNECTED = "Connected";
//
// public static final String SERVICE_PREFIX = "service:";
// public static final String DYNAMIC_PREFIX = "dynamic:";
// }
// Path: jagnet-core/src/main/java/org/gillius/jagnet/proxy/client/ProxyClientHandler.java
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.CharsetUtil;
import org.gillius.jagnet.proxy.ProxyConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.function.Consumer;
package org.gillius.jagnet.proxy.client;
public class ProxyClientHandler extends ByteToMessageDecoder {
private static final Logger log = LoggerFactory.getLogger(ProxyClientHandler.class);
private final String tag;
private final Consumer<ChannelHandlerContext> onConnected;
public ProxyClientHandler(String tag, Consumer<ChannelHandlerContext> onConnected) {
this.tag = tag;
this.onConnected = onConnected;
}
private State state = State.WAIT_ACK;
private enum State {
WAIT_ACK, WAIT_START
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
ctx.writeAndFlush( | Unpooled.copiedBuffer(ProxyConstants.INTRO_HEADER + "\n" + tag + "\n", CharsetUtil.UTF_8)); |
jjhesk/LoyalNativeSlider | library/src/main/java/com/hkm/slider/GalleryWidget/InfinityFilePagerAdapter.java | // Path: library/src/main/java/com/hkm/slider/TouchView/FileTouchImageView.java
// public class FileTouchImageView extends UrlTouchImageView
// {
//
// public FileTouchImageView(Context ctx)
// {
// super(ctx);
//
// }
// public FileTouchImageView(Context ctx, AttributeSet attrs)
// {
// super(ctx, attrs);
// }
//
// public void setUrl(String imagePath)
// {
// // new ImageLoadTask().execute(imagePath);
// }
// //No caching load
// /* public class ImageLoadTask extends UrlTouchImageView.ImageLoadTask
// {
// @Override
// protected Bitmap doInBackground(String... strings) {
// String path = strings[0];
// Bitmap bm = null;
// try {
// File file = new File(path);
// FileInputStream fis = new FileInputStream(file);
// InputStreamWrapper bis = new InputStreamWrapper(fis, 8192, file.length());
// bis.setProgressListener(new InputStreamWrapper.InputStreamProgressListener()
// {
// @Override
// public void onProgress(float progressValue, long bytesLoaded,
// long bytesTotal)
// {
// publishProgress((int)(progressValue * 100));
// }
// });
// bm = BitmapFactory.decodeStream(bis);
// bis.close();
// } catch (Exception e) {
// e.printStackTrace();
// }
// return bm;
// }
// }*/
// }
| import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.hkm.slider.TouchView.FileTouchImageView;
import java.util.List; | package com.hkm.slider.GalleryWidget;
/**
* Class wraps file paths to adapter, then it instantiates {@link com.hkm.slider.TouchView.FileTouchImageView} objects to paging up through them.
*/
public class InfinityFilePagerAdapter extends BasePagerAdapter {
private int TOTAL_PAGES = -1;
private int MIN_LOOPS = 1000;
// You can choose a bigger number for LOOPS, but you know, nobody will fling
// more than 1000 times just in order to test your "infinite" ViewPager :D
public int FIRST_PAGE = 1;
private ImageView.ScaleType mScaleType = null;
public InfinityFilePagerAdapter(Context context, List<String> resources) {
super(context, resources);
TOTAL_PAGES = resources.size();
FIRST_PAGE = TOTAL_PAGES * MIN_LOOPS / 2;
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object); | // Path: library/src/main/java/com/hkm/slider/TouchView/FileTouchImageView.java
// public class FileTouchImageView extends UrlTouchImageView
// {
//
// public FileTouchImageView(Context ctx)
// {
// super(ctx);
//
// }
// public FileTouchImageView(Context ctx, AttributeSet attrs)
// {
// super(ctx, attrs);
// }
//
// public void setUrl(String imagePath)
// {
// // new ImageLoadTask().execute(imagePath);
// }
// //No caching load
// /* public class ImageLoadTask extends UrlTouchImageView.ImageLoadTask
// {
// @Override
// protected Bitmap doInBackground(String... strings) {
// String path = strings[0];
// Bitmap bm = null;
// try {
// File file = new File(path);
// FileInputStream fis = new FileInputStream(file);
// InputStreamWrapper bis = new InputStreamWrapper(fis, 8192, file.length());
// bis.setProgressListener(new InputStreamWrapper.InputStreamProgressListener()
// {
// @Override
// public void onProgress(float progressValue, long bytesLoaded,
// long bytesTotal)
// {
// publishProgress((int)(progressValue * 100));
// }
// });
// bm = BitmapFactory.decodeStream(bis);
// bis.close();
// } catch (Exception e) {
// e.printStackTrace();
// }
// return bm;
// }
// }*/
// }
// Path: library/src/main/java/com/hkm/slider/GalleryWidget/InfinityFilePagerAdapter.java
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.hkm.slider.TouchView.FileTouchImageView;
import java.util.List;
package com.hkm.slider.GalleryWidget;
/**
* Class wraps file paths to adapter, then it instantiates {@link com.hkm.slider.TouchView.FileTouchImageView} objects to paging up through them.
*/
public class InfinityFilePagerAdapter extends BasePagerAdapter {
private int TOTAL_PAGES = -1;
private int MIN_LOOPS = 1000;
// You can choose a bigger number for LOOPS, but you know, nobody will fling
// more than 1000 times just in order to test your "infinite" ViewPager :D
public int FIRST_PAGE = 1;
private ImageView.ScaleType mScaleType = null;
public InfinityFilePagerAdapter(Context context, List<String> resources) {
super(context, resources);
TOTAL_PAGES = resources.size();
FIRST_PAGE = TOTAL_PAGES * MIN_LOOPS / 2;
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object); | ((GalleryViewPager) container).mCurrentView = ((FileTouchImageView) object).getImageView(); |
jjhesk/LoyalNativeSlider | library/src/main/java/com/hkm/slider/Tricks/AnimationHelper.java | // Path: library/src/main/java/com/hkm/slider/SliderAdapter.java
// public class SliderAdapter<T extends BaseSliderView> extends PagerAdapter implements BaseSliderView.ImageLoadListener {
//
// private SparseArray<Integer> measurement_height = new SparseArray<>();
// private Context mContext;
// private ArrayList<T> mImageContents;
// private int mLoadConfiguration = POSITION_NONE;
// private SliderLayout.OnViewConfigurationDetected mSetViewListener;
//
// public SliderAdapter(Context context) {
// mContext = context;
// mImageContents = new ArrayList<>();
// }
//
// public void addSlider(T slider) {
// slider.setOnImageLoadListener(this);
// mImageContents.add(slider);
// addSingleNotification();
// }
//
// public void loadSliders(List<T> slider) {
// mLoadConfiguration = POSITION_UNCHANGED;
// addSliders(slider);
// }
//
// private void addSingleNotification() {
// Iterator<T> it = mImageContents.iterator();
// int orderNumber = 0;
// while (it.hasNext()) {
// T slide = it.next();
// slide.setSlideOrderNumber(orderNumber);
// orderNumber++;
// }
// notifyDataSetChanged();
// }
//
// public void addSliders(List<T> slider) {
// Iterator<T> it = slider.iterator();
// int orderNumber = 0;
// while (it.hasNext()) {
// T slide = it.next();
// slide.setOnImageLoadListener(this);
// slide.setSlideOrderNumber(orderNumber);
// if (mlayout != null) {
// slide.setSliderContainerInternal(mlayout);
// }
// mImageContents.add(slide);
// orderNumber++;
// }
// notifyDataSetChanged();
// }
//
// public BaseSliderView getSliderView(int position) {
// if (position < 0 || position >= mImageContents.size()) {
// return null;
// } else {
// return mImageContents.get(position);
// }
// }
//
// @Override
// public int getItemPosition(Object object) {
// return mLoadConfiguration;
// }
//
// public void removeSlider(BaseSliderView slider) {
// if (mImageContents.contains(slider)) {
// mImageContents.remove(slider);
// notifyDataSetChanged();
// }
// }
//
// public void removeSliderAt(int position) {
// if (mImageContents.size() < position) {
// mImageContents.remove(position);
// notifyDataSetChanged();
// }
// }
//
// public void removeAllSliders() {
// mImageContents.clear();
// notifyDataSetChanged();
// }
//
// @Override
// public int getCount() {
// return mImageContents.size();
// }
//
// @Override
// public boolean isViewFromObject(View view, Object object) {
// return view == object;
// }
//
// @Override
// public void destroyItem(ViewGroup container, int position, Object object) {
// container.removeView((View) object);
// }
//
// private boolean enable_layout_observer = false;
//
// public void setOnInitiateViewListener(SliderLayout.OnViewConfigurationDetected object) {
// mSetViewListener = object;
// enable_layout_observer = true;
// }
//
// private SliderLayout mlayout;
//
// public void setSliderContainerInternal(SliderLayout ob) {
// mlayout = ob;
// }
//
// @Override
// public Object instantiateItem(ViewGroup container, final int position) {
// BaseSliderView b = mImageContents.get(position);
// View item = b.getView();
// // collectionConfiguration(item, position);
// container.addView(item);
// return item;
// }
//
// public void endLayoutObserver() {
// enable_layout_observer = false;
// }
//
// private void collectionConfiguration(final View layer, final int position) {
// if (mSetViewListener != null && enable_layout_observer) {
// layer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
// @Override
// public void onGlobalLayout() {
// int debug = layer.getHeight();
// Log.d("checkLayoutSlideHeight", debug + " px");
// measurement_height.append(position, layer.getHeight());
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
// layer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
// }
// if (enable_layout_observer) {
// mSetViewListener.onLayoutGenerated(measurement_height);
// }
// }
// });
// }
// }
//
// @Override
// public void onStart(BaseSliderView target) {
//
// }
//
// /**
// * When image download error, then remove.
// *
// * @param result bool
// * @param target the based slider target
// */
// @Override
// public void onEnd(boolean result, BaseSliderView target) {
// if (target.isErrorDisappear() == false || result == true) {
// return;
// }
// if (!mRemoveItemOnFailureToLoad) return;
// for (BaseSliderView slider : mImageContents) {
// if (slider.equals(target)) {
// removeSlider(target);
// break;
// }
// }
// }
//
// private boolean mRemoveItemOnFailureToLoad = true;
//
// public final void setRemoveItemOnFailureToLoad(boolean b) {
// mRemoveItemOnFailureToLoad = b;
// }
//
// }
| import android.os.Build;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.View;
import com.hkm.slider.SliderAdapter; | package com.hkm.slider.Tricks;
/**
* Created by hesk on 17/3/16.
*/
public class AnimationHelper {
public static long mTransitionAnimation = 1000;
| // Path: library/src/main/java/com/hkm/slider/SliderAdapter.java
// public class SliderAdapter<T extends BaseSliderView> extends PagerAdapter implements BaseSliderView.ImageLoadListener {
//
// private SparseArray<Integer> measurement_height = new SparseArray<>();
// private Context mContext;
// private ArrayList<T> mImageContents;
// private int mLoadConfiguration = POSITION_NONE;
// private SliderLayout.OnViewConfigurationDetected mSetViewListener;
//
// public SliderAdapter(Context context) {
// mContext = context;
// mImageContents = new ArrayList<>();
// }
//
// public void addSlider(T slider) {
// slider.setOnImageLoadListener(this);
// mImageContents.add(slider);
// addSingleNotification();
// }
//
// public void loadSliders(List<T> slider) {
// mLoadConfiguration = POSITION_UNCHANGED;
// addSliders(slider);
// }
//
// private void addSingleNotification() {
// Iterator<T> it = mImageContents.iterator();
// int orderNumber = 0;
// while (it.hasNext()) {
// T slide = it.next();
// slide.setSlideOrderNumber(orderNumber);
// orderNumber++;
// }
// notifyDataSetChanged();
// }
//
// public void addSliders(List<T> slider) {
// Iterator<T> it = slider.iterator();
// int orderNumber = 0;
// while (it.hasNext()) {
// T slide = it.next();
// slide.setOnImageLoadListener(this);
// slide.setSlideOrderNumber(orderNumber);
// if (mlayout != null) {
// slide.setSliderContainerInternal(mlayout);
// }
// mImageContents.add(slide);
// orderNumber++;
// }
// notifyDataSetChanged();
// }
//
// public BaseSliderView getSliderView(int position) {
// if (position < 0 || position >= mImageContents.size()) {
// return null;
// } else {
// return mImageContents.get(position);
// }
// }
//
// @Override
// public int getItemPosition(Object object) {
// return mLoadConfiguration;
// }
//
// public void removeSlider(BaseSliderView slider) {
// if (mImageContents.contains(slider)) {
// mImageContents.remove(slider);
// notifyDataSetChanged();
// }
// }
//
// public void removeSliderAt(int position) {
// if (mImageContents.size() < position) {
// mImageContents.remove(position);
// notifyDataSetChanged();
// }
// }
//
// public void removeAllSliders() {
// mImageContents.clear();
// notifyDataSetChanged();
// }
//
// @Override
// public int getCount() {
// return mImageContents.size();
// }
//
// @Override
// public boolean isViewFromObject(View view, Object object) {
// return view == object;
// }
//
// @Override
// public void destroyItem(ViewGroup container, int position, Object object) {
// container.removeView((View) object);
// }
//
// private boolean enable_layout_observer = false;
//
// public void setOnInitiateViewListener(SliderLayout.OnViewConfigurationDetected object) {
// mSetViewListener = object;
// enable_layout_observer = true;
// }
//
// private SliderLayout mlayout;
//
// public void setSliderContainerInternal(SliderLayout ob) {
// mlayout = ob;
// }
//
// @Override
// public Object instantiateItem(ViewGroup container, final int position) {
// BaseSliderView b = mImageContents.get(position);
// View item = b.getView();
// // collectionConfiguration(item, position);
// container.addView(item);
// return item;
// }
//
// public void endLayoutObserver() {
// enable_layout_observer = false;
// }
//
// private void collectionConfiguration(final View layer, final int position) {
// if (mSetViewListener != null && enable_layout_observer) {
// layer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
// @Override
// public void onGlobalLayout() {
// int debug = layer.getHeight();
// Log.d("checkLayoutSlideHeight", debug + " px");
// measurement_height.append(position, layer.getHeight());
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
// layer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
// }
// if (enable_layout_observer) {
// mSetViewListener.onLayoutGenerated(measurement_height);
// }
// }
// });
// }
// }
//
// @Override
// public void onStart(BaseSliderView target) {
//
// }
//
// /**
// * When image download error, then remove.
// *
// * @param result bool
// * @param target the based slider target
// */
// @Override
// public void onEnd(boolean result, BaseSliderView target) {
// if (target.isErrorDisappear() == false || result == true) {
// return;
// }
// if (!mRemoveItemOnFailureToLoad) return;
// for (BaseSliderView slider : mImageContents) {
// if (slider.equals(target)) {
// removeSlider(target);
// break;
// }
// }
// }
//
// private boolean mRemoveItemOnFailureToLoad = true;
//
// public final void setRemoveItemOnFailureToLoad(boolean b) {
// mRemoveItemOnFailureToLoad = b;
// }
//
// }
// Path: library/src/main/java/com/hkm/slider/Tricks/AnimationHelper.java
import android.os.Build;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.View;
import com.hkm.slider.SliderAdapter;
package com.hkm.slider.Tricks;
/**
* Created by hesk on 17/3/16.
*/
public class AnimationHelper {
public static long mTransitionAnimation = 1000;
| public static void notify_component(final @Nullable View mObject, final SliderAdapter mSliderAdapter, Handler postHandler, final int delayPost) { |
jjhesk/LoyalNativeSlider | library/src/main/java/com/hkm/slider/GalleryWidget/FilePagerAdapter.java | // Path: library/src/main/java/com/hkm/slider/TouchView/FileTouchImageView.java
// public class FileTouchImageView extends UrlTouchImageView
// {
//
// public FileTouchImageView(Context ctx)
// {
// super(ctx);
//
// }
// public FileTouchImageView(Context ctx, AttributeSet attrs)
// {
// super(ctx, attrs);
// }
//
// public void setUrl(String imagePath)
// {
// // new ImageLoadTask().execute(imagePath);
// }
// //No caching load
// /* public class ImageLoadTask extends UrlTouchImageView.ImageLoadTask
// {
// @Override
// protected Bitmap doInBackground(String... strings) {
// String path = strings[0];
// Bitmap bm = null;
// try {
// File file = new File(path);
// FileInputStream fis = new FileInputStream(file);
// InputStreamWrapper bis = new InputStreamWrapper(fis, 8192, file.length());
// bis.setProgressListener(new InputStreamWrapper.InputStreamProgressListener()
// {
// @Override
// public void onProgress(float progressValue, long bytesLoaded,
// long bytesTotal)
// {
// publishProgress((int)(progressValue * 100));
// }
// });
// bm = BitmapFactory.decodeStream(bis);
// bis.close();
// } catch (Exception e) {
// e.printStackTrace();
// }
// return bm;
// }
// }*/
// }
| import java.util.List;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import com.hkm.slider.TouchView.FileTouchImageView;
| package com.hkm.slider.GalleryWidget;
/**
Class wraps file paths to adapter, then it instantiates {@link com.hkm.slider.TouchView.FileTouchImageView} objects to paging up through them.
*/
public class FilePagerAdapter extends BasePagerAdapter {
public FilePagerAdapter(Context context, List<String> resources)
{
super(context, resources);
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
| // Path: library/src/main/java/com/hkm/slider/TouchView/FileTouchImageView.java
// public class FileTouchImageView extends UrlTouchImageView
// {
//
// public FileTouchImageView(Context ctx)
// {
// super(ctx);
//
// }
// public FileTouchImageView(Context ctx, AttributeSet attrs)
// {
// super(ctx, attrs);
// }
//
// public void setUrl(String imagePath)
// {
// // new ImageLoadTask().execute(imagePath);
// }
// //No caching load
// /* public class ImageLoadTask extends UrlTouchImageView.ImageLoadTask
// {
// @Override
// protected Bitmap doInBackground(String... strings) {
// String path = strings[0];
// Bitmap bm = null;
// try {
// File file = new File(path);
// FileInputStream fis = new FileInputStream(file);
// InputStreamWrapper bis = new InputStreamWrapper(fis, 8192, file.length());
// bis.setProgressListener(new InputStreamWrapper.InputStreamProgressListener()
// {
// @Override
// public void onProgress(float progressValue, long bytesLoaded,
// long bytesTotal)
// {
// publishProgress((int)(progressValue * 100));
// }
// });
// bm = BitmapFactory.decodeStream(bis);
// bis.close();
// } catch (Exception e) {
// e.printStackTrace();
// }
// return bm;
// }
// }*/
// }
// Path: library/src/main/java/com/hkm/slider/GalleryWidget/FilePagerAdapter.java
import java.util.List;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import com.hkm.slider.TouchView.FileTouchImageView;
package com.hkm.slider.GalleryWidget;
/**
Class wraps file paths to adapter, then it instantiates {@link com.hkm.slider.TouchView.FileTouchImageView} objects to paging up through them.
*/
public class FilePagerAdapter extends BasePagerAdapter {
public FilePagerAdapter(Context context, List<String> resources)
{
super(context, resources);
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
| ((GalleryViewPager)container).mCurrentView = ((FileTouchImageView)object).getImageView();
|
jjhesk/LoyalNativeSlider | library/src/main/java/com/hkm/slider/GalleryWidget/UrlPagerAdapter.java | // Path: library/src/main/java/com/hkm/slider/TouchView/UrlTouchImageView.java
// public class UrlTouchImageView extends RelativeLayout {
// protected ProgressBar mProgressBar;
// protected TouchImageView mImageView;
//
// protected Context mContext;
// private String mImageUrl;
// protected RequestBuilder<Bitmap> generator;
//
// public UrlTouchImageView(Context ctx) {
// super(ctx);
// mContext = ctx;
// init();
//
// }
//
// public UrlTouchImageView(Context ctx, AttributeSet attrs) {
// super(ctx, attrs);
// mContext = ctx;
// init();
// }
//
// public TouchImageView getImageView() {
// return mImageView;
// }
//
// @SuppressWarnings("deprecation")
// protected void init() {
// mImageView = new TouchImageView(mContext);
// LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
// mImageView.setLayoutParams(params);
// ViewTreeObserver vto = mImageView.getViewTreeObserver();
// /**
// * Callback method to be invoked when the global layout state or the visibility of views
// * within the view tree changes
// */
// glide3();
// vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
// public boolean onPreDraw() {
// mImageView.getViewTreeObserver().removeOnPreDrawListener(this);
// initLoadingRequest();
// return false;
// }
// });
// this.addView(mImageView);
// mProgressBar = new ProgressBar(mContext, null);
// params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
// params.addRule(RelativeLayout.CENTER_VERTICAL);
// params.setMargins(30, 0, 30, 0);
// mProgressBar.setLayoutParams(params);
// mProgressBar.setIndeterminate(false);
// mProgressBar.setMax(100);
// this.addView(mProgressBar);
// }
//
// private void initLoadingRequest() {
// generator.load(mImageUrl).into(mImageView);
// }
//
// private void glide3() {
// generator = Glide.with(mContext)
// .asBitmap()
// .apply(new RequestOptions()
// .diskCacheStrategy(DiskCacheStrategy.ALL)
// .skipMemoryCache(true)
// )
// .listener(new RequestListener<Bitmap>() {
// @Override
// public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
// mImageView.setVisibility(GONE);
// return false;
// }
//
// @Override
// public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
// mProgressBar.animate().alpha(0).withEndAction(new Runnable() {
// @Override
// public void run() {
// mProgressBar.setVisibility(GONE);
// }
// });
// }
// return false;
// }
// });
// }
//
//
// public void setUrl(String imageUrl) {
// mImageUrl = imageUrl;
// }
//
// public void setScaleType(ScaleType scaleType) {
// mImageView.setScaleType(scaleType);
// }
//
// }
| import java.util.List;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import com.hkm.slider.TouchView.UrlTouchImageView;
| package com.hkm.slider.GalleryWidget;
/**
* Class wraps URLs to adapter, then it instantiates {@link com.hkm.slider.TouchView.FileTouchImageView} objects to paging up through them.
*/
public class UrlPagerAdapter extends BasePagerAdapter {
public UrlPagerAdapter(Context context, List<String> resources) {
super(context, resources);
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
| // Path: library/src/main/java/com/hkm/slider/TouchView/UrlTouchImageView.java
// public class UrlTouchImageView extends RelativeLayout {
// protected ProgressBar mProgressBar;
// protected TouchImageView mImageView;
//
// protected Context mContext;
// private String mImageUrl;
// protected RequestBuilder<Bitmap> generator;
//
// public UrlTouchImageView(Context ctx) {
// super(ctx);
// mContext = ctx;
// init();
//
// }
//
// public UrlTouchImageView(Context ctx, AttributeSet attrs) {
// super(ctx, attrs);
// mContext = ctx;
// init();
// }
//
// public TouchImageView getImageView() {
// return mImageView;
// }
//
// @SuppressWarnings("deprecation")
// protected void init() {
// mImageView = new TouchImageView(mContext);
// LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
// mImageView.setLayoutParams(params);
// ViewTreeObserver vto = mImageView.getViewTreeObserver();
// /**
// * Callback method to be invoked when the global layout state or the visibility of views
// * within the view tree changes
// */
// glide3();
// vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
// public boolean onPreDraw() {
// mImageView.getViewTreeObserver().removeOnPreDrawListener(this);
// initLoadingRequest();
// return false;
// }
// });
// this.addView(mImageView);
// mProgressBar = new ProgressBar(mContext, null);
// params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
// params.addRule(RelativeLayout.CENTER_VERTICAL);
// params.setMargins(30, 0, 30, 0);
// mProgressBar.setLayoutParams(params);
// mProgressBar.setIndeterminate(false);
// mProgressBar.setMax(100);
// this.addView(mProgressBar);
// }
//
// private void initLoadingRequest() {
// generator.load(mImageUrl).into(mImageView);
// }
//
// private void glide3() {
// generator = Glide.with(mContext)
// .asBitmap()
// .apply(new RequestOptions()
// .diskCacheStrategy(DiskCacheStrategy.ALL)
// .skipMemoryCache(true)
// )
// .listener(new RequestListener<Bitmap>() {
// @Override
// public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
// mImageView.setVisibility(GONE);
// return false;
// }
//
// @Override
// public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
// mProgressBar.animate().alpha(0).withEndAction(new Runnable() {
// @Override
// public void run() {
// mProgressBar.setVisibility(GONE);
// }
// });
// }
// return false;
// }
// });
// }
//
//
// public void setUrl(String imageUrl) {
// mImageUrl = imageUrl;
// }
//
// public void setScaleType(ScaleType scaleType) {
// mImageView.setScaleType(scaleType);
// }
//
// }
// Path: library/src/main/java/com/hkm/slider/GalleryWidget/UrlPagerAdapter.java
import java.util.List;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import com.hkm.slider.TouchView.UrlTouchImageView;
package com.hkm.slider.GalleryWidget;
/**
* Class wraps URLs to adapter, then it instantiates {@link com.hkm.slider.TouchView.FileTouchImageView} objects to paging up through them.
*/
public class UrlPagerAdapter extends BasePagerAdapter {
public UrlPagerAdapter(Context context, List<String> resources) {
super(context, resources);
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
| ((GalleryViewPager) container).mCurrentView = ((UrlTouchImageView) object).getImageView();
|
jjhesk/LoyalNativeSlider | library/src/main/java/com/hkm/slider/GalleryWidget/InfinityUrlAdapter.java | // Path: library/src/main/java/com/hkm/slider/TouchView/UrlTouchImageView.java
// public class UrlTouchImageView extends RelativeLayout {
// protected ProgressBar mProgressBar;
// protected TouchImageView mImageView;
//
// protected Context mContext;
// private String mImageUrl;
// protected RequestBuilder<Bitmap> generator;
//
// public UrlTouchImageView(Context ctx) {
// super(ctx);
// mContext = ctx;
// init();
//
// }
//
// public UrlTouchImageView(Context ctx, AttributeSet attrs) {
// super(ctx, attrs);
// mContext = ctx;
// init();
// }
//
// public TouchImageView getImageView() {
// return mImageView;
// }
//
// @SuppressWarnings("deprecation")
// protected void init() {
// mImageView = new TouchImageView(mContext);
// LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
// mImageView.setLayoutParams(params);
// ViewTreeObserver vto = mImageView.getViewTreeObserver();
// /**
// * Callback method to be invoked when the global layout state or the visibility of views
// * within the view tree changes
// */
// glide3();
// vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
// public boolean onPreDraw() {
// mImageView.getViewTreeObserver().removeOnPreDrawListener(this);
// initLoadingRequest();
// return false;
// }
// });
// this.addView(mImageView);
// mProgressBar = new ProgressBar(mContext, null);
// params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
// params.addRule(RelativeLayout.CENTER_VERTICAL);
// params.setMargins(30, 0, 30, 0);
// mProgressBar.setLayoutParams(params);
// mProgressBar.setIndeterminate(false);
// mProgressBar.setMax(100);
// this.addView(mProgressBar);
// }
//
// private void initLoadingRequest() {
// generator.load(mImageUrl).into(mImageView);
// }
//
// private void glide3() {
// generator = Glide.with(mContext)
// .asBitmap()
// .apply(new RequestOptions()
// .diskCacheStrategy(DiskCacheStrategy.ALL)
// .skipMemoryCache(true)
// )
// .listener(new RequestListener<Bitmap>() {
// @Override
// public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
// mImageView.setVisibility(GONE);
// return false;
// }
//
// @Override
// public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
// mProgressBar.animate().alpha(0).withEndAction(new Runnable() {
// @Override
// public void run() {
// mProgressBar.setVisibility(GONE);
// }
// });
// }
// return false;
// }
// });
// }
//
//
// public void setUrl(String imageUrl) {
// mImageUrl = imageUrl;
// }
//
// public void setScaleType(ScaleType scaleType) {
// mImageView.setScaleType(scaleType);
// }
//
// }
| import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.hkm.slider.TouchView.UrlTouchImageView;
import java.util.List; | package com.hkm.slider.GalleryWidget;
/**
* Created by fabio on 28/05/14.
*/
public class InfinityUrlAdapter extends BasePagerAdapter {
private int TOTAL_PAGES = -1;
private int MIN_LOOPS = 1000;
// You can choose a bigger number for LOOPS, but you know, nobody will fling
// more than 1000 times just in order to test your "infinite" ViewPager :D
public int FIRST_PAGE = 1;
private ImageView.ScaleType mScaleType = null;
public InfinityUrlAdapter(Context context, List<String> resources) {
super(context, resources);
TOTAL_PAGES = resources.size();
FIRST_PAGE = TOTAL_PAGES * MIN_LOOPS / 2;
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, FIRST_PAGE/*position*/, object); | // Path: library/src/main/java/com/hkm/slider/TouchView/UrlTouchImageView.java
// public class UrlTouchImageView extends RelativeLayout {
// protected ProgressBar mProgressBar;
// protected TouchImageView mImageView;
//
// protected Context mContext;
// private String mImageUrl;
// protected RequestBuilder<Bitmap> generator;
//
// public UrlTouchImageView(Context ctx) {
// super(ctx);
// mContext = ctx;
// init();
//
// }
//
// public UrlTouchImageView(Context ctx, AttributeSet attrs) {
// super(ctx, attrs);
// mContext = ctx;
// init();
// }
//
// public TouchImageView getImageView() {
// return mImageView;
// }
//
// @SuppressWarnings("deprecation")
// protected void init() {
// mImageView = new TouchImageView(mContext);
// LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
// mImageView.setLayoutParams(params);
// ViewTreeObserver vto = mImageView.getViewTreeObserver();
// /**
// * Callback method to be invoked when the global layout state or the visibility of views
// * within the view tree changes
// */
// glide3();
// vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
// public boolean onPreDraw() {
// mImageView.getViewTreeObserver().removeOnPreDrawListener(this);
// initLoadingRequest();
// return false;
// }
// });
// this.addView(mImageView);
// mProgressBar = new ProgressBar(mContext, null);
// params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
// params.addRule(RelativeLayout.CENTER_VERTICAL);
// params.setMargins(30, 0, 30, 0);
// mProgressBar.setLayoutParams(params);
// mProgressBar.setIndeterminate(false);
// mProgressBar.setMax(100);
// this.addView(mProgressBar);
// }
//
// private void initLoadingRequest() {
// generator.load(mImageUrl).into(mImageView);
// }
//
// private void glide3() {
// generator = Glide.with(mContext)
// .asBitmap()
// .apply(new RequestOptions()
// .diskCacheStrategy(DiskCacheStrategy.ALL)
// .skipMemoryCache(true)
// )
// .listener(new RequestListener<Bitmap>() {
// @Override
// public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
// mImageView.setVisibility(GONE);
// return false;
// }
//
// @Override
// public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
// mProgressBar.animate().alpha(0).withEndAction(new Runnable() {
// @Override
// public void run() {
// mProgressBar.setVisibility(GONE);
// }
// });
// }
// return false;
// }
// });
// }
//
//
// public void setUrl(String imageUrl) {
// mImageUrl = imageUrl;
// }
//
// public void setScaleType(ScaleType scaleType) {
// mImageView.setScaleType(scaleType);
// }
//
// }
// Path: library/src/main/java/com/hkm/slider/GalleryWidget/InfinityUrlAdapter.java
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.hkm.slider.TouchView.UrlTouchImageView;
import java.util.List;
package com.hkm.slider.GalleryWidget;
/**
* Created by fabio on 28/05/14.
*/
public class InfinityUrlAdapter extends BasePagerAdapter {
private int TOTAL_PAGES = -1;
private int MIN_LOOPS = 1000;
// You can choose a bigger number for LOOPS, but you know, nobody will fling
// more than 1000 times just in order to test your "infinite" ViewPager :D
public int FIRST_PAGE = 1;
private ImageView.ScaleType mScaleType = null;
public InfinityUrlAdapter(Context context, List<String> resources) {
super(context, resources);
TOTAL_PAGES = resources.size();
FIRST_PAGE = TOTAL_PAGES * MIN_LOOPS / 2;
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, FIRST_PAGE/*position*/, object); | ((GalleryViewPager) container).mCurrentView = ((UrlTouchImageView) object).getImageView(); |
GoogleCloudPlatform/endpoints-codelab-android | todoTxtTouch/src/main/java/com/todotxt/todotxttouch/remote/RemoteFolderImpl.java | // Path: todoTxtTouch/src/main/java/com/todotxt/todotxttouch/util/Strings.java
// public final class Strings {
// public static final String SINGLE_SPACE = " ";
//
// /**
// * Inserts a given string into another padding it with spaces. Is aware if
// * the insertion point has a space on either end and does not add extra
// * spaces.
// *
// * @param s the string to insert into
// * @param insertAt the position to insert the string
// * @param stringToInsert the string to insert
// * @return the result of inserting the stringToInsert into the passed in
// * string
// * @throws IndexOutOfBoundsException if the insertAt is negative, or
// * insertAt is larger than the length of s String object
// */
// public static String insertPadded(String s, int insertAt, String stringToInsert) {
// if (Strings.isEmptyOrNull(stringToInsert)) {
// return s;
// }
//
// if (insertAt < 0) {
// throw new IndexOutOfBoundsException("Invalid insertAt of ["
// + insertAt + "] for string [" + s + "]");
// }
//
// StringBuilder newText = new StringBuilder();
//
// if (insertAt > 0) {
// newText.append(s.substring(0, insertAt));
//
// if (newText.lastIndexOf(SINGLE_SPACE) != newText.length() - 1) {
// newText.append(SINGLE_SPACE);
// }
//
// newText.append(stringToInsert);
// String postItem = s.substring(insertAt);
//
// if (postItem.indexOf(SINGLE_SPACE) != 0) {
// newText.append(SINGLE_SPACE);
// }
//
// newText.append(postItem);
// } else {
// newText.append(stringToInsert);
//
// if (s.indexOf(SINGLE_SPACE) != 0) {
// newText.append(SINGLE_SPACE);
// }
//
// newText.append(s);
// }
//
// return newText.toString();
// }
//
// /**
// * Inserts a given string into another padding it with spaces. Is aware if
// * the insertion point has a space on either end and does not add extra
// * spaces. If the string-to-insert is already present (and not part of
// * another word) we return the original string unchanged.
// *
// * @param s the string to insert into
// * @param insertAt the position to insert the string
// * @param stringToInsert the string to insert
// * @return the result of inserting the stringToInsert into the passed in
// * string
// * @throws IndexOutOfBoundsException if the insertAt is negative, or
// * insertAt is larger than the length of s String object
// */
// public static String insertPaddedIfNeeded(String s, int insertAt, String stringToInsert) {
// if (Strings.isEmptyOrNull(stringToInsert)) {
// return s;
// }
//
// boolean found = false;
// int startPos = 0;
//
// while ((startPos < s.length()) && (!found)) {
// int pos = s.indexOf(stringToInsert, startPos);
//
// if (pos < 0)
// break;
//
// startPos = pos + 1;
// int before = pos - 1;
// int after = pos + stringToInsert.length();
//
// if (((pos == 0) || (Character.isWhitespace(s.charAt(before)))) &&
// ((after >= s.length()) || (Character.isWhitespace(s.charAt(after)))))
// found = true;
// }
//
// if (found) {
// StringBuilder newText = new StringBuilder(s);
//
// if (newText.lastIndexOf(SINGLE_SPACE) != newText.length() - 1) {
// newText.append(SINGLE_SPACE);
// }
//
// return (newText.toString());
// } else
// return (Strings.insertPadded(s, insertAt, stringToInsert));
// }
//
// /**
// * Checks the passed in string to see if it is null or an empty string
// *
// * @param s the string to check
// * @return true if null or ""
// */
// public static boolean isEmptyOrNull(String s) {
// return s == null || s.length() == 0;
// }
//
// /**
// * Checks the passed in string to see if it is null, empty, or blank; where
// * 'blank' is defined as consisting entirely of whitespace.
// *
// * @param s the string to check
// * @return true if null or "" or all whitespace
// */
// public static boolean isBlank(String s) {
// return isEmptyOrNull(s) || s.trim().length() == 0;
// }
// }
| import com.todotxt.todotxttouch.util.Path;
import com.todotxt.todotxttouch.util.Strings; |
public RemoteFolderImpl(String path, String name, String parentPath, String parentName) {
mPath = path;
mName = name;
mParentPath = parentPath;
mParentName = parentName;
}
@Override
public String getName() {
return mName;
}
@Override
public String getParentName() {
return mParentName;
}
@Override
public String getPath() {
return mPath;
}
@Override
public String getParentPath() {
return mParentPath;
}
@Override
public boolean hasParent() { | // Path: todoTxtTouch/src/main/java/com/todotxt/todotxttouch/util/Strings.java
// public final class Strings {
// public static final String SINGLE_SPACE = " ";
//
// /**
// * Inserts a given string into another padding it with spaces. Is aware if
// * the insertion point has a space on either end and does not add extra
// * spaces.
// *
// * @param s the string to insert into
// * @param insertAt the position to insert the string
// * @param stringToInsert the string to insert
// * @return the result of inserting the stringToInsert into the passed in
// * string
// * @throws IndexOutOfBoundsException if the insertAt is negative, or
// * insertAt is larger than the length of s String object
// */
// public static String insertPadded(String s, int insertAt, String stringToInsert) {
// if (Strings.isEmptyOrNull(stringToInsert)) {
// return s;
// }
//
// if (insertAt < 0) {
// throw new IndexOutOfBoundsException("Invalid insertAt of ["
// + insertAt + "] for string [" + s + "]");
// }
//
// StringBuilder newText = new StringBuilder();
//
// if (insertAt > 0) {
// newText.append(s.substring(0, insertAt));
//
// if (newText.lastIndexOf(SINGLE_SPACE) != newText.length() - 1) {
// newText.append(SINGLE_SPACE);
// }
//
// newText.append(stringToInsert);
// String postItem = s.substring(insertAt);
//
// if (postItem.indexOf(SINGLE_SPACE) != 0) {
// newText.append(SINGLE_SPACE);
// }
//
// newText.append(postItem);
// } else {
// newText.append(stringToInsert);
//
// if (s.indexOf(SINGLE_SPACE) != 0) {
// newText.append(SINGLE_SPACE);
// }
//
// newText.append(s);
// }
//
// return newText.toString();
// }
//
// /**
// * Inserts a given string into another padding it with spaces. Is aware if
// * the insertion point has a space on either end and does not add extra
// * spaces. If the string-to-insert is already present (and not part of
// * another word) we return the original string unchanged.
// *
// * @param s the string to insert into
// * @param insertAt the position to insert the string
// * @param stringToInsert the string to insert
// * @return the result of inserting the stringToInsert into the passed in
// * string
// * @throws IndexOutOfBoundsException if the insertAt is negative, or
// * insertAt is larger than the length of s String object
// */
// public static String insertPaddedIfNeeded(String s, int insertAt, String stringToInsert) {
// if (Strings.isEmptyOrNull(stringToInsert)) {
// return s;
// }
//
// boolean found = false;
// int startPos = 0;
//
// while ((startPos < s.length()) && (!found)) {
// int pos = s.indexOf(stringToInsert, startPos);
//
// if (pos < 0)
// break;
//
// startPos = pos + 1;
// int before = pos - 1;
// int after = pos + stringToInsert.length();
//
// if (((pos == 0) || (Character.isWhitespace(s.charAt(before)))) &&
// ((after >= s.length()) || (Character.isWhitespace(s.charAt(after)))))
// found = true;
// }
//
// if (found) {
// StringBuilder newText = new StringBuilder(s);
//
// if (newText.lastIndexOf(SINGLE_SPACE) != newText.length() - 1) {
// newText.append(SINGLE_SPACE);
// }
//
// return (newText.toString());
// } else
// return (Strings.insertPadded(s, insertAt, stringToInsert));
// }
//
// /**
// * Checks the passed in string to see if it is null or an empty string
// *
// * @param s the string to check
// * @return true if null or ""
// */
// public static boolean isEmptyOrNull(String s) {
// return s == null || s.length() == 0;
// }
//
// /**
// * Checks the passed in string to see if it is null, empty, or blank; where
// * 'blank' is defined as consisting entirely of whitespace.
// *
// * @param s the string to check
// * @return true if null or "" or all whitespace
// */
// public static boolean isBlank(String s) {
// return isEmptyOrNull(s) || s.trim().length() == 0;
// }
// }
// Path: todoTxtTouch/src/main/java/com/todotxt/todotxttouch/remote/RemoteFolderImpl.java
import com.todotxt.todotxttouch.util.Path;
import com.todotxt.todotxttouch.util.Strings;
public RemoteFolderImpl(String path, String name, String parentPath, String parentName) {
mPath = path;
mName = name;
mParentPath = parentPath;
mParentName = parentName;
}
@Override
public String getName() {
return mName;
}
@Override
public String getParentName() {
return mParentName;
}
@Override
public String getPath() {
return mPath;
}
@Override
public String getParentPath() {
return mParentPath;
}
@Override
public boolean hasParent() { | return !Strings.isBlank(getParentPath()); |
GoogleCloudPlatform/endpoints-codelab-android | todoTxtTouch/src/main/java/com/todotxt/todotxttouch/TodoLocationPreference.java | // Path: todoTxtTouch/src/main/java/com/todotxt/todotxttouch/remote/RemoteFolder.java
// public interface RemoteFolder {
// /**
// * @return The folder's name without any path information.
// */
// String getName();
//
// /**
// * @return The full path of the folder.
// */
// String getPath();
//
// /**
// * @return The name of the parent without any path information.
// */
// String getParentName();
//
// /**
// * @return The full path of the folder's parent.
// */
// String getParentPath();
//
// /**
// * @return True if this is not a root folder.
// */
// boolean hasParent();
// }
//
// Path: todoTxtTouch/src/main/java/com/todotxt/todotxttouch/remote/RemoteFolderImpl.java
// public class RemoteFolderImpl implements RemoteFolder {
// protected String mPath;
// protected String mName;
// protected String mParentPath;
// protected String mParentName;
//
// public RemoteFolderImpl(String path) {
// mPath = path;
// mName = Path.fileName(path);
// mParentPath = Path.parentPath(path);
// mParentName = Path.fileName(mParentPath);
// }
//
// public RemoteFolderImpl(String path, String name, String parentPath, String parentName) {
// mPath = path;
// mName = name;
// mParentPath = parentPath;
// mParentName = parentName;
// }
//
// @Override
// public String getName() {
// return mName;
// }
//
// @Override
// public String getParentName() {
// return mParentName;
// }
//
// @Override
// public String getPath() {
// return mPath;
// }
//
// @Override
// public String getParentPath() {
// return mParentPath;
// }
//
// @Override
// public boolean hasParent() {
// return !Strings.isBlank(getParentPath());
// }
//
// @Override
// public String toString() {
// return getName();
// }
//
// @Override
// public boolean equals(Object o) {
// if (o instanceof RemoteFolder) {
// return getPath().equalsIgnoreCase(((RemoteFolder) o).getPath());
// }
//
// return false;
// }
//
// @Override
// public int hashCode() {
// return getPath().hashCode();
// }
//
// }
//
// Path: todoTxtTouch/src/main/java/com/todotxt/todotxttouch/util/Tree.java
// public class Tree<E> {
// private Tree<E> parent = null;
// private List<Tree<E>> children = null;
// private E data;
//
// public Tree(E data) {
// this.data = data;
// }
//
// public Tree(Tree<E> parent, E data) {
// this.parent = parent;
// this.data = data;
// }
//
// public Tree<E> addChild(Tree<E> child) {
// if (children == null) {
// children = new ArrayList<Tree<E>>();
// }
//
// children.add(child);
// child.parent = this;
//
// return child;
// }
//
// public Tree<E> addChild(E data) {
// Tree<E> child = new Tree<E>(data);
//
// return addChild(child);
// }
//
// public E getData() {
// return data;
// }
//
// public Tree<E> getParent() {
// return parent;
// }
//
// public boolean isLoaded() {
// return children != null;
// }
//
// public void setLoaded() {
// if (children == null) {
// children = new ArrayList<Tree<E>>();
// }
// }
//
// public List<Tree<E>> getChildren() {
// return children;
// }
//
// public boolean contains(Tree<E> child) {
// if (children == null) {
// return false;
// }
//
// return children.contains(child);
// }
//
// public boolean contains(E data) {
// if (children == null) {
// return false;
// }
//
// for (Tree<E> child : children) {
// if (child.getData().equals(data)) {
// return true;
// }
// }
//
// return false;
// }
//
// public Tree<E> getChild(int position) {
// return children.get(position);
// }
// }
| import java.io.File;
import java.util.Collections;
import java.util.List;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Parcel;
import android.os.Parcelable;
import android.preference.DialogPreference;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.todotxt.todotxttouch.remote.RemoteFolder;
import com.todotxt.todotxttouch.remote.RemoteFolderImpl;
import com.todotxt.todotxttouch.util.Tree; |
// initialize the view
initFolderTree();
selectFolder(mCurrentSelection);
mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == 0 && mCurrentSelection.getData().hasParent()) {
// go back up to previous directory
upToParent();
} else if (position == mAdapter.getCount() - 1) {
// signal that AddNew was clicked
mDisplayMode = DisplayMode.ADD_NEW;
mEditText.setVisibility(View.VISIBLE);
mListFrame.setVisibility(View.GONE);
mEditText.requestFocus();
} else {
// drill down to this directory
int index = mCurrentSelection.getData().hasParent() ? position - 1
: position;
selectFolder(mCurrentSelection.getChild(index));
}
}
});
}
private void initFolderTree() {
if (mRootFolder == null) { | // Path: todoTxtTouch/src/main/java/com/todotxt/todotxttouch/remote/RemoteFolder.java
// public interface RemoteFolder {
// /**
// * @return The folder's name without any path information.
// */
// String getName();
//
// /**
// * @return The full path of the folder.
// */
// String getPath();
//
// /**
// * @return The name of the parent without any path information.
// */
// String getParentName();
//
// /**
// * @return The full path of the folder's parent.
// */
// String getParentPath();
//
// /**
// * @return True if this is not a root folder.
// */
// boolean hasParent();
// }
//
// Path: todoTxtTouch/src/main/java/com/todotxt/todotxttouch/remote/RemoteFolderImpl.java
// public class RemoteFolderImpl implements RemoteFolder {
// protected String mPath;
// protected String mName;
// protected String mParentPath;
// protected String mParentName;
//
// public RemoteFolderImpl(String path) {
// mPath = path;
// mName = Path.fileName(path);
// mParentPath = Path.parentPath(path);
// mParentName = Path.fileName(mParentPath);
// }
//
// public RemoteFolderImpl(String path, String name, String parentPath, String parentName) {
// mPath = path;
// mName = name;
// mParentPath = parentPath;
// mParentName = parentName;
// }
//
// @Override
// public String getName() {
// return mName;
// }
//
// @Override
// public String getParentName() {
// return mParentName;
// }
//
// @Override
// public String getPath() {
// return mPath;
// }
//
// @Override
// public String getParentPath() {
// return mParentPath;
// }
//
// @Override
// public boolean hasParent() {
// return !Strings.isBlank(getParentPath());
// }
//
// @Override
// public String toString() {
// return getName();
// }
//
// @Override
// public boolean equals(Object o) {
// if (o instanceof RemoteFolder) {
// return getPath().equalsIgnoreCase(((RemoteFolder) o).getPath());
// }
//
// return false;
// }
//
// @Override
// public int hashCode() {
// return getPath().hashCode();
// }
//
// }
//
// Path: todoTxtTouch/src/main/java/com/todotxt/todotxttouch/util/Tree.java
// public class Tree<E> {
// private Tree<E> parent = null;
// private List<Tree<E>> children = null;
// private E data;
//
// public Tree(E data) {
// this.data = data;
// }
//
// public Tree(Tree<E> parent, E data) {
// this.parent = parent;
// this.data = data;
// }
//
// public Tree<E> addChild(Tree<E> child) {
// if (children == null) {
// children = new ArrayList<Tree<E>>();
// }
//
// children.add(child);
// child.parent = this;
//
// return child;
// }
//
// public Tree<E> addChild(E data) {
// Tree<E> child = new Tree<E>(data);
//
// return addChild(child);
// }
//
// public E getData() {
// return data;
// }
//
// public Tree<E> getParent() {
// return parent;
// }
//
// public boolean isLoaded() {
// return children != null;
// }
//
// public void setLoaded() {
// if (children == null) {
// children = new ArrayList<Tree<E>>();
// }
// }
//
// public List<Tree<E>> getChildren() {
// return children;
// }
//
// public boolean contains(Tree<E> child) {
// if (children == null) {
// return false;
// }
//
// return children.contains(child);
// }
//
// public boolean contains(E data) {
// if (children == null) {
// return false;
// }
//
// for (Tree<E> child : children) {
// if (child.getData().equals(data)) {
// return true;
// }
// }
//
// return false;
// }
//
// public Tree<E> getChild(int position) {
// return children.get(position);
// }
// }
// Path: todoTxtTouch/src/main/java/com/todotxt/todotxttouch/TodoLocationPreference.java
import java.io.File;
import java.util.Collections;
import java.util.List;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Parcel;
import android.os.Parcelable;
import android.preference.DialogPreference;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.todotxt.todotxttouch.remote.RemoteFolder;
import com.todotxt.todotxttouch.remote.RemoteFolderImpl;
import com.todotxt.todotxttouch.util.Tree;
// initialize the view
initFolderTree();
selectFolder(mCurrentSelection);
mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == 0 && mCurrentSelection.getData().hasParent()) {
// go back up to previous directory
upToParent();
} else if (position == mAdapter.getCount() - 1) {
// signal that AddNew was clicked
mDisplayMode = DisplayMode.ADD_NEW;
mEditText.setVisibility(View.VISIBLE);
mListFrame.setVisibility(View.GONE);
mEditText.requestFocus();
} else {
// drill down to this directory
int index = mCurrentSelection.getData().hasParent() ? position - 1
: position;
selectFolder(mCurrentSelection.getChild(index));
}
}
});
}
private void initFolderTree() {
if (mRootFolder == null) { | mRootFolder = mCurrentSelection = new Tree<RemoteFolder>(new RemoteFolderImpl(null, null, null, null)); |
GoogleCloudPlatform/endpoints-codelab-android | todoTxtTouch/src/main/java/com/todotxt/todotxttouch/task/LinkParser.java | // Path: todoTxtTouch/src/main/java/com/todotxt/todotxttouch/TodoException.java
// public class TodoException extends RuntimeException {
// private static final long serialVersionUID = 2160630991596963352L;
//
// public TodoException(String msg) {
// super(msg);
// }
//
// public TodoException(String msg, Throwable t) {
// super(msg, t);
// }
// }
| import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.todotxt.todotxttouch.TodoException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; | /**
* This file is part of Todo.txt for Android, an app for managing your todo.txt file (http://todotxt.com).
*
* Copyright (c) 2009-2013 Todo.txt for Android contributors (http://todotxt.com)
*
* LICENSE:
*
* Todo.txt for Android 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.
*
* Todo.txt for Android 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 Todo.txt for Android. If not, see
* <http://www.gnu.org/licenses/>.
*
* Todo.txt for Android's source code is available at https://github.com/ginatrapani/todo.txt-android
*
* @author Todo.txt for Android contributors <todotxt@yahoogroups.com>
* @license http://www.gnu.org/licenses/gpl.html
* @copyright 2009-2013 Todo.txt for Android contributors (http://todotxt.com)
*/
package com.todotxt.todotxttouch.task;
public class LinkParser {
private static final Pattern LINK_PATTERN = Pattern
.compile("(http|https)://[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&:/~\\+#]*[\\w\\-\\@?^=%&/~\\+#])?");
private static final LinkParser INSTANCE = new LinkParser();
private LinkParser() {
}
public static LinkParser getInstance() {
return INSTANCE;
}
public List<URL> parse(String inputText) {
if (inputText == null) {
return Collections.emptyList();
}
Matcher m = LINK_PATTERN.matcher(inputText);
List<URL> links = new ArrayList<URL>();
while (m.find()) {
URL link;
try {
link = new URL(m.group());
links.add(link);
} catch (MalformedURLException e) { | // Path: todoTxtTouch/src/main/java/com/todotxt/todotxttouch/TodoException.java
// public class TodoException extends RuntimeException {
// private static final long serialVersionUID = 2160630991596963352L;
//
// public TodoException(String msg) {
// super(msg);
// }
//
// public TodoException(String msg, Throwable t) {
// super(msg, t);
// }
// }
// Path: todoTxtTouch/src/main/java/com/todotxt/todotxttouch/task/LinkParser.java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.todotxt.todotxttouch.TodoException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* This file is part of Todo.txt for Android, an app for managing your todo.txt file (http://todotxt.com).
*
* Copyright (c) 2009-2013 Todo.txt for Android contributors (http://todotxt.com)
*
* LICENSE:
*
* Todo.txt for Android 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.
*
* Todo.txt for Android 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 Todo.txt for Android. If not, see
* <http://www.gnu.org/licenses/>.
*
* Todo.txt for Android's source code is available at https://github.com/ginatrapani/todo.txt-android
*
* @author Todo.txt for Android contributors <todotxt@yahoogroups.com>
* @license http://www.gnu.org/licenses/gpl.html
* @copyright 2009-2013 Todo.txt for Android contributors (http://todotxt.com)
*/
package com.todotxt.todotxttouch.task;
public class LinkParser {
private static final Pattern LINK_PATTERN = Pattern
.compile("(http|https)://[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&:/~\\+#]*[\\w\\-\\@?^=%&/~\\+#])?");
private static final LinkParser INSTANCE = new LinkParser();
private LinkParser() {
}
public static LinkParser getInstance() {
return INSTANCE;
}
public List<URL> parse(String inputText) {
if (inputText == null) {
return Collections.emptyList();
}
Matcher m = LINK_PATTERN.matcher(inputText);
List<URL> links = new ArrayList<URL>();
while (m.find()) {
URL link;
try {
link = new URL(m.group());
links.add(link);
} catch (MalformedURLException e) { | throw new TodoException("Malformed URL matched the regex", e); |
GoogleCloudPlatform/endpoints-codelab-android | todoTxtTouch/src/main/java/com/todotxt/todotxttouch/util/Util.java | // Path: todoTxtTouch/src/main/java/com/todotxt/todotxttouch/TodoException.java
// public class TodoException extends RuntimeException {
// private static final long serialVersionUID = 2160630991596963352L;
//
// public TodoException(String msg) {
// super(msg);
// }
//
// public TodoException(String msg, Throwable t) {
// super(msg, t);
// }
// }
| import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Environment;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import com.todotxt.todotxttouch.R;
import com.todotxt.todotxttouch.TodoException; |
public static boolean isDeviceWritable() {
String sdState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(sdState)) {
return true;
} else {
return false;
}
}
public static boolean isDeviceReadable() {
String sdState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(sdState)
|| Environment.MEDIA_MOUNTED_READ_ONLY.equals(sdState)) {
return true;
} else {
return false;
}
}
public interface InputDialogListener {
void onClick(String input);
}
public interface LoginDialogListener {
void onClick(String username, String password);
}
| // Path: todoTxtTouch/src/main/java/com/todotxt/todotxttouch/TodoException.java
// public class TodoException extends RuntimeException {
// private static final long serialVersionUID = 2160630991596963352L;
//
// public TodoException(String msg) {
// super(msg);
// }
//
// public TodoException(String msg, Throwable t) {
// super(msg, t);
// }
// }
// Path: todoTxtTouch/src/main/java/com/todotxt/todotxttouch/util/Util.java
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Environment;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import com.todotxt.todotxttouch.R;
import com.todotxt.todotxttouch.TodoException;
public static boolean isDeviceWritable() {
String sdState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(sdState)) {
return true;
} else {
return false;
}
}
public static boolean isDeviceReadable() {
String sdState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(sdState)
|| Environment.MEDIA_MOUNTED_READ_ONLY.equals(sdState)) {
return true;
} else {
return false;
}
}
public interface InputDialogListener {
void onClick(String input);
}
public interface LoginDialogListener {
void onClick(String username, String password);
}
| public static void createParentDirectory(File dest) throws TodoException { |
mmiklavc/scalable-ocr | nifi/src/test/java/ocr/nifi/preprocessing/PreprocessingTest.java | // Path: common/src/main/java/ocr/common/Util.java
// public class Util {
// public enum Locations {
// CONVERT(new String[]{
// "/usr/local/bin/convert",
// "/opt/local/bin/convert"
// }, t -> findFile(t, "convert tool")),
// TESSDATA(new String[]{
// "/opt/local/share/tessdata/",
// "/usr/local/Cellar/tesseract/3.04.01_1/share/tessdata/"
// }, t -> findFile(t, "tessdata")),
// JNA(new String[]{
// "/opt/local/lib"
// }, t -> findDir(t, "jna library"));
//
// private final String[] locs;
// private final Function<String[], Optional<File>> searchHandler;
//
// Locations(String[] locs, Function<String[], Optional<File>> searchHandler) {
// this.locs = locs;
// this.searchHandler = searchHandler;
// }
//
// public Optional<File> find() {
// return searchHandler.apply(locs);
// }
//
// public Optional<File> find(Optional<?> path) {
// if (path.isPresent()) {
// File f = new File(path.get().toString());
// if (f.exists()) {
// return Optional.of(f);
// }
// }
// return find();
// }
// }
//
// public static Optional<File> findFile(String[] locs, String item) {
// return findFile(locs, item, false);
// }
//
// public static Optional<File> findDir(String[] locs, String item) {
// return findFile(locs, item, true);
// }
//
// public static Optional<File> findFile(String[] locs, String item, boolean checkIsDir) {
// for (String loc : locs) {
// File binPath = new File(loc);
// if (binPath.exists()) {
// if (checkIsDir) {
// if (binPath.isDirectory()) {
// return Optional.of(binPath);
// }
// continue;
// }
// return Optional.of(binPath);
// }
// }
// return Optional.empty();
// }
//
// }
//
// Path: preprocessing/src/main/java/ocr/preprocessing/conversion/ImageUtils.java
// public enum ImageUtils {
// INSTANCE;
//
// public BufferedImage readImage(byte[] inputImage) throws IOException {
// return ImageIO.read(new ByteArrayInputStream(inputImage));
// }
// public BufferedImage readImage(File inputFile) throws IOException {
// return ImageIO.read(inputFile);
// }
//
// public int getHeight(BufferedImage img) {
// return img.getHeight();
// }
//
// public int getWidth(BufferedImage img) {
// return img.getWidth();
// }
//
// public double getAspectRatio(BufferedImage img) {
//
// return (1.0*getHeight(img))/getWidth(img);
// }
//
// }
| import ocr.common.Util;
import ocr.preprocessing.conversion.ImageUtils;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.Assert;
import org.junit.Test;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.util.List; | package ocr.nifi.preprocessing;
public class PreprocessingTest {
@Test
public void test() throws Exception {
// Generate a test runner to mock a processor in a flow
TestRunner runner = TestRunners.newTestRunner(new PreprocessingProcessor());
File inputFile = new File("../preprocessing/src/test/resources/images/brscan_original_r90.jpg");
// Add properties | // Path: common/src/main/java/ocr/common/Util.java
// public class Util {
// public enum Locations {
// CONVERT(new String[]{
// "/usr/local/bin/convert",
// "/opt/local/bin/convert"
// }, t -> findFile(t, "convert tool")),
// TESSDATA(new String[]{
// "/opt/local/share/tessdata/",
// "/usr/local/Cellar/tesseract/3.04.01_1/share/tessdata/"
// }, t -> findFile(t, "tessdata")),
// JNA(new String[]{
// "/opt/local/lib"
// }, t -> findDir(t, "jna library"));
//
// private final String[] locs;
// private final Function<String[], Optional<File>> searchHandler;
//
// Locations(String[] locs, Function<String[], Optional<File>> searchHandler) {
// this.locs = locs;
// this.searchHandler = searchHandler;
// }
//
// public Optional<File> find() {
// return searchHandler.apply(locs);
// }
//
// public Optional<File> find(Optional<?> path) {
// if (path.isPresent()) {
// File f = new File(path.get().toString());
// if (f.exists()) {
// return Optional.of(f);
// }
// }
// return find();
// }
// }
//
// public static Optional<File> findFile(String[] locs, String item) {
// return findFile(locs, item, false);
// }
//
// public static Optional<File> findDir(String[] locs, String item) {
// return findFile(locs, item, true);
// }
//
// public static Optional<File> findFile(String[] locs, String item, boolean checkIsDir) {
// for (String loc : locs) {
// File binPath = new File(loc);
// if (binPath.exists()) {
// if (checkIsDir) {
// if (binPath.isDirectory()) {
// return Optional.of(binPath);
// }
// continue;
// }
// return Optional.of(binPath);
// }
// }
// return Optional.empty();
// }
//
// }
//
// Path: preprocessing/src/main/java/ocr/preprocessing/conversion/ImageUtils.java
// public enum ImageUtils {
// INSTANCE;
//
// public BufferedImage readImage(byte[] inputImage) throws IOException {
// return ImageIO.read(new ByteArrayInputStream(inputImage));
// }
// public BufferedImage readImage(File inputFile) throws IOException {
// return ImageIO.read(inputFile);
// }
//
// public int getHeight(BufferedImage img) {
// return img.getHeight();
// }
//
// public int getWidth(BufferedImage img) {
// return img.getWidth();
// }
//
// public double getAspectRatio(BufferedImage img) {
//
// return (1.0*getHeight(img))/getWidth(img);
// }
//
// }
// Path: nifi/src/test/java/ocr/nifi/preprocessing/PreprocessingTest.java
import ocr.common.Util;
import ocr.preprocessing.conversion.ImageUtils;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.Assert;
import org.junit.Test;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
package ocr.nifi.preprocessing;
public class PreprocessingTest {
@Test
public void test() throws Exception {
// Generate a test runner to mock a processor in a flow
TestRunner runner = TestRunners.newTestRunner(new PreprocessingProcessor());
File inputFile = new File("../preprocessing/src/test/resources/images/brscan_original_r90.jpg");
// Add properties | runner.setProperty(PreprocessingProcessor.CONVERT_PATH, Util.Locations.CONVERT.find().get().getAbsolutePath()); |
mmiklavc/scalable-ocr | nifi/src/test/java/ocr/nifi/preprocessing/PreprocessingTest.java | // Path: common/src/main/java/ocr/common/Util.java
// public class Util {
// public enum Locations {
// CONVERT(new String[]{
// "/usr/local/bin/convert",
// "/opt/local/bin/convert"
// }, t -> findFile(t, "convert tool")),
// TESSDATA(new String[]{
// "/opt/local/share/tessdata/",
// "/usr/local/Cellar/tesseract/3.04.01_1/share/tessdata/"
// }, t -> findFile(t, "tessdata")),
// JNA(new String[]{
// "/opt/local/lib"
// }, t -> findDir(t, "jna library"));
//
// private final String[] locs;
// private final Function<String[], Optional<File>> searchHandler;
//
// Locations(String[] locs, Function<String[], Optional<File>> searchHandler) {
// this.locs = locs;
// this.searchHandler = searchHandler;
// }
//
// public Optional<File> find() {
// return searchHandler.apply(locs);
// }
//
// public Optional<File> find(Optional<?> path) {
// if (path.isPresent()) {
// File f = new File(path.get().toString());
// if (f.exists()) {
// return Optional.of(f);
// }
// }
// return find();
// }
// }
//
// public static Optional<File> findFile(String[] locs, String item) {
// return findFile(locs, item, false);
// }
//
// public static Optional<File> findDir(String[] locs, String item) {
// return findFile(locs, item, true);
// }
//
// public static Optional<File> findFile(String[] locs, String item, boolean checkIsDir) {
// for (String loc : locs) {
// File binPath = new File(loc);
// if (binPath.exists()) {
// if (checkIsDir) {
// if (binPath.isDirectory()) {
// return Optional.of(binPath);
// }
// continue;
// }
// return Optional.of(binPath);
// }
// }
// return Optional.empty();
// }
//
// }
//
// Path: preprocessing/src/main/java/ocr/preprocessing/conversion/ImageUtils.java
// public enum ImageUtils {
// INSTANCE;
//
// public BufferedImage readImage(byte[] inputImage) throws IOException {
// return ImageIO.read(new ByteArrayInputStream(inputImage));
// }
// public BufferedImage readImage(File inputFile) throws IOException {
// return ImageIO.read(inputFile);
// }
//
// public int getHeight(BufferedImage img) {
// return img.getHeight();
// }
//
// public int getWidth(BufferedImage img) {
// return img.getWidth();
// }
//
// public double getAspectRatio(BufferedImage img) {
//
// return (1.0*getHeight(img))/getWidth(img);
// }
//
// }
| import ocr.common.Util;
import ocr.preprocessing.conversion.ImageUtils;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.Assert;
import org.junit.Test;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.util.List; | package ocr.nifi.preprocessing;
public class PreprocessingTest {
@Test
public void test() throws Exception {
// Generate a test runner to mock a processor in a flow
TestRunner runner = TestRunners.newTestRunner(new PreprocessingProcessor());
File inputFile = new File("../preprocessing/src/test/resources/images/brscan_original_r90.jpg");
// Add properties
runner.setProperty(PreprocessingProcessor.CONVERT_PATH, Util.Locations.CONVERT.find().get().getAbsolutePath());
runner.setProperty(PreprocessingProcessor.TEMP_DIR, "/tmp");
runner.setProperty(PreprocessingProcessor.DEFINITIONS, "-g -e normalize -f 15 -o 10 -u -s 2 -T -p 20");
// Add the content to the runner
runner.enqueue(new FileInputStream(inputFile));
// Run the enqueued content, it also takes an int = number of contents queued
runner.run(1);
// All results were processed with out failure
runner.assertQueueEmpty();
// If you need to read or do additional tests on results you can access the content
List<MockFlowFile> results = runner.getFlowFilesForRelationship(PreprocessingProcessor.SUCCESS);
Assert.assertEquals(1, results.size());
byte[] value = runner.getContentAsByteArray(results.get(0)); | // Path: common/src/main/java/ocr/common/Util.java
// public class Util {
// public enum Locations {
// CONVERT(new String[]{
// "/usr/local/bin/convert",
// "/opt/local/bin/convert"
// }, t -> findFile(t, "convert tool")),
// TESSDATA(new String[]{
// "/opt/local/share/tessdata/",
// "/usr/local/Cellar/tesseract/3.04.01_1/share/tessdata/"
// }, t -> findFile(t, "tessdata")),
// JNA(new String[]{
// "/opt/local/lib"
// }, t -> findDir(t, "jna library"));
//
// private final String[] locs;
// private final Function<String[], Optional<File>> searchHandler;
//
// Locations(String[] locs, Function<String[], Optional<File>> searchHandler) {
// this.locs = locs;
// this.searchHandler = searchHandler;
// }
//
// public Optional<File> find() {
// return searchHandler.apply(locs);
// }
//
// public Optional<File> find(Optional<?> path) {
// if (path.isPresent()) {
// File f = new File(path.get().toString());
// if (f.exists()) {
// return Optional.of(f);
// }
// }
// return find();
// }
// }
//
// public static Optional<File> findFile(String[] locs, String item) {
// return findFile(locs, item, false);
// }
//
// public static Optional<File> findDir(String[] locs, String item) {
// return findFile(locs, item, true);
// }
//
// public static Optional<File> findFile(String[] locs, String item, boolean checkIsDir) {
// for (String loc : locs) {
// File binPath = new File(loc);
// if (binPath.exists()) {
// if (checkIsDir) {
// if (binPath.isDirectory()) {
// return Optional.of(binPath);
// }
// continue;
// }
// return Optional.of(binPath);
// }
// }
// return Optional.empty();
// }
//
// }
//
// Path: preprocessing/src/main/java/ocr/preprocessing/conversion/ImageUtils.java
// public enum ImageUtils {
// INSTANCE;
//
// public BufferedImage readImage(byte[] inputImage) throws IOException {
// return ImageIO.read(new ByteArrayInputStream(inputImage));
// }
// public BufferedImage readImage(File inputFile) throws IOException {
// return ImageIO.read(inputFile);
// }
//
// public int getHeight(BufferedImage img) {
// return img.getHeight();
// }
//
// public int getWidth(BufferedImage img) {
// return img.getWidth();
// }
//
// public double getAspectRatio(BufferedImage img) {
//
// return (1.0*getHeight(img))/getWidth(img);
// }
//
// }
// Path: nifi/src/test/java/ocr/nifi/preprocessing/PreprocessingTest.java
import ocr.common.Util;
import ocr.preprocessing.conversion.ImageUtils;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.Assert;
import org.junit.Test;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
package ocr.nifi.preprocessing;
public class PreprocessingTest {
@Test
public void test() throws Exception {
// Generate a test runner to mock a processor in a flow
TestRunner runner = TestRunners.newTestRunner(new PreprocessingProcessor());
File inputFile = new File("../preprocessing/src/test/resources/images/brscan_original_r90.jpg");
// Add properties
runner.setProperty(PreprocessingProcessor.CONVERT_PATH, Util.Locations.CONVERT.find().get().getAbsolutePath());
runner.setProperty(PreprocessingProcessor.TEMP_DIR, "/tmp");
runner.setProperty(PreprocessingProcessor.DEFINITIONS, "-g -e normalize -f 15 -o 10 -u -s 2 -T -p 20");
// Add the content to the runner
runner.enqueue(new FileInputStream(inputFile));
// Run the enqueued content, it also takes an int = number of contents queued
runner.run(1);
// All results were processed with out failure
runner.assertQueueEmpty();
// If you need to read or do additional tests on results you can access the content
List<MockFlowFile> results = runner.getFlowFilesForRelationship(PreprocessingProcessor.SUCCESS);
Assert.assertEquals(1, results.size());
byte[] value = runner.getContentAsByteArray(results.get(0)); | BufferedImage bi = ImageUtils.INSTANCE.readImage(value); |
mmiklavc/scalable-ocr | preprocessing/src/main/java/ocr/preprocessing/conversion/TextCleaner.java | // Path: common/src/main/java/ocr/common/Util.java
// public class Util {
// public enum Locations {
// CONVERT(new String[]{
// "/usr/local/bin/convert",
// "/opt/local/bin/convert"
// }, t -> findFile(t, "convert tool")),
// TESSDATA(new String[]{
// "/opt/local/share/tessdata/",
// "/usr/local/Cellar/tesseract/3.04.01_1/share/tessdata/"
// }, t -> findFile(t, "tessdata")),
// JNA(new String[]{
// "/opt/local/lib"
// }, t -> findDir(t, "jna library"));
//
// private final String[] locs;
// private final Function<String[], Optional<File>> searchHandler;
//
// Locations(String[] locs, Function<String[], Optional<File>> searchHandler) {
// this.locs = locs;
// this.searchHandler = searchHandler;
// }
//
// public Optional<File> find() {
// return searchHandler.apply(locs);
// }
//
// public Optional<File> find(Optional<?> path) {
// if (path.isPresent()) {
// File f = new File(path.get().toString());
// if (f.exists()) {
// return Optional.of(f);
// }
// }
// return find();
// }
// }
//
// public static Optional<File> findFile(String[] locs, String item) {
// return findFile(locs, item, false);
// }
//
// public static Optional<File> findDir(String[] locs, String item) {
// return findFile(locs, item, true);
// }
//
// public static Optional<File> findFile(String[] locs, String item, boolean checkIsDir) {
// for (String loc : locs) {
// File binPath = new File(loc);
// if (binPath.exists()) {
// if (checkIsDir) {
// if (binPath.isDirectory()) {
// return Optional.of(binPath);
// }
// continue;
// }
// return Optional.of(binPath);
// }
// }
// return Optional.empty();
// }
//
// }
| import com.google.common.base.Joiner;
import ocr.common.Util;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.io.IOUtils;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Optional; | ret.add(options.get(CleaningOptions.ADAPTIVE_BLUR));
ret.add(options.get(CleaningOptions.TRIM));
ret.add(options.get(CleaningOptions.PAD));
ret.add(outputFile);
return CLIUtils.translateCommandline(Joiner.on(" ").join(ret));
}
public byte[] convert(InputStream is) throws IOException, CommandFailedException {
String suffix = ".tiff";
File file = getTmpOutputFile(suffix);
try {
Files.copy(is, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
return convert(file.getAbsolutePath(), suffix);
}
finally {
if(file != null && file.exists()) {
file.delete();
}
}
}
public byte[] convert(String inputFile, String suffix) throws IOException, CommandFailedException {
File outFile = null;
try {
outFile = getTmpOutputFile(suffix);
if(!new File(inputFile).exists()) {
throw new FileNotFoundException("Unable to find input file: " + inputFile);
}
ArrayList<String> completeCommand = new ArrayList<>();
{ | // Path: common/src/main/java/ocr/common/Util.java
// public class Util {
// public enum Locations {
// CONVERT(new String[]{
// "/usr/local/bin/convert",
// "/opt/local/bin/convert"
// }, t -> findFile(t, "convert tool")),
// TESSDATA(new String[]{
// "/opt/local/share/tessdata/",
// "/usr/local/Cellar/tesseract/3.04.01_1/share/tessdata/"
// }, t -> findFile(t, "tessdata")),
// JNA(new String[]{
// "/opt/local/lib"
// }, t -> findDir(t, "jna library"));
//
// private final String[] locs;
// private final Function<String[], Optional<File>> searchHandler;
//
// Locations(String[] locs, Function<String[], Optional<File>> searchHandler) {
// this.locs = locs;
// this.searchHandler = searchHandler;
// }
//
// public Optional<File> find() {
// return searchHandler.apply(locs);
// }
//
// public Optional<File> find(Optional<?> path) {
// if (path.isPresent()) {
// File f = new File(path.get().toString());
// if (f.exists()) {
// return Optional.of(f);
// }
// }
// return find();
// }
// }
//
// public static Optional<File> findFile(String[] locs, String item) {
// return findFile(locs, item, false);
// }
//
// public static Optional<File> findDir(String[] locs, String item) {
// return findFile(locs, item, true);
// }
//
// public static Optional<File> findFile(String[] locs, String item, boolean checkIsDir) {
// for (String loc : locs) {
// File binPath = new File(loc);
// if (binPath.exists()) {
// if (checkIsDir) {
// if (binPath.isDirectory()) {
// return Optional.of(binPath);
// }
// continue;
// }
// return Optional.of(binPath);
// }
// }
// return Optional.empty();
// }
//
// }
// Path: preprocessing/src/main/java/ocr/preprocessing/conversion/TextCleaner.java
import com.google.common.base.Joiner;
import ocr.common.Util;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.io.IOUtils;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Optional;
ret.add(options.get(CleaningOptions.ADAPTIVE_BLUR));
ret.add(options.get(CleaningOptions.TRIM));
ret.add(options.get(CleaningOptions.PAD));
ret.add(outputFile);
return CLIUtils.translateCommandline(Joiner.on(" ").join(ret));
}
public byte[] convert(InputStream is) throws IOException, CommandFailedException {
String suffix = ".tiff";
File file = getTmpOutputFile(suffix);
try {
Files.copy(is, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
return convert(file.getAbsolutePath(), suffix);
}
finally {
if(file != null && file.exists()) {
file.delete();
}
}
}
public byte[] convert(String inputFile, String suffix) throws IOException, CommandFailedException {
File outFile = null;
try {
outFile = getTmpOutputFile(suffix);
if(!new File(inputFile).exists()) {
throw new FileNotFoundException("Unable to find input file: " + inputFile);
}
ArrayList<String> completeCommand = new ArrayList<>();
{ | String command = Util.Locations.CONVERT.find(convertPath).orElseThrow(() -> new IllegalStateException("Bad baby.")).getAbsolutePath(); |
mmiklavc/scalable-ocr | nifi/src/main/java/ocr/nifi/validation/JsonValidator.java | // Path: nifi/src/main/java/ocr/nifi/util/JSONUtils.java
// public enum JSONUtils {
// INSTANCE;
// private static ThreadLocal<ObjectMapper> _mapper = new ThreadLocal<ObjectMapper>() {
// /**
// * Returns the current thread's "initial value" for this
// * thread-local variable. This method will be invoked the first
// * time a thread accesses the variable with the {@link #get}
// * method, unless the thread previously invoked the {@link #set}
// * method, in which case the {@code initialValue} method will not
// * be invoked for the thread. Normally, this method is invoked at
// * most once per thread, but it may be invoked again in case of
// * subsequent invocations of {@link #remove} followed by {@link #get}.
// * <p>
// * <p>This implementation simply returns {@code null}; if the
// * programmer desires thread-local variables to have an initial
// * value other than {@code null}, {@code ThreadLocal} must be
// * subclassed, and this method overridden. Typically, an
// * anonymous inner class will be used.
// *
// * @return the initial value for this thread-local
// */
// @Override
// protected ObjectMapper initialValue() {
// return new ObjectMapper();
// }
// };
//
// public <T> T load(InputStream is, TypeReference<T> ref) throws IOException {
// return _mapper.get().readValue(is, ref);
// }
//
// public <T> T load(String is, TypeReference<T> ref) throws IOException {
// return _mapper.get().readValue(is, ref);
// }
//
// public <T> T load(File f, TypeReference<T> ref) throws IOException {
// try (InputStream is = new BufferedInputStream(new FileInputStream(f))) {
// return _mapper.get().readValue(is, ref);
// }
// }
//
// public <T> T load(InputStream is, Class<T> clazz) throws IOException {
// return _mapper.get().readValue(is, clazz);
// }
//
// public <T> T load(File f, Class<T> clazz) throws IOException {
// try (InputStream is = new BufferedInputStream(new FileInputStream(f))) {
// return _mapper.get().readValue(is, clazz);
// }
// }
//
// public <T> T load(String is, Class<T> clazz) throws IOException {
// return _mapper.get().readValue(is, clazz);
// }
//
// public String toJSON(Object o, boolean pretty) throws JsonProcessingException {
// if (pretty) {
// return _mapper.get().writerWithDefaultPrettyPrinter().writeValueAsString(o);
// } else {
// return _mapper.get().writeValueAsString(o);
// }
// }
//
// public byte[] toJSON(Object config) throws JsonProcessingException {
// return _mapper.get().writeValueAsBytes(config);
// }
// }
| import com.fasterxml.jackson.core.type.TypeReference;
import ocr.nifi.util.JSONUtils;
import org.apache.nifi.components.ValidationContext;
import org.apache.nifi.components.ValidationResult;
import org.apache.nifi.components.Validator;
import java.io.IOException;
import java.util.Map;
import static com.sun.corba.se.spi.activation.IIOP_CLEAR_TEXT.value; | package ocr.nifi.validation;
public class JsonValidator implements Validator {
@Override
public ValidationResult validate(String subject, String input, ValidationContext context) {
try { | // Path: nifi/src/main/java/ocr/nifi/util/JSONUtils.java
// public enum JSONUtils {
// INSTANCE;
// private static ThreadLocal<ObjectMapper> _mapper = new ThreadLocal<ObjectMapper>() {
// /**
// * Returns the current thread's "initial value" for this
// * thread-local variable. This method will be invoked the first
// * time a thread accesses the variable with the {@link #get}
// * method, unless the thread previously invoked the {@link #set}
// * method, in which case the {@code initialValue} method will not
// * be invoked for the thread. Normally, this method is invoked at
// * most once per thread, but it may be invoked again in case of
// * subsequent invocations of {@link #remove} followed by {@link #get}.
// * <p>
// * <p>This implementation simply returns {@code null}; if the
// * programmer desires thread-local variables to have an initial
// * value other than {@code null}, {@code ThreadLocal} must be
// * subclassed, and this method overridden. Typically, an
// * anonymous inner class will be used.
// *
// * @return the initial value for this thread-local
// */
// @Override
// protected ObjectMapper initialValue() {
// return new ObjectMapper();
// }
// };
//
// public <T> T load(InputStream is, TypeReference<T> ref) throws IOException {
// return _mapper.get().readValue(is, ref);
// }
//
// public <T> T load(String is, TypeReference<T> ref) throws IOException {
// return _mapper.get().readValue(is, ref);
// }
//
// public <T> T load(File f, TypeReference<T> ref) throws IOException {
// try (InputStream is = new BufferedInputStream(new FileInputStream(f))) {
// return _mapper.get().readValue(is, ref);
// }
// }
//
// public <T> T load(InputStream is, Class<T> clazz) throws IOException {
// return _mapper.get().readValue(is, clazz);
// }
//
// public <T> T load(File f, Class<T> clazz) throws IOException {
// try (InputStream is = new BufferedInputStream(new FileInputStream(f))) {
// return _mapper.get().readValue(is, clazz);
// }
// }
//
// public <T> T load(String is, Class<T> clazz) throws IOException {
// return _mapper.get().readValue(is, clazz);
// }
//
// public String toJSON(Object o, boolean pretty) throws JsonProcessingException {
// if (pretty) {
// return _mapper.get().writerWithDefaultPrettyPrinter().writeValueAsString(o);
// } else {
// return _mapper.get().writeValueAsString(o);
// }
// }
//
// public byte[] toJSON(Object config) throws JsonProcessingException {
// return _mapper.get().writeValueAsBytes(config);
// }
// }
// Path: nifi/src/main/java/ocr/nifi/validation/JsonValidator.java
import com.fasterxml.jackson.core.type.TypeReference;
import ocr.nifi.util.JSONUtils;
import org.apache.nifi.components.ValidationContext;
import org.apache.nifi.components.ValidationResult;
import org.apache.nifi.components.Validator;
import java.io.IOException;
import java.util.Map;
import static com.sun.corba.se.spi.activation.IIOP_CLEAR_TEXT.value;
package ocr.nifi.validation;
public class JsonValidator implements Validator {
@Override
public ValidationResult validate(String subject, String input, ValidationContext context) {
try { | JSONUtils.INSTANCE.load(input, new TypeReference<Map<String, String>>() { |
mmiklavc/scalable-ocr | nifi/src/test/java/ocr/nifi/extraction/ExtractionProcessorTest.java | // Path: common/src/main/java/ocr/common/Util.java
// public class Util {
// public enum Locations {
// CONVERT(new String[]{
// "/usr/local/bin/convert",
// "/opt/local/bin/convert"
// }, t -> findFile(t, "convert tool")),
// TESSDATA(new String[]{
// "/opt/local/share/tessdata/",
// "/usr/local/Cellar/tesseract/3.04.01_1/share/tessdata/"
// }, t -> findFile(t, "tessdata")),
// JNA(new String[]{
// "/opt/local/lib"
// }, t -> findDir(t, "jna library"));
//
// private final String[] locs;
// private final Function<String[], Optional<File>> searchHandler;
//
// Locations(String[] locs, Function<String[], Optional<File>> searchHandler) {
// this.locs = locs;
// this.searchHandler = searchHandler;
// }
//
// public Optional<File> find() {
// return searchHandler.apply(locs);
// }
//
// public Optional<File> find(Optional<?> path) {
// if (path.isPresent()) {
// File f = new File(path.get().toString());
// if (f.exists()) {
// return Optional.of(f);
// }
// }
// return find();
// }
// }
//
// public static Optional<File> findFile(String[] locs, String item) {
// return findFile(locs, item, false);
// }
//
// public static Optional<File> findDir(String[] locs, String item) {
// return findFile(locs, item, true);
// }
//
// public static Optional<File> findFile(String[] locs, String item, boolean checkIsDir) {
// for (String loc : locs) {
// File binPath = new File(loc);
// if (binPath.exists()) {
// if (checkIsDir) {
// if (binPath.isDirectory()) {
// return Optional.of(binPath);
// }
// continue;
// }
// return Optional.of(binPath);
// }
// }
// return Optional.empty();
// }
//
// }
| import ocr.common.Util;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List; | package ocr.nifi.extraction;
public class ExtractionProcessorTest {
@Test
public void test() throws FileNotFoundException {
// Generate a test runner to mock a processor in a flow
TestRunner runner = TestRunners.newTestRunner(new ExtractionProcessor());
File inputFile = new File("../extraction/src/test/resources/pdf-test.tiff");
// Add properties | // Path: common/src/main/java/ocr/common/Util.java
// public class Util {
// public enum Locations {
// CONVERT(new String[]{
// "/usr/local/bin/convert",
// "/opt/local/bin/convert"
// }, t -> findFile(t, "convert tool")),
// TESSDATA(new String[]{
// "/opt/local/share/tessdata/",
// "/usr/local/Cellar/tesseract/3.04.01_1/share/tessdata/"
// }, t -> findFile(t, "tessdata")),
// JNA(new String[]{
// "/opt/local/lib"
// }, t -> findDir(t, "jna library"));
//
// private final String[] locs;
// private final Function<String[], Optional<File>> searchHandler;
//
// Locations(String[] locs, Function<String[], Optional<File>> searchHandler) {
// this.locs = locs;
// this.searchHandler = searchHandler;
// }
//
// public Optional<File> find() {
// return searchHandler.apply(locs);
// }
//
// public Optional<File> find(Optional<?> path) {
// if (path.isPresent()) {
// File f = new File(path.get().toString());
// if (f.exists()) {
// return Optional.of(f);
// }
// }
// return find();
// }
// }
//
// public static Optional<File> findFile(String[] locs, String item) {
// return findFile(locs, item, false);
// }
//
// public static Optional<File> findDir(String[] locs, String item) {
// return findFile(locs, item, true);
// }
//
// public static Optional<File> findFile(String[] locs, String item, boolean checkIsDir) {
// for (String loc : locs) {
// File binPath = new File(loc);
// if (binPath.exists()) {
// if (checkIsDir) {
// if (binPath.isDirectory()) {
// return Optional.of(binPath);
// }
// continue;
// }
// return Optional.of(binPath);
// }
// }
// return Optional.empty();
// }
//
// }
// Path: nifi/src/test/java/ocr/nifi/extraction/ExtractionProcessorTest.java
import ocr.common.Util;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;
package ocr.nifi.extraction;
public class ExtractionProcessorTest {
@Test
public void test() throws FileNotFoundException {
// Generate a test runner to mock a processor in a flow
TestRunner runner = TestRunners.newTestRunner(new ExtractionProcessor());
File inputFile = new File("../extraction/src/test/resources/pdf-test.tiff");
// Add properties | runner.setProperty(ExtractionProcessor.JNI_PATH, Util.Locations.JNA.find().get().getAbsolutePath()); |
mmiklavc/scalable-ocr | extraction/src/test/java/ocr/extraction/tesseract/TesseractUtilTest.java | // Path: common/src/main/java/ocr/common/Util.java
// public class Util {
// public enum Locations {
// CONVERT(new String[]{
// "/usr/local/bin/convert",
// "/opt/local/bin/convert"
// }, t -> findFile(t, "convert tool")),
// TESSDATA(new String[]{
// "/opt/local/share/tessdata/",
// "/usr/local/Cellar/tesseract/3.04.01_1/share/tessdata/"
// }, t -> findFile(t, "tessdata")),
// JNA(new String[]{
// "/opt/local/lib"
// }, t -> findDir(t, "jna library"));
//
// private final String[] locs;
// private final Function<String[], Optional<File>> searchHandler;
//
// Locations(String[] locs, Function<String[], Optional<File>> searchHandler) {
// this.locs = locs;
// this.searchHandler = searchHandler;
// }
//
// public Optional<File> find() {
// return searchHandler.apply(locs);
// }
//
// public Optional<File> find(Optional<?> path) {
// if (path.isPresent()) {
// File f = new File(path.get().toString());
// if (f.exists()) {
// return Optional.of(f);
// }
// }
// return find();
// }
// }
//
// public static Optional<File> findFile(String[] locs, String item) {
// return findFile(locs, item, false);
// }
//
// public static Optional<File> findDir(String[] locs, String item) {
// return findFile(locs, item, true);
// }
//
// public static Optional<File> findFile(String[] locs, String item, boolean checkIsDir) {
// for (String loc : locs) {
// File binPath = new File(loc);
// if (binPath.exists()) {
// if (checkIsDir) {
// if (binPath.isDirectory()) {
// return Optional.of(binPath);
// }
// continue;
// }
// return Optional.of(binPath);
// }
// }
// return Optional.empty();
// }
//
// }
| import ocr.common.Util;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.nio.file.Files;
import java.util.HashMap; | package ocr.extraction.tesseract;
public class TesseractUtilTest {
@Test
public void testTesseractHappyPath() throws Exception { | // Path: common/src/main/java/ocr/common/Util.java
// public class Util {
// public enum Locations {
// CONVERT(new String[]{
// "/usr/local/bin/convert",
// "/opt/local/bin/convert"
// }, t -> findFile(t, "convert tool")),
// TESSDATA(new String[]{
// "/opt/local/share/tessdata/",
// "/usr/local/Cellar/tesseract/3.04.01_1/share/tessdata/"
// }, t -> findFile(t, "tessdata")),
// JNA(new String[]{
// "/opt/local/lib"
// }, t -> findDir(t, "jna library"));
//
// private final String[] locs;
// private final Function<String[], Optional<File>> searchHandler;
//
// Locations(String[] locs, Function<String[], Optional<File>> searchHandler) {
// this.locs = locs;
// this.searchHandler = searchHandler;
// }
//
// public Optional<File> find() {
// return searchHandler.apply(locs);
// }
//
// public Optional<File> find(Optional<?> path) {
// if (path.isPresent()) {
// File f = new File(path.get().toString());
// if (f.exists()) {
// return Optional.of(f);
// }
// }
// return find();
// }
// }
//
// public static Optional<File> findFile(String[] locs, String item) {
// return findFile(locs, item, false);
// }
//
// public static Optional<File> findDir(String[] locs, String item) {
// return findFile(locs, item, true);
// }
//
// public static Optional<File> findFile(String[] locs, String item, boolean checkIsDir) {
// for (String loc : locs) {
// File binPath = new File(loc);
// if (binPath.exists()) {
// if (checkIsDir) {
// if (binPath.isDirectory()) {
// return Optional.of(binPath);
// }
// continue;
// }
// return Optional.of(binPath);
// }
// }
// return Optional.empty();
// }
//
// }
// Path: extraction/src/test/java/ocr/extraction/tesseract/TesseractUtilTest.java
import ocr.common.Util;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.nio.file.Files;
import java.util.HashMap;
package ocr.extraction.tesseract;
public class TesseractUtilTest {
@Test
public void testTesseractHappyPath() throws Exception { | System.getProperties().setProperty("jna.library.path", Util.Locations.JNA.find().get().getAbsolutePath()); |
mmiklavc/scalable-ocr | nifi/src/test/java/ocr/nifi/conversion/ConversionProcessorTest.java | // Path: preprocessing/src/main/java/ocr/preprocessing/conversion/ImageUtils.java
// public enum ImageUtils {
// INSTANCE;
//
// public BufferedImage readImage(byte[] inputImage) throws IOException {
// return ImageIO.read(new ByteArrayInputStream(inputImage));
// }
// public BufferedImage readImage(File inputFile) throws IOException {
// return ImageIO.read(inputFile);
// }
//
// public int getHeight(BufferedImage img) {
// return img.getHeight();
// }
//
// public int getWidth(BufferedImage img) {
// return img.getWidth();
// }
//
// public double getAspectRatio(BufferedImage img) {
//
// return (1.0*getHeight(img))/getWidth(img);
// }
//
// }
| import ocr.preprocessing.conversion.ImageUtils;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.ghost4j.document.PDFDocument;
import org.junit.Assert;
import org.junit.Test;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; | package ocr.nifi.conversion;
public class ConversionProcessorTest {
@Test
public void test() throws Exception {
// Generate a test runner to mock a processor in a flow
TestRunner runner = TestRunners.newTestRunner(new ConversionProcessor());
File inputFile = new File("../conversion/src/test/resources/text-detection.pdf");
// Add properties
runner.setProperty(ConversionProcessor.JNI_PATH, "/opt/local/lib");
runner.setProperty(ConversionProcessor.TEMP_DIR, "/tmp");
// Add the content to the runner
runner.enqueue(new FileInputStream(inputFile));
// Run the enqueued content, it also takes an int = number of contents queued
runner.run(1);
// All results were processed with out failure
runner.assertQueueEmpty();
// If you need to read or do additional tests on results you can access the content
List<MockFlowFile> results = runner.getFlowFilesForRelationship(ConversionProcessor.SUCCESS);
assertEquals(2, results.size() );
for(MockFlowFile result : results) {
byte[] value = runner.getContentAsByteArray(result); | // Path: preprocessing/src/main/java/ocr/preprocessing/conversion/ImageUtils.java
// public enum ImageUtils {
// INSTANCE;
//
// public BufferedImage readImage(byte[] inputImage) throws IOException {
// return ImageIO.read(new ByteArrayInputStream(inputImage));
// }
// public BufferedImage readImage(File inputFile) throws IOException {
// return ImageIO.read(inputFile);
// }
//
// public int getHeight(BufferedImage img) {
// return img.getHeight();
// }
//
// public int getWidth(BufferedImage img) {
// return img.getWidth();
// }
//
// public double getAspectRatio(BufferedImage img) {
//
// return (1.0*getHeight(img))/getWidth(img);
// }
//
// }
// Path: nifi/src/test/java/ocr/nifi/conversion/ConversionProcessorTest.java
import ocr.preprocessing.conversion.ImageUtils;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.ghost4j.document.PDFDocument;
import org.junit.Assert;
import org.junit.Test;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
package ocr.nifi.conversion;
public class ConversionProcessorTest {
@Test
public void test() throws Exception {
// Generate a test runner to mock a processor in a flow
TestRunner runner = TestRunners.newTestRunner(new ConversionProcessor());
File inputFile = new File("../conversion/src/test/resources/text-detection.pdf");
// Add properties
runner.setProperty(ConversionProcessor.JNI_PATH, "/opt/local/lib");
runner.setProperty(ConversionProcessor.TEMP_DIR, "/tmp");
// Add the content to the runner
runner.enqueue(new FileInputStream(inputFile));
// Run the enqueued content, it also takes an int = number of contents queued
runner.run(1);
// All results were processed with out failure
runner.assertQueueEmpty();
// If you need to read or do additional tests on results you can access the content
List<MockFlowFile> results = runner.getFlowFilesForRelationship(ConversionProcessor.SUCCESS);
assertEquals(2, results.size() );
for(MockFlowFile result : results) {
byte[] value = runner.getContentAsByteArray(result); | BufferedImage bi = ImageUtils.INSTANCE.readImage(value); |
castle/castle-java | src/main/java/io/castle/client/internal/utils/VerdictTransportModel.java | // Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/RiskPolicyResult.java
// public class RiskPolicyResult {
//
// /**
// * id of the risk policy
// */
// private String id;
//
// /**
// * id of the risk policy revision
// */
// private String revisionId;
//
// /**
// * name of the risk policy
// */
// private String name;
//
// /**
// * type of the risk policy
// */
// private RiskPolicyType type;
//
//
// public String getId() {
// return id;
// }
//
// public String getRevisionId() {
// return revisionId;
// }
//
// public String getName() {
// return name;
// }
//
// public RiskPolicyType getType() {
// return type;
// }
// }
| import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.RiskPolicyResult; | package io.castle.client.internal.utils;
public class VerdictTransportModel {
private AuthenticateAction action; | // Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/RiskPolicyResult.java
// public class RiskPolicyResult {
//
// /**
// * id of the risk policy
// */
// private String id;
//
// /**
// * id of the risk policy revision
// */
// private String revisionId;
//
// /**
// * name of the risk policy
// */
// private String name;
//
// /**
// * type of the risk policy
// */
// private RiskPolicyType type;
//
//
// public String getId() {
// return id;
// }
//
// public String getRevisionId() {
// return revisionId;
// }
//
// public String getName() {
// return name;
// }
//
// public RiskPolicyType getType() {
// return type;
// }
// }
// Path: src/main/java/io/castle/client/internal/utils/VerdictTransportModel.java
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.RiskPolicyResult;
package io.castle.client.internal.utils;
public class VerdictTransportModel {
private AuthenticateAction action; | private RiskPolicyResult riskPolicy; |
castle/castle-java | src/test/java/io/castle/client/CastleMergeHttpTest.java | // Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/test/java/io/castle/client/utils/SDKVersion.java
// public class SDKVersion {
//
// private static String libraryString = "\"library\":{\"name\":\"castle-java\",\"version\":\"" + getSDKVersion() + "\",\"platform\":\"" + getJavaPlatform() + "\",\"platform_version\":\"" + getJavaVersion() + "\"}";
//
// private static String version = getSDKVersion();
//
// public static String getLibraryString() {
// return libraryString;
// }
//
// public static String getVersion() {
// return version;
// }
//
// private static String getSDKVersion() {
// Properties versionProperties = new Properties();
// PropertiesReader reader = new PropertiesReader();
// InputStream resourceAsStream = Castle.class.getClassLoader().getResourceAsStream("version.properties");
// reader.loadPropertiesFromStream(versionProperties, resourceAsStream);
// return versionProperties.getProperty("sdk.version");
// }
//
// public static String getJavaVersion() {
// return System.getProperty("java.vm.version");
// }
//
// public static String getJavaPlatform() {
// return System.getProperty("java.vm.name");
// }
// }
//
// Path: src/main/java/io/castle/client/model/AsyncCallbackHandler.java
// public interface AsyncCallbackHandler<T> {
// void onResponse(T response);
//
// void onException(Exception exception);
// }
| import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.utils.SDKVersion;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.mock.web.MockHttpServletRequest;
import com.google.common.collect.ImmutableMap;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.atomic.AtomicReference;
import io.castle.client.model.AsyncCallbackHandler;
import org.assertj.core.api.Assertions; | package io.castle.client;
public class CastleMergeHttpTest extends AbstractCastleHttpLayerTest {
public CastleMergeHttpTest() { | // Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/test/java/io/castle/client/utils/SDKVersion.java
// public class SDKVersion {
//
// private static String libraryString = "\"library\":{\"name\":\"castle-java\",\"version\":\"" + getSDKVersion() + "\",\"platform\":\"" + getJavaPlatform() + "\",\"platform_version\":\"" + getJavaVersion() + "\"}";
//
// private static String version = getSDKVersion();
//
// public static String getLibraryString() {
// return libraryString;
// }
//
// public static String getVersion() {
// return version;
// }
//
// private static String getSDKVersion() {
// Properties versionProperties = new Properties();
// PropertiesReader reader = new PropertiesReader();
// InputStream resourceAsStream = Castle.class.getClassLoader().getResourceAsStream("version.properties");
// reader.loadPropertiesFromStream(versionProperties, resourceAsStream);
// return versionProperties.getProperty("sdk.version");
// }
//
// public static String getJavaVersion() {
// return System.getProperty("java.vm.version");
// }
//
// public static String getJavaPlatform() {
// return System.getProperty("java.vm.name");
// }
// }
//
// Path: src/main/java/io/castle/client/model/AsyncCallbackHandler.java
// public interface AsyncCallbackHandler<T> {
// void onResponse(T response);
//
// void onException(Exception exception);
// }
// Path: src/test/java/io/castle/client/CastleMergeHttpTest.java
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.utils.SDKVersion;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.mock.web.MockHttpServletRequest;
import com.google.common.collect.ImmutableMap;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.atomic.AtomicReference;
import io.castle.client.model.AsyncCallbackHandler;
import org.assertj.core.api.Assertions;
package io.castle.client;
public class CastleMergeHttpTest extends AbstractCastleHttpLayerTest {
public CastleMergeHttpTest() { | super(new AuthenticateFailoverStrategy(AuthenticateAction.CHALLENGE)); |
castle/castle-java | src/test/java/io/castle/client/CastleMergeHttpTest.java | // Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/test/java/io/castle/client/utils/SDKVersion.java
// public class SDKVersion {
//
// private static String libraryString = "\"library\":{\"name\":\"castle-java\",\"version\":\"" + getSDKVersion() + "\",\"platform\":\"" + getJavaPlatform() + "\",\"platform_version\":\"" + getJavaVersion() + "\"}";
//
// private static String version = getSDKVersion();
//
// public static String getLibraryString() {
// return libraryString;
// }
//
// public static String getVersion() {
// return version;
// }
//
// private static String getSDKVersion() {
// Properties versionProperties = new Properties();
// PropertiesReader reader = new PropertiesReader();
// InputStream resourceAsStream = Castle.class.getClassLoader().getResourceAsStream("version.properties");
// reader.loadPropertiesFromStream(versionProperties, resourceAsStream);
// return versionProperties.getProperty("sdk.version");
// }
//
// public static String getJavaVersion() {
// return System.getProperty("java.vm.version");
// }
//
// public static String getJavaPlatform() {
// return System.getProperty("java.vm.name");
// }
// }
//
// Path: src/main/java/io/castle/client/model/AsyncCallbackHandler.java
// public interface AsyncCallbackHandler<T> {
// void onResponse(T response);
//
// void onException(Exception exception);
// }
| import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.utils.SDKVersion;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.mock.web.MockHttpServletRequest;
import com.google.common.collect.ImmutableMap;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.atomic.AtomicReference;
import io.castle.client.model.AsyncCallbackHandler;
import org.assertj.core.api.Assertions; | package io.castle.client;
public class CastleMergeHttpTest extends AbstractCastleHttpLayerTest {
public CastleMergeHttpTest() { | // Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/test/java/io/castle/client/utils/SDKVersion.java
// public class SDKVersion {
//
// private static String libraryString = "\"library\":{\"name\":\"castle-java\",\"version\":\"" + getSDKVersion() + "\",\"platform\":\"" + getJavaPlatform() + "\",\"platform_version\":\"" + getJavaVersion() + "\"}";
//
// private static String version = getSDKVersion();
//
// public static String getLibraryString() {
// return libraryString;
// }
//
// public static String getVersion() {
// return version;
// }
//
// private static String getSDKVersion() {
// Properties versionProperties = new Properties();
// PropertiesReader reader = new PropertiesReader();
// InputStream resourceAsStream = Castle.class.getClassLoader().getResourceAsStream("version.properties");
// reader.loadPropertiesFromStream(versionProperties, resourceAsStream);
// return versionProperties.getProperty("sdk.version");
// }
//
// public static String getJavaVersion() {
// return System.getProperty("java.vm.version");
// }
//
// public static String getJavaPlatform() {
// return System.getProperty("java.vm.name");
// }
// }
//
// Path: src/main/java/io/castle/client/model/AsyncCallbackHandler.java
// public interface AsyncCallbackHandler<T> {
// void onResponse(T response);
//
// void onException(Exception exception);
// }
// Path: src/test/java/io/castle/client/CastleMergeHttpTest.java
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.utils.SDKVersion;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.mock.web.MockHttpServletRequest;
import com.google.common.collect.ImmutableMap;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.atomic.AtomicReference;
import io.castle.client.model.AsyncCallbackHandler;
import org.assertj.core.api.Assertions;
package io.castle.client;
public class CastleMergeHttpTest extends AbstractCastleHttpLayerTest {
public CastleMergeHttpTest() { | super(new AuthenticateFailoverStrategy(AuthenticateAction.CHALLENGE)); |
castle/castle-java | src/test/java/io/castle/client/CastleMergeHttpTest.java | // Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/test/java/io/castle/client/utils/SDKVersion.java
// public class SDKVersion {
//
// private static String libraryString = "\"library\":{\"name\":\"castle-java\",\"version\":\"" + getSDKVersion() + "\",\"platform\":\"" + getJavaPlatform() + "\",\"platform_version\":\"" + getJavaVersion() + "\"}";
//
// private static String version = getSDKVersion();
//
// public static String getLibraryString() {
// return libraryString;
// }
//
// public static String getVersion() {
// return version;
// }
//
// private static String getSDKVersion() {
// Properties versionProperties = new Properties();
// PropertiesReader reader = new PropertiesReader();
// InputStream resourceAsStream = Castle.class.getClassLoader().getResourceAsStream("version.properties");
// reader.loadPropertiesFromStream(versionProperties, resourceAsStream);
// return versionProperties.getProperty("sdk.version");
// }
//
// public static String getJavaVersion() {
// return System.getProperty("java.vm.version");
// }
//
// public static String getJavaPlatform() {
// return System.getProperty("java.vm.name");
// }
// }
//
// Path: src/main/java/io/castle/client/model/AsyncCallbackHandler.java
// public interface AsyncCallbackHandler<T> {
// void onResponse(T response);
//
// void onException(Exception exception);
// }
| import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.utils.SDKVersion;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.mock.web.MockHttpServletRequest;
import com.google.common.collect.ImmutableMap;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.atomic.AtomicReference;
import io.castle.client.model.AsyncCallbackHandler;
import org.assertj.core.api.Assertions; | package io.castle.client;
public class CastleMergeHttpTest extends AbstractCastleHttpLayerTest {
public CastleMergeHttpTest() {
super(new AuthenticateFailoverStrategy(AuthenticateAction.CHALLENGE));
}
@Test
public void mergeContextIsSendOnHttp() throws InterruptedException, JSONException {
// Given
server.enqueue(new MockResponse().setResponseCode(200));
String event = "any.valid.event";
// And a mock Request
HttpServletRequest request = new MockHttpServletRequest();
// And a extra context
CustomExtraContext customExtraContext = new CustomExtraContext();
customExtraContext.setAddString("String value");
customExtraContext.setCondition(true);
customExtraContext.setValue(10L);
sdk.onRequest(request).mergeContext(customExtraContext).track(event, null, null, null, ImmutableMap.builder()
.put("x", "valueX")
.put("y", 234567)
.build());
RecordedRequest recordedRequest = server.takeRequest();
String body = recordedRequest.getBody().readUtf8();
| // Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/test/java/io/castle/client/utils/SDKVersion.java
// public class SDKVersion {
//
// private static String libraryString = "\"library\":{\"name\":\"castle-java\",\"version\":\"" + getSDKVersion() + "\",\"platform\":\"" + getJavaPlatform() + "\",\"platform_version\":\"" + getJavaVersion() + "\"}";
//
// private static String version = getSDKVersion();
//
// public static String getLibraryString() {
// return libraryString;
// }
//
// public static String getVersion() {
// return version;
// }
//
// private static String getSDKVersion() {
// Properties versionProperties = new Properties();
// PropertiesReader reader = new PropertiesReader();
// InputStream resourceAsStream = Castle.class.getClassLoader().getResourceAsStream("version.properties");
// reader.loadPropertiesFromStream(versionProperties, resourceAsStream);
// return versionProperties.getProperty("sdk.version");
// }
//
// public static String getJavaVersion() {
// return System.getProperty("java.vm.version");
// }
//
// public static String getJavaPlatform() {
// return System.getProperty("java.vm.name");
// }
// }
//
// Path: src/main/java/io/castle/client/model/AsyncCallbackHandler.java
// public interface AsyncCallbackHandler<T> {
// void onResponse(T response);
//
// void onException(Exception exception);
// }
// Path: src/test/java/io/castle/client/CastleMergeHttpTest.java
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.utils.SDKVersion;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.mock.web.MockHttpServletRequest;
import com.google.common.collect.ImmutableMap;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.atomic.AtomicReference;
import io.castle.client.model.AsyncCallbackHandler;
import org.assertj.core.api.Assertions;
package io.castle.client;
public class CastleMergeHttpTest extends AbstractCastleHttpLayerTest {
public CastleMergeHttpTest() {
super(new AuthenticateFailoverStrategy(AuthenticateAction.CHALLENGE));
}
@Test
public void mergeContextIsSendOnHttp() throws InterruptedException, JSONException {
// Given
server.enqueue(new MockResponse().setResponseCode(200));
String event = "any.valid.event";
// And a mock Request
HttpServletRequest request = new MockHttpServletRequest();
// And a extra context
CustomExtraContext customExtraContext = new CustomExtraContext();
customExtraContext.setAddString("String value");
customExtraContext.setCondition(true);
customExtraContext.setValue(10L);
sdk.onRequest(request).mergeContext(customExtraContext).track(event, null, null, null, ImmutableMap.builder()
.put("x", "valueX")
.put("y", 234567)
.build());
RecordedRequest recordedRequest = server.takeRequest();
String body = recordedRequest.getBody().readUtf8();
| JSONAssert.assertEquals("{\"event\":\"any.valid.event\",\"context\":{\"active\":true,\"ip\":\"127.0.0.1\",\"headers\":{\"REMOTE_ADDR\":\"127.0.0.1\"}," + SDKVersion.getLibraryString() +",\"add_string\":\"String value\",\"condition\":true,\"value\":10},\"user_traits\":{\"x\":\"valueX\",\"y\":234567}}", body, false); |
castle/castle-java | src/test/java/io/castle/client/CastleRemoveUserHttpTest.java | // Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleApiInternalServerErrorException.java
// public class CastleApiInternalServerErrorException extends CastleServerErrorException {
//
// public CastleApiInternalServerErrorException(Response response) {
// super(response);
// }
// }
| import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleApiInternalServerErrorException;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import javax.servlet.http.HttpServletRequest; | package io.castle.client;
public class CastleRemoveUserHttpTest extends AbstractCastleHttpLayerTest {
public CastleRemoveUserHttpTest() { | // Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleApiInternalServerErrorException.java
// public class CastleApiInternalServerErrorException extends CastleServerErrorException {
//
// public CastleApiInternalServerErrorException(Response response) {
// super(response);
// }
// }
// Path: src/test/java/io/castle/client/CastleRemoveUserHttpTest.java
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleApiInternalServerErrorException;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
package io.castle.client;
public class CastleRemoveUserHttpTest extends AbstractCastleHttpLayerTest {
public CastleRemoveUserHttpTest() { | super(new AuthenticateFailoverStrategy(AuthenticateAction.CHALLENGE)); |
castle/castle-java | src/test/java/io/castle/client/CastleRemoveUserHttpTest.java | // Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleApiInternalServerErrorException.java
// public class CastleApiInternalServerErrorException extends CastleServerErrorException {
//
// public CastleApiInternalServerErrorException(Response response) {
// super(response);
// }
// }
| import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleApiInternalServerErrorException;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import javax.servlet.http.HttpServletRequest; | package io.castle.client;
public class CastleRemoveUserHttpTest extends AbstractCastleHttpLayerTest {
public CastleRemoveUserHttpTest() { | // Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleApiInternalServerErrorException.java
// public class CastleApiInternalServerErrorException extends CastleServerErrorException {
//
// public CastleApiInternalServerErrorException(Response response) {
// super(response);
// }
// }
// Path: src/test/java/io/castle/client/CastleRemoveUserHttpTest.java
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleApiInternalServerErrorException;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
package io.castle.client;
public class CastleRemoveUserHttpTest extends AbstractCastleHttpLayerTest {
public CastleRemoveUserHttpTest() { | super(new AuthenticateFailoverStrategy(AuthenticateAction.CHALLENGE)); |
castle/castle-java | src/test/java/io/castle/client/CastleRemoveUserHttpTest.java | // Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleApiInternalServerErrorException.java
// public class CastleApiInternalServerErrorException extends CastleServerErrorException {
//
// public CastleApiInternalServerErrorException(Response response) {
// super(response);
// }
// }
| import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleApiInternalServerErrorException;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import javax.servlet.http.HttpServletRequest; | package io.castle.client;
public class CastleRemoveUserHttpTest extends AbstractCastleHttpLayerTest {
public CastleRemoveUserHttpTest() {
super(new AuthenticateFailoverStrategy(AuthenticateAction.CHALLENGE));
}
@Test
public void removeUser() throws Exception {
// Mock a response
MockResponse mockResponse = new MockResponse();
mockResponse.setResponseCode(202);
server.enqueue(mockResponse);
// And a mock Request
HttpServletRequest request = new MockHttpServletRequest();
// And an privacy remove user request is made
Boolean response = sdk.onRequest(request).removeUser("user-test-id");
// Then
RecordedRequest recordedRequest = server.takeRequest();
Assert.assertEquals(testServerBaseUrl.resolve("v1/privacy/users/user-test-id"), recordedRequest.getRequestUrl());
Assert.assertEquals("DELETE", recordedRequest.getMethod());
Assert.assertTrue(response);
}
@Test
public void removeUserNotFoundTest() throws Exception {
// Mock a response
MockResponse mockResponse = new MockResponse();
mockResponse.setResponseCode(404);
server.enqueue(mockResponse);
// And a mock Request
HttpServletRequest request = new MockHttpServletRequest();
// And an privacy remove user request is made
Boolean response = sdk.onRequest(request).removeUser("user-test-id");
// Then it doesn't throw exception
RecordedRequest recordedRequest = server.takeRequest();
Assert.assertEquals(testServerBaseUrl.resolve("v1/privacy/users/user-test-id"), recordedRequest.getRequestUrl());
Assert.assertEquals("DELETE", recordedRequest.getMethod());
Assert.assertNull(response);
}
| // Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleApiInternalServerErrorException.java
// public class CastleApiInternalServerErrorException extends CastleServerErrorException {
//
// public CastleApiInternalServerErrorException(Response response) {
// super(response);
// }
// }
// Path: src/test/java/io/castle/client/CastleRemoveUserHttpTest.java
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleApiInternalServerErrorException;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
package io.castle.client;
public class CastleRemoveUserHttpTest extends AbstractCastleHttpLayerTest {
public CastleRemoveUserHttpTest() {
super(new AuthenticateFailoverStrategy(AuthenticateAction.CHALLENGE));
}
@Test
public void removeUser() throws Exception {
// Mock a response
MockResponse mockResponse = new MockResponse();
mockResponse.setResponseCode(202);
server.enqueue(mockResponse);
// And a mock Request
HttpServletRequest request = new MockHttpServletRequest();
// And an privacy remove user request is made
Boolean response = sdk.onRequest(request).removeUser("user-test-id");
// Then
RecordedRequest recordedRequest = server.takeRequest();
Assert.assertEquals(testServerBaseUrl.resolve("v1/privacy/users/user-test-id"), recordedRequest.getRequestUrl());
Assert.assertEquals("DELETE", recordedRequest.getMethod());
Assert.assertTrue(response);
}
@Test
public void removeUserNotFoundTest() throws Exception {
// Mock a response
MockResponse mockResponse = new MockResponse();
mockResponse.setResponseCode(404);
server.enqueue(mockResponse);
// And a mock Request
HttpServletRequest request = new MockHttpServletRequest();
// And an privacy remove user request is made
Boolean response = sdk.onRequest(request).removeUser("user-test-id");
// Then it doesn't throw exception
RecordedRequest recordedRequest = server.takeRequest();
Assert.assertEquals(testServerBaseUrl.resolve("v1/privacy/users/user-test-id"), recordedRequest.getRequestUrl());
Assert.assertEquals("DELETE", recordedRequest.getMethod());
Assert.assertNull(response);
}
| @Test(expected = CastleApiInternalServerErrorException.class) |
castle/castle-java | src/test/java/io/castle/client/model/CastleUserDevicesTest.java | // Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
//
// Path: src/test/java/io/castle/client/utils/DeviceUtils.java
// public class DeviceUtils {
//
// public static final String DEVICE_TOKEN = "abcdefg12345";
// public static final double DEVICE_RISK = 0.000154;
// public static final String DEVICE_CREATED_AT = "2018-06-15T16:36:22.916Z";
// public static final String DEVICE_LAST_SEEN_AT = "2018-07-19T23:09:29.681Z";
// public static final String DEVICE_APPROVED_AT = null;
// public static final String DEVICE_ESCALATED_AT = null;
// public static final String DEVICE_MITIGATED_AT = null;
//
// public static final String CONTEXT_TYPE = "desktop";
// public static final String CONTEXT_IP = "1.1.1.1";
//
// public static final String USER_AGENT_FAMILY = "Opera";
// public static final String USER_AGENT_DEVICE = "Unknown";
// public static final String USER_AGENT_PLATFORM = "Mac OS X";
// public static final String USER_AGENT_OS = "Mac OS X 10.13.6";
// public static final String USER_AGENT_VERSION = "54.0.2952";
// public static final String USER_AGENT_BROWSER = "Opera";
// public static final String USER_AGENT_RAW = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51";
// public static final boolean USER_AGENT_MOBILE = false;
//
// public static CastleUserDevice createExpectedDevice() {
// CastleUserDevice device = new CastleUserDevice();
// device.setToken(DEVICE_TOKEN);
// device.setRisk(DEVICE_RISK);
// device.setCreatedAt(DEVICE_CREATED_AT);
// device.setLastSeenAt(DEVICE_LAST_SEEN_AT);
// device.setApprovedAt(null);
// device.setEscalatedAt(null);
// device.setMitigatedAt(null);
//
// CastleUserDeviceContext deviceContext = new CastleUserDeviceContext();
// deviceContext.setIp(CONTEXT_IP);
// deviceContext.setType(CONTEXT_TYPE);
//
// DeviceUserAgent userAgent = new DeviceUserAgent();
// userAgent.setFamily(USER_AGENT_FAMILY);
// userAgent.setDevice(USER_AGENT_DEVICE);
// userAgent.setPlatform(USER_AGENT_PLATFORM);
// userAgent.setOs(USER_AGENT_OS);
// userAgent.setVersion(USER_AGENT_VERSION);
// userAgent.setBrowser(USER_AGENT_BROWSER);
// userAgent.setRaw(USER_AGENT_RAW);
// userAgent.setMobile(USER_AGENT_MOBILE);
//
// deviceContext.setUserAgent(userAgent);
//
// device.setContext(deviceContext);
//
// return device;
// }
//
// public static CastleUserDevices createExpectedDevices() {
// CastleUserDevices devices = new CastleUserDevices();
// devices.setDevices(Arrays.asList(createExpectedDevice()));
// return devices;
// }
//
// public static String getDefaultDeviceJSON() {
// return "{\"token\":\"abcdefg12345\",\"risk\":0.000154,\"created_at\":\"2018-06-15T16:36:22.916Z\",\"last_seen_at\":\"2018-07-19T23:09:29.681Z\",\"approved_at\":null,\"escalated_at\":null,\"mitigated_at\":null,\"context\":{\"ip\":\"1.1.1.1\",\"location\":{\"country_code\":\"US\",\"country\":\"United States\",\"region\":\"New Jersey\",\"region_code\":\"NJ\",\"city\":\"Lyndhurst\",\"lat\":40.7923,\"lon\":-74.1001},\"user_agent\":{\"raw\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51\",\"browser\":\"Opera\",\"version\":\"54.0.2952\",\"os\":\"Mac OS X 10.13.6\",\"mobile\":false,\"platform\":\"Mac OS X\",\"device\":\"Unknown\",\"family\":\"Opera\"},\"type\":\"desktop\"}}";
// }
// }
| import io.castle.client.internal.json.CastleGsonModel;
import io.castle.client.utils.DeviceUtils;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List; | package io.castle.client.model;
public class CastleUserDevicesTest {
private CastleGsonModel model = new CastleGsonModel();
@Test
public void jsonSerialized() {
// Given
CastleUserDevices devices = new CastleUserDevices();
// When
String payloadJson = model.getGson().toJson(devices);
// Then
Assertions.assertThat(payloadJson).isEqualTo("{\"total_count\":0}");
}
@Test
public void fullBuilderJson() {
// Given
CastleUserDevices devices = new CastleUserDevices();
List<CastleUserDevice> devicesList = new ArrayList<>();
CastleUserDevice device = new CastleUserDevice(); | // Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
//
// Path: src/test/java/io/castle/client/utils/DeviceUtils.java
// public class DeviceUtils {
//
// public static final String DEVICE_TOKEN = "abcdefg12345";
// public static final double DEVICE_RISK = 0.000154;
// public static final String DEVICE_CREATED_AT = "2018-06-15T16:36:22.916Z";
// public static final String DEVICE_LAST_SEEN_AT = "2018-07-19T23:09:29.681Z";
// public static final String DEVICE_APPROVED_AT = null;
// public static final String DEVICE_ESCALATED_AT = null;
// public static final String DEVICE_MITIGATED_AT = null;
//
// public static final String CONTEXT_TYPE = "desktop";
// public static final String CONTEXT_IP = "1.1.1.1";
//
// public static final String USER_AGENT_FAMILY = "Opera";
// public static final String USER_AGENT_DEVICE = "Unknown";
// public static final String USER_AGENT_PLATFORM = "Mac OS X";
// public static final String USER_AGENT_OS = "Mac OS X 10.13.6";
// public static final String USER_AGENT_VERSION = "54.0.2952";
// public static final String USER_AGENT_BROWSER = "Opera";
// public static final String USER_AGENT_RAW = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51";
// public static final boolean USER_AGENT_MOBILE = false;
//
// public static CastleUserDevice createExpectedDevice() {
// CastleUserDevice device = new CastleUserDevice();
// device.setToken(DEVICE_TOKEN);
// device.setRisk(DEVICE_RISK);
// device.setCreatedAt(DEVICE_CREATED_AT);
// device.setLastSeenAt(DEVICE_LAST_SEEN_AT);
// device.setApprovedAt(null);
// device.setEscalatedAt(null);
// device.setMitigatedAt(null);
//
// CastleUserDeviceContext deviceContext = new CastleUserDeviceContext();
// deviceContext.setIp(CONTEXT_IP);
// deviceContext.setType(CONTEXT_TYPE);
//
// DeviceUserAgent userAgent = new DeviceUserAgent();
// userAgent.setFamily(USER_AGENT_FAMILY);
// userAgent.setDevice(USER_AGENT_DEVICE);
// userAgent.setPlatform(USER_AGENT_PLATFORM);
// userAgent.setOs(USER_AGENT_OS);
// userAgent.setVersion(USER_AGENT_VERSION);
// userAgent.setBrowser(USER_AGENT_BROWSER);
// userAgent.setRaw(USER_AGENT_RAW);
// userAgent.setMobile(USER_AGENT_MOBILE);
//
// deviceContext.setUserAgent(userAgent);
//
// device.setContext(deviceContext);
//
// return device;
// }
//
// public static CastleUserDevices createExpectedDevices() {
// CastleUserDevices devices = new CastleUserDevices();
// devices.setDevices(Arrays.asList(createExpectedDevice()));
// return devices;
// }
//
// public static String getDefaultDeviceJSON() {
// return "{\"token\":\"abcdefg12345\",\"risk\":0.000154,\"created_at\":\"2018-06-15T16:36:22.916Z\",\"last_seen_at\":\"2018-07-19T23:09:29.681Z\",\"approved_at\":null,\"escalated_at\":null,\"mitigated_at\":null,\"context\":{\"ip\":\"1.1.1.1\",\"location\":{\"country_code\":\"US\",\"country\":\"United States\",\"region\":\"New Jersey\",\"region_code\":\"NJ\",\"city\":\"Lyndhurst\",\"lat\":40.7923,\"lon\":-74.1001},\"user_agent\":{\"raw\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51\",\"browser\":\"Opera\",\"version\":\"54.0.2952\",\"os\":\"Mac OS X 10.13.6\",\"mobile\":false,\"platform\":\"Mac OS X\",\"device\":\"Unknown\",\"family\":\"Opera\"},\"type\":\"desktop\"}}";
// }
// }
// Path: src/test/java/io/castle/client/model/CastleUserDevicesTest.java
import io.castle.client.internal.json.CastleGsonModel;
import io.castle.client.utils.DeviceUtils;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
package io.castle.client.model;
public class CastleUserDevicesTest {
private CastleGsonModel model = new CastleGsonModel();
@Test
public void jsonSerialized() {
// Given
CastleUserDevices devices = new CastleUserDevices();
// When
String payloadJson = model.getGson().toJson(devices);
// Then
Assertions.assertThat(payloadJson).isEqualTo("{\"total_count\":0}");
}
@Test
public void fullBuilderJson() {
// Given
CastleUserDevices devices = new CastleUserDevices();
List<CastleUserDevice> devicesList = new ArrayList<>();
CastleUserDevice device = new CastleUserDevice(); | device.setToken(DeviceUtils.DEVICE_TOKEN); |
castle/castle-java | src/main/java/io/castle/client/internal/utils/VerdictBuilder.java | // Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/RiskPolicyResult.java
// public class RiskPolicyResult {
//
// /**
// * id of the risk policy
// */
// private String id;
//
// /**
// * id of the risk policy revision
// */
// private String revisionId;
//
// /**
// * name of the risk policy
// */
// private String name;
//
// /**
// * type of the risk policy
// */
// private RiskPolicyType type;
//
//
// public String getId() {
// return id;
// }
//
// public String getRevisionId() {
// return revisionId;
// }
//
// public String getName() {
// return name;
// }
//
// public RiskPolicyType getType() {
// return type;
// }
// }
//
// Path: src/main/java/io/castle/client/model/Verdict.java
// public class Verdict {
//
// /**
// * AuthenticateAction returned by a call to the CastleAPI, or configured by a failover strategy.
// */
// private AuthenticateAction action;
//
// /**
// * String representing a user ID associated with an authenticate call.
// */
// private String userId;
//
// /**
// * True if the SDK resorted the {@code AuthenticateFailoverStrategy} configured.
// */
// private boolean failover;
//
// /**
// * Explains the reason why the {@code AuthenticateFailoverStrategy} was used.
// */
// private String failoverReason;
//
// /**
// * String representing a device ID associated with an authenticate call.
// */
// private String deviceToken;
//
// /**
// * Float representing risk value associated with an authenticate call.
// */
// private float risk;
//
// /**
// * RiskPolicyResult representing risk policy used for generating this verdict.
// */
// private RiskPolicyResult riskPolicy;
//
// /**
// * JsonElement representing the full response of the server request
// */
// private JsonElement internal;
//
// public AuthenticateAction getAction() {
// return action;
// }
//
// public void setAction(AuthenticateAction action) {
// this.action = action;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
//
// public boolean isFailover() {
// return failover;
// }
//
// public void setFailover(boolean failover) {
// this.failover = failover;
// }
//
// public String getFailoverReason() {
// return failoverReason;
// }
//
// public void setFailoverReason(String failoverReason) {
// this.failoverReason = failoverReason;
// }
//
// public String getDeviceToken() {
// return deviceToken;
// }
//
// public void setRisk(float risk) {
// this.risk = risk;
// }
//
// public float getRisk() {
// return risk;
// }
//
// public void setDeviceToken(String deviceToken) {
// this.deviceToken = deviceToken;
// }
//
// public void setInternal(JsonElement internal) {
// this.internal = internal;
// }
//
// public RiskPolicyResult getRiskPolicy() {
// return riskPolicy;
// }
//
// public void setRiskPolicy(RiskPolicyResult riskPolicy) {
// this.riskPolicy = riskPolicy;
// }
//
// public JsonElement getInternal() {
// return internal;
// }
// }
| import com.google.gson.JsonElement;
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.RiskPolicyResult;
import io.castle.client.model.Verdict; | package io.castle.client.internal.utils;
public class VerdictBuilder {
private AuthenticateAction action; | // Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/RiskPolicyResult.java
// public class RiskPolicyResult {
//
// /**
// * id of the risk policy
// */
// private String id;
//
// /**
// * id of the risk policy revision
// */
// private String revisionId;
//
// /**
// * name of the risk policy
// */
// private String name;
//
// /**
// * type of the risk policy
// */
// private RiskPolicyType type;
//
//
// public String getId() {
// return id;
// }
//
// public String getRevisionId() {
// return revisionId;
// }
//
// public String getName() {
// return name;
// }
//
// public RiskPolicyType getType() {
// return type;
// }
// }
//
// Path: src/main/java/io/castle/client/model/Verdict.java
// public class Verdict {
//
// /**
// * AuthenticateAction returned by a call to the CastleAPI, or configured by a failover strategy.
// */
// private AuthenticateAction action;
//
// /**
// * String representing a user ID associated with an authenticate call.
// */
// private String userId;
//
// /**
// * True if the SDK resorted the {@code AuthenticateFailoverStrategy} configured.
// */
// private boolean failover;
//
// /**
// * Explains the reason why the {@code AuthenticateFailoverStrategy} was used.
// */
// private String failoverReason;
//
// /**
// * String representing a device ID associated with an authenticate call.
// */
// private String deviceToken;
//
// /**
// * Float representing risk value associated with an authenticate call.
// */
// private float risk;
//
// /**
// * RiskPolicyResult representing risk policy used for generating this verdict.
// */
// private RiskPolicyResult riskPolicy;
//
// /**
// * JsonElement representing the full response of the server request
// */
// private JsonElement internal;
//
// public AuthenticateAction getAction() {
// return action;
// }
//
// public void setAction(AuthenticateAction action) {
// this.action = action;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
//
// public boolean isFailover() {
// return failover;
// }
//
// public void setFailover(boolean failover) {
// this.failover = failover;
// }
//
// public String getFailoverReason() {
// return failoverReason;
// }
//
// public void setFailoverReason(String failoverReason) {
// this.failoverReason = failoverReason;
// }
//
// public String getDeviceToken() {
// return deviceToken;
// }
//
// public void setRisk(float risk) {
// this.risk = risk;
// }
//
// public float getRisk() {
// return risk;
// }
//
// public void setDeviceToken(String deviceToken) {
// this.deviceToken = deviceToken;
// }
//
// public void setInternal(JsonElement internal) {
// this.internal = internal;
// }
//
// public RiskPolicyResult getRiskPolicy() {
// return riskPolicy;
// }
//
// public void setRiskPolicy(RiskPolicyResult riskPolicy) {
// this.riskPolicy = riskPolicy;
// }
//
// public JsonElement getInternal() {
// return internal;
// }
// }
// Path: src/main/java/io/castle/client/internal/utils/VerdictBuilder.java
import com.google.gson.JsonElement;
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.RiskPolicyResult;
import io.castle.client.model.Verdict;
package io.castle.client.internal.utils;
public class VerdictBuilder {
private AuthenticateAction action; | private RiskPolicyResult riskPolicy; |
castle/castle-java | src/main/java/io/castle/client/internal/utils/VerdictBuilder.java | // Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/RiskPolicyResult.java
// public class RiskPolicyResult {
//
// /**
// * id of the risk policy
// */
// private String id;
//
// /**
// * id of the risk policy revision
// */
// private String revisionId;
//
// /**
// * name of the risk policy
// */
// private String name;
//
// /**
// * type of the risk policy
// */
// private RiskPolicyType type;
//
//
// public String getId() {
// return id;
// }
//
// public String getRevisionId() {
// return revisionId;
// }
//
// public String getName() {
// return name;
// }
//
// public RiskPolicyType getType() {
// return type;
// }
// }
//
// Path: src/main/java/io/castle/client/model/Verdict.java
// public class Verdict {
//
// /**
// * AuthenticateAction returned by a call to the CastleAPI, or configured by a failover strategy.
// */
// private AuthenticateAction action;
//
// /**
// * String representing a user ID associated with an authenticate call.
// */
// private String userId;
//
// /**
// * True if the SDK resorted the {@code AuthenticateFailoverStrategy} configured.
// */
// private boolean failover;
//
// /**
// * Explains the reason why the {@code AuthenticateFailoverStrategy} was used.
// */
// private String failoverReason;
//
// /**
// * String representing a device ID associated with an authenticate call.
// */
// private String deviceToken;
//
// /**
// * Float representing risk value associated with an authenticate call.
// */
// private float risk;
//
// /**
// * RiskPolicyResult representing risk policy used for generating this verdict.
// */
// private RiskPolicyResult riskPolicy;
//
// /**
// * JsonElement representing the full response of the server request
// */
// private JsonElement internal;
//
// public AuthenticateAction getAction() {
// return action;
// }
//
// public void setAction(AuthenticateAction action) {
// this.action = action;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
//
// public boolean isFailover() {
// return failover;
// }
//
// public void setFailover(boolean failover) {
// this.failover = failover;
// }
//
// public String getFailoverReason() {
// return failoverReason;
// }
//
// public void setFailoverReason(String failoverReason) {
// this.failoverReason = failoverReason;
// }
//
// public String getDeviceToken() {
// return deviceToken;
// }
//
// public void setRisk(float risk) {
// this.risk = risk;
// }
//
// public float getRisk() {
// return risk;
// }
//
// public void setDeviceToken(String deviceToken) {
// this.deviceToken = deviceToken;
// }
//
// public void setInternal(JsonElement internal) {
// this.internal = internal;
// }
//
// public RiskPolicyResult getRiskPolicy() {
// return riskPolicy;
// }
//
// public void setRiskPolicy(RiskPolicyResult riskPolicy) {
// this.riskPolicy = riskPolicy;
// }
//
// public JsonElement getInternal() {
// return internal;
// }
// }
| import com.google.gson.JsonElement;
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.RiskPolicyResult;
import io.castle.client.model.Verdict; | .withFailover(true)
.withFailoverReason(failoverReason);
}
public VerdictBuilder withAction(AuthenticateAction action) {
this.action = action;
return this;
}
public VerdictBuilder withUserId(String userId) {
this.userId = userId;
return this;
}
public VerdictBuilder withRiskPolicy(RiskPolicyResult riskPolicy) {
this.riskPolicy = riskPolicy;
return this;
}
public VerdictBuilder withDeviceToken(final String deviceToken) {
this.deviceToken = deviceToken;
return this;
}
public VerdictBuilder withRisk(final float risk) {
this.risk = risk;
return this;
}
| // Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/RiskPolicyResult.java
// public class RiskPolicyResult {
//
// /**
// * id of the risk policy
// */
// private String id;
//
// /**
// * id of the risk policy revision
// */
// private String revisionId;
//
// /**
// * name of the risk policy
// */
// private String name;
//
// /**
// * type of the risk policy
// */
// private RiskPolicyType type;
//
//
// public String getId() {
// return id;
// }
//
// public String getRevisionId() {
// return revisionId;
// }
//
// public String getName() {
// return name;
// }
//
// public RiskPolicyType getType() {
// return type;
// }
// }
//
// Path: src/main/java/io/castle/client/model/Verdict.java
// public class Verdict {
//
// /**
// * AuthenticateAction returned by a call to the CastleAPI, or configured by a failover strategy.
// */
// private AuthenticateAction action;
//
// /**
// * String representing a user ID associated with an authenticate call.
// */
// private String userId;
//
// /**
// * True if the SDK resorted the {@code AuthenticateFailoverStrategy} configured.
// */
// private boolean failover;
//
// /**
// * Explains the reason why the {@code AuthenticateFailoverStrategy} was used.
// */
// private String failoverReason;
//
// /**
// * String representing a device ID associated with an authenticate call.
// */
// private String deviceToken;
//
// /**
// * Float representing risk value associated with an authenticate call.
// */
// private float risk;
//
// /**
// * RiskPolicyResult representing risk policy used for generating this verdict.
// */
// private RiskPolicyResult riskPolicy;
//
// /**
// * JsonElement representing the full response of the server request
// */
// private JsonElement internal;
//
// public AuthenticateAction getAction() {
// return action;
// }
//
// public void setAction(AuthenticateAction action) {
// this.action = action;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
//
// public boolean isFailover() {
// return failover;
// }
//
// public void setFailover(boolean failover) {
// this.failover = failover;
// }
//
// public String getFailoverReason() {
// return failoverReason;
// }
//
// public void setFailoverReason(String failoverReason) {
// this.failoverReason = failoverReason;
// }
//
// public String getDeviceToken() {
// return deviceToken;
// }
//
// public void setRisk(float risk) {
// this.risk = risk;
// }
//
// public float getRisk() {
// return risk;
// }
//
// public void setDeviceToken(String deviceToken) {
// this.deviceToken = deviceToken;
// }
//
// public void setInternal(JsonElement internal) {
// this.internal = internal;
// }
//
// public RiskPolicyResult getRiskPolicy() {
// return riskPolicy;
// }
//
// public void setRiskPolicy(RiskPolicyResult riskPolicy) {
// this.riskPolicy = riskPolicy;
// }
//
// public JsonElement getInternal() {
// return internal;
// }
// }
// Path: src/main/java/io/castle/client/internal/utils/VerdictBuilder.java
import com.google.gson.JsonElement;
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.RiskPolicyResult;
import io.castle.client.model.Verdict;
.withFailover(true)
.withFailoverReason(failoverReason);
}
public VerdictBuilder withAction(AuthenticateAction action) {
this.action = action;
return this;
}
public VerdictBuilder withUserId(String userId) {
this.userId = userId;
return this;
}
public VerdictBuilder withRiskPolicy(RiskPolicyResult riskPolicy) {
this.riskPolicy = riskPolicy;
return this;
}
public VerdictBuilder withDeviceToken(final String deviceToken) {
this.deviceToken = deviceToken;
return this;
}
public VerdictBuilder withRisk(final float risk) {
this.risk = risk;
return this;
}
| public Verdict build() { |
castle/castle-java | src/test/java/io/castle/client/internal/config/ConfigurationLoaderTest.java | // Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleRuntimeException.java
// public class CastleRuntimeException extends RuntimeException {
//
// public CastleRuntimeException(Throwable throwable) {
// super(throwable);
// }
//
// public CastleRuntimeException(String message) {
// super(message);
// }
//
// public CastleRuntimeException(Response response) {
// super(response.toString());
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
| import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleRuntimeException;
import io.castle.client.model.CastleSdkConfigurationException;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import java.util.Properties; | package io.castle.client.internal.config;
public class ConfigurationLoaderTest {
@Rule
public final EnvironmentVariables environmentVariables
= new EnvironmentVariables();
@Test | // Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleRuntimeException.java
// public class CastleRuntimeException extends RuntimeException {
//
// public CastleRuntimeException(Throwable throwable) {
// super(throwable);
// }
//
// public CastleRuntimeException(String message) {
// super(message);
// }
//
// public CastleRuntimeException(Response response) {
// super(response.toString());
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
// Path: src/test/java/io/castle/client/internal/config/ConfigurationLoaderTest.java
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleRuntimeException;
import io.castle.client.model.CastleSdkConfigurationException;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import java.util.Properties;
package io.castle.client.internal.config;
public class ConfigurationLoaderTest {
@Rule
public final EnvironmentVariables environmentVariables
= new EnvironmentVariables();
@Test | public void loadConfigWithNullValuesExceptForAppIDAndPISecret() throws CastleSdkConfigurationException { |
castle/castle-java | src/test/java/io/castle/client/internal/config/ConfigurationLoaderTest.java | // Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleRuntimeException.java
// public class CastleRuntimeException extends RuntimeException {
//
// public CastleRuntimeException(Throwable throwable) {
// super(throwable);
// }
//
// public CastleRuntimeException(String message) {
// super(message);
// }
//
// public CastleRuntimeException(Response response) {
// super(response.toString());
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
| import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleRuntimeException;
import io.castle.client.model.CastleSdkConfigurationException;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import java.util.Properties; | }
@Test
public void loadFromProperties() throws CastleSdkConfigurationException {
//given
CastleConfiguration expectedConfiguration = CastleConfigurationBuilder
.aConfigBuilder()
.withApiSecret("test_api_secret")
.withCastleAppId("test_app_id")
.withApiBaseUrl("https://testing.api.dev.castle/v1/")
.withAllowListHeaders(
"TestAllow",
"User-Agent",
"Accept-Language",
"Accept-Encoding",
"Accept-Charset",
"Accept",
"Accept-Datetime",
"X-Forwarded-For",
"Forwarded",
"X-Forwarded",
"X-Real-IP",
"REMOTE_ADDR"
)
.withDenyListHeaders(
"TestDeny",
"Cookie"
)
.withDefaultBackendProvider()
.withTimeout(100) | // Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleRuntimeException.java
// public class CastleRuntimeException extends RuntimeException {
//
// public CastleRuntimeException(Throwable throwable) {
// super(throwable);
// }
//
// public CastleRuntimeException(String message) {
// super(message);
// }
//
// public CastleRuntimeException(Response response) {
// super(response.toString());
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
// Path: src/test/java/io/castle/client/internal/config/ConfigurationLoaderTest.java
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleRuntimeException;
import io.castle.client.model.CastleSdkConfigurationException;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import java.util.Properties;
}
@Test
public void loadFromProperties() throws CastleSdkConfigurationException {
//given
CastleConfiguration expectedConfiguration = CastleConfigurationBuilder
.aConfigBuilder()
.withApiSecret("test_api_secret")
.withCastleAppId("test_app_id")
.withApiBaseUrl("https://testing.api.dev.castle/v1/")
.withAllowListHeaders(
"TestAllow",
"User-Agent",
"Accept-Language",
"Accept-Encoding",
"Accept-Charset",
"Accept",
"Accept-Datetime",
"X-Forwarded-For",
"Forwarded",
"X-Forwarded",
"X-Real-IP",
"REMOTE_ADDR"
)
.withDenyListHeaders(
"TestDeny",
"Cookie"
)
.withDefaultBackendProvider()
.withTimeout(100) | .withAuthenticateFailoverStrategy(new AuthenticateFailoverStrategy(AuthenticateAction.CHALLENGE)) |
castle/castle-java | src/test/java/io/castle/client/internal/config/ConfigurationLoaderTest.java | // Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleRuntimeException.java
// public class CastleRuntimeException extends RuntimeException {
//
// public CastleRuntimeException(Throwable throwable) {
// super(throwable);
// }
//
// public CastleRuntimeException(String message) {
// super(message);
// }
//
// public CastleRuntimeException(Response response) {
// super(response.toString());
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
| import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleRuntimeException;
import io.castle.client.model.CastleSdkConfigurationException;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import java.util.Properties; | }
@Test
public void loadFromProperties() throws CastleSdkConfigurationException {
//given
CastleConfiguration expectedConfiguration = CastleConfigurationBuilder
.aConfigBuilder()
.withApiSecret("test_api_secret")
.withCastleAppId("test_app_id")
.withApiBaseUrl("https://testing.api.dev.castle/v1/")
.withAllowListHeaders(
"TestAllow",
"User-Agent",
"Accept-Language",
"Accept-Encoding",
"Accept-Charset",
"Accept",
"Accept-Datetime",
"X-Forwarded-For",
"Forwarded",
"X-Forwarded",
"X-Real-IP",
"REMOTE_ADDR"
)
.withDenyListHeaders(
"TestDeny",
"Cookie"
)
.withDefaultBackendProvider()
.withTimeout(100) | // Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleRuntimeException.java
// public class CastleRuntimeException extends RuntimeException {
//
// public CastleRuntimeException(Throwable throwable) {
// super(throwable);
// }
//
// public CastleRuntimeException(String message) {
// super(message);
// }
//
// public CastleRuntimeException(Response response) {
// super(response.toString());
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
// Path: src/test/java/io/castle/client/internal/config/ConfigurationLoaderTest.java
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleRuntimeException;
import io.castle.client.model.CastleSdkConfigurationException;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import java.util.Properties;
}
@Test
public void loadFromProperties() throws CastleSdkConfigurationException {
//given
CastleConfiguration expectedConfiguration = CastleConfigurationBuilder
.aConfigBuilder()
.withApiSecret("test_api_secret")
.withCastleAppId("test_app_id")
.withApiBaseUrl("https://testing.api.dev.castle/v1/")
.withAllowListHeaders(
"TestAllow",
"User-Agent",
"Accept-Language",
"Accept-Encoding",
"Accept-Charset",
"Accept",
"Accept-Datetime",
"X-Forwarded-For",
"Forwarded",
"X-Forwarded",
"X-Real-IP",
"REMOTE_ADDR"
)
.withDenyListHeaders(
"TestDeny",
"Cookie"
)
.withDefaultBackendProvider()
.withTimeout(100) | .withAuthenticateFailoverStrategy(new AuthenticateFailoverStrategy(AuthenticateAction.CHALLENGE)) |
castle/castle-java | src/test/java/io/castle/client/internal/config/ConfigurationLoaderTest.java | // Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleRuntimeException.java
// public class CastleRuntimeException extends RuntimeException {
//
// public CastleRuntimeException(Throwable throwable) {
// super(throwable);
// }
//
// public CastleRuntimeException(String message) {
// super(message);
// }
//
// public CastleRuntimeException(Response response) {
// super(response.toString());
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
| import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleRuntimeException;
import io.castle.client.model.CastleSdkConfigurationException;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import java.util.Properties; |
//then log http flag is true
Assertions.assertThat(castleConfiguration.isLogHttpRequests()).isTrue();
}
@Test(expected = NumberFormatException.class)
public void testTimeoutWithNonParsableInt() throws CastleSdkConfigurationException {
//given
Properties properties = new Properties();
properties.setProperty("api_secret", "212312");
properties.setProperty("app_id", "F");
properties.setProperty("timeout", "UnparsableInt");
ConfigurationLoader loader = new ConfigurationLoader(properties);
//then
loader.loadConfiguration();
//then an exception is throw, since the provided timeout cannot be parsed into an int.
}
@Test(expected = CastleSdkConfigurationException.class)
public void tryToLoadConfigurationsFromAWrongFile() throws CastleSdkConfigurationException {
//given
setEnvAndTestCorrectness("CASTLE_PROPERTIES_FILE", "castle_sdk.wrongproperties");
ConfigurationLoader loader = new ConfigurationLoader();
//when
loader.loadConfiguration();
}
| // Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleRuntimeException.java
// public class CastleRuntimeException extends RuntimeException {
//
// public CastleRuntimeException(Throwable throwable) {
// super(throwable);
// }
//
// public CastleRuntimeException(String message) {
// super(message);
// }
//
// public CastleRuntimeException(Response response) {
// super(response.toString());
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
// Path: src/test/java/io/castle/client/internal/config/ConfigurationLoaderTest.java
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleRuntimeException;
import io.castle.client.model.CastleSdkConfigurationException;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import java.util.Properties;
//then log http flag is true
Assertions.assertThat(castleConfiguration.isLogHttpRequests()).isTrue();
}
@Test(expected = NumberFormatException.class)
public void testTimeoutWithNonParsableInt() throws CastleSdkConfigurationException {
//given
Properties properties = new Properties();
properties.setProperty("api_secret", "212312");
properties.setProperty("app_id", "F");
properties.setProperty("timeout", "UnparsableInt");
ConfigurationLoader loader = new ConfigurationLoader(properties);
//then
loader.loadConfiguration();
//then an exception is throw, since the provided timeout cannot be parsed into an int.
}
@Test(expected = CastleSdkConfigurationException.class)
public void tryToLoadConfigurationsFromAWrongFile() throws CastleSdkConfigurationException {
//given
setEnvAndTestCorrectness("CASTLE_PROPERTIES_FILE", "castle_sdk.wrongproperties");
ConfigurationLoader loader = new ConfigurationLoader();
//when
loader.loadConfiguration();
}
| @Test(expected = CastleRuntimeException.class) |
castle/castle-java | src/test/java/io/castle/client/TimestampTest.java | // Path: src/main/java/io/castle/client/internal/utils/Timestamp.java
// public class Timestamp {
// private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", new Locale("en", "US", "POSIX"));
//
// /**
// * Return an ISO 8601 combined date and time string for current date/time
// *
// * @return String with format "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
// */
// public static String timestamp() {
// return timestamp(new Date());
// }
//
// /**
// * Return an ISO 8601 combined date and time string for specified date/time
// *
// * @param date Date
// * @return String with format "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
// */
// public static String timestamp(Date date) {
// dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
// return dateFormat.format(date);
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
| import io.castle.client.internal.utils.Timestamp;
import io.castle.client.model.CastleSdkConfigurationException;
import org.assertj.core.api.Assertions;
import org.assertj.core.util.DateUtil;
import org.junit.Test;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone; | package io.castle.client;
public class TimestampTest {
@Test
public void dateToTimestamp() {
//Given
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), new Locale("en", "US", "POSIX"));
calendar.set(Calendar.YEAR, 2019);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.DAY_OF_MONTH, 2);
calendar.set(Calendar.HOUR_OF_DAY, 3);
calendar.set(Calendar.MINUTE, 4);
calendar.set(Calendar.SECOND, 5);
calendar.set(Calendar.MILLISECOND, 678);
| // Path: src/main/java/io/castle/client/internal/utils/Timestamp.java
// public class Timestamp {
// private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", new Locale("en", "US", "POSIX"));
//
// /**
// * Return an ISO 8601 combined date and time string for current date/time
// *
// * @return String with format "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
// */
// public static String timestamp() {
// return timestamp(new Date());
// }
//
// /**
// * Return an ISO 8601 combined date and time string for specified date/time
// *
// * @param date Date
// * @return String with format "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
// */
// public static String timestamp(Date date) {
// dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
// return dateFormat.format(date);
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
// Path: src/test/java/io/castle/client/TimestampTest.java
import io.castle.client.internal.utils.Timestamp;
import io.castle.client.model.CastleSdkConfigurationException;
import org.assertj.core.api.Assertions;
import org.assertj.core.util.DateUtil;
import org.junit.Test;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
package io.castle.client;
public class TimestampTest {
@Test
public void dateToTimestamp() {
//Given
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), new Locale("en", "US", "POSIX"));
calendar.set(Calendar.YEAR, 2019);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.DAY_OF_MONTH, 2);
calendar.set(Calendar.HOUR_OF_DAY, 3);
calendar.set(Calendar.MINUTE, 4);
calendar.set(Calendar.SECOND, 5);
calendar.set(Calendar.MILLISECOND, 678);
| String timestamp = Timestamp.timestamp(calendar.getTime()); |
castle/castle-java | src/test/java/io/castle/client/CastleDeviceApproveHttpTest.java | // Path: src/test/java/io/castle/client/utils/DeviceUtils.java
// public class DeviceUtils {
//
// public static final String DEVICE_TOKEN = "abcdefg12345";
// public static final double DEVICE_RISK = 0.000154;
// public static final String DEVICE_CREATED_AT = "2018-06-15T16:36:22.916Z";
// public static final String DEVICE_LAST_SEEN_AT = "2018-07-19T23:09:29.681Z";
// public static final String DEVICE_APPROVED_AT = null;
// public static final String DEVICE_ESCALATED_AT = null;
// public static final String DEVICE_MITIGATED_AT = null;
//
// public static final String CONTEXT_TYPE = "desktop";
// public static final String CONTEXT_IP = "1.1.1.1";
//
// public static final String USER_AGENT_FAMILY = "Opera";
// public static final String USER_AGENT_DEVICE = "Unknown";
// public static final String USER_AGENT_PLATFORM = "Mac OS X";
// public static final String USER_AGENT_OS = "Mac OS X 10.13.6";
// public static final String USER_AGENT_VERSION = "54.0.2952";
// public static final String USER_AGENT_BROWSER = "Opera";
// public static final String USER_AGENT_RAW = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51";
// public static final boolean USER_AGENT_MOBILE = false;
//
// public static CastleUserDevice createExpectedDevice() {
// CastleUserDevice device = new CastleUserDevice();
// device.setToken(DEVICE_TOKEN);
// device.setRisk(DEVICE_RISK);
// device.setCreatedAt(DEVICE_CREATED_AT);
// device.setLastSeenAt(DEVICE_LAST_SEEN_AT);
// device.setApprovedAt(null);
// device.setEscalatedAt(null);
// device.setMitigatedAt(null);
//
// CastleUserDeviceContext deviceContext = new CastleUserDeviceContext();
// deviceContext.setIp(CONTEXT_IP);
// deviceContext.setType(CONTEXT_TYPE);
//
// DeviceUserAgent userAgent = new DeviceUserAgent();
// userAgent.setFamily(USER_AGENT_FAMILY);
// userAgent.setDevice(USER_AGENT_DEVICE);
// userAgent.setPlatform(USER_AGENT_PLATFORM);
// userAgent.setOs(USER_AGENT_OS);
// userAgent.setVersion(USER_AGENT_VERSION);
// userAgent.setBrowser(USER_AGENT_BROWSER);
// userAgent.setRaw(USER_AGENT_RAW);
// userAgent.setMobile(USER_AGENT_MOBILE);
//
// deviceContext.setUserAgent(userAgent);
//
// device.setContext(deviceContext);
//
// return device;
// }
//
// public static CastleUserDevices createExpectedDevices() {
// CastleUserDevices devices = new CastleUserDevices();
// devices.setDevices(Arrays.asList(createExpectedDevice()));
// return devices;
// }
//
// public static String getDefaultDeviceJSON() {
// return "{\"token\":\"abcdefg12345\",\"risk\":0.000154,\"created_at\":\"2018-06-15T16:36:22.916Z\",\"last_seen_at\":\"2018-07-19T23:09:29.681Z\",\"approved_at\":null,\"escalated_at\":null,\"mitigated_at\":null,\"context\":{\"ip\":\"1.1.1.1\",\"location\":{\"country_code\":\"US\",\"country\":\"United States\",\"region\":\"New Jersey\",\"region_code\":\"NJ\",\"city\":\"Lyndhurst\",\"lat\":40.7923,\"lon\":-74.1001},\"user_agent\":{\"raw\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51\",\"browser\":\"Opera\",\"version\":\"54.0.2952\",\"os\":\"Mac OS X 10.13.6\",\"mobile\":false,\"platform\":\"Mac OS X\",\"device\":\"Unknown\",\"family\":\"Opera\"},\"type\":\"desktop\"}}";
// }
// }
| import io.castle.client.model.*;
import io.castle.client.utils.DeviceUtils;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import static okhttp3.mockwebserver.SocketPolicy.NO_RESPONSE; | package io.castle.client;
public class CastleDeviceApproveHttpTest extends AbstractCastleHttpLayerTest {
public CastleDeviceApproveHttpTest() {
super(new AuthenticateFailoverStrategy(AuthenticateAction.CHALLENGE));
}
@Test public void approveDevice() throws InterruptedException {
MockResponse mockResponse = new MockResponse(); | // Path: src/test/java/io/castle/client/utils/DeviceUtils.java
// public class DeviceUtils {
//
// public static final String DEVICE_TOKEN = "abcdefg12345";
// public static final double DEVICE_RISK = 0.000154;
// public static final String DEVICE_CREATED_AT = "2018-06-15T16:36:22.916Z";
// public static final String DEVICE_LAST_SEEN_AT = "2018-07-19T23:09:29.681Z";
// public static final String DEVICE_APPROVED_AT = null;
// public static final String DEVICE_ESCALATED_AT = null;
// public static final String DEVICE_MITIGATED_AT = null;
//
// public static final String CONTEXT_TYPE = "desktop";
// public static final String CONTEXT_IP = "1.1.1.1";
//
// public static final String USER_AGENT_FAMILY = "Opera";
// public static final String USER_AGENT_DEVICE = "Unknown";
// public static final String USER_AGENT_PLATFORM = "Mac OS X";
// public static final String USER_AGENT_OS = "Mac OS X 10.13.6";
// public static final String USER_AGENT_VERSION = "54.0.2952";
// public static final String USER_AGENT_BROWSER = "Opera";
// public static final String USER_AGENT_RAW = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51";
// public static final boolean USER_AGENT_MOBILE = false;
//
// public static CastleUserDevice createExpectedDevice() {
// CastleUserDevice device = new CastleUserDevice();
// device.setToken(DEVICE_TOKEN);
// device.setRisk(DEVICE_RISK);
// device.setCreatedAt(DEVICE_CREATED_AT);
// device.setLastSeenAt(DEVICE_LAST_SEEN_AT);
// device.setApprovedAt(null);
// device.setEscalatedAt(null);
// device.setMitigatedAt(null);
//
// CastleUserDeviceContext deviceContext = new CastleUserDeviceContext();
// deviceContext.setIp(CONTEXT_IP);
// deviceContext.setType(CONTEXT_TYPE);
//
// DeviceUserAgent userAgent = new DeviceUserAgent();
// userAgent.setFamily(USER_AGENT_FAMILY);
// userAgent.setDevice(USER_AGENT_DEVICE);
// userAgent.setPlatform(USER_AGENT_PLATFORM);
// userAgent.setOs(USER_AGENT_OS);
// userAgent.setVersion(USER_AGENT_VERSION);
// userAgent.setBrowser(USER_AGENT_BROWSER);
// userAgent.setRaw(USER_AGENT_RAW);
// userAgent.setMobile(USER_AGENT_MOBILE);
//
// deviceContext.setUserAgent(userAgent);
//
// device.setContext(deviceContext);
//
// return device;
// }
//
// public static CastleUserDevices createExpectedDevices() {
// CastleUserDevices devices = new CastleUserDevices();
// devices.setDevices(Arrays.asList(createExpectedDevice()));
// return devices;
// }
//
// public static String getDefaultDeviceJSON() {
// return "{\"token\":\"abcdefg12345\",\"risk\":0.000154,\"created_at\":\"2018-06-15T16:36:22.916Z\",\"last_seen_at\":\"2018-07-19T23:09:29.681Z\",\"approved_at\":null,\"escalated_at\":null,\"mitigated_at\":null,\"context\":{\"ip\":\"1.1.1.1\",\"location\":{\"country_code\":\"US\",\"country\":\"United States\",\"region\":\"New Jersey\",\"region_code\":\"NJ\",\"city\":\"Lyndhurst\",\"lat\":40.7923,\"lon\":-74.1001},\"user_agent\":{\"raw\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51\",\"browser\":\"Opera\",\"version\":\"54.0.2952\",\"os\":\"Mac OS X 10.13.6\",\"mobile\":false,\"platform\":\"Mac OS X\",\"device\":\"Unknown\",\"family\":\"Opera\"},\"type\":\"desktop\"}}";
// }
// }
// Path: src/test/java/io/castle/client/CastleDeviceApproveHttpTest.java
import io.castle.client.model.*;
import io.castle.client.utils.DeviceUtils;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import static okhttp3.mockwebserver.SocketPolicy.NO_RESPONSE;
package io.castle.client;
public class CastleDeviceApproveHttpTest extends AbstractCastleHttpLayerTest {
public CastleDeviceApproveHttpTest() {
super(new AuthenticateFailoverStrategy(AuthenticateAction.CHALLENGE));
}
@Test public void approveDevice() throws InterruptedException {
MockResponse mockResponse = new MockResponse(); | mockResponse.setBody(DeviceUtils.getDefaultDeviceJSON()); |
castle/castle-java | src/main/java/io/castle/client/internal/json/CastleHeadersDeserializer.java | // Path: src/main/java/io/castle/client/model/CastleHeader.java
// public class CastleHeader {
// private String key;
// private String value;
//
// public CastleHeader() {
// }
//
// public CastleHeader(String key, String value) {
// this.key = key;
// this.value = value;
// }
//
// public String getKey() {
// return key;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// CastleHeader that = (CastleHeader) o;
// return Objects.equals(key, that.key) &&
// Objects.equals(value, that.value);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(key, value);
// }
//
// @Override
// public String toString() {
// return "CastleHeader{" +
// "key='" + key + '\'' +
// ", value='" + value + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleHeaders.java
// public class CastleHeaders {
//
// private List<CastleHeader> headers;
//
// public List<CastleHeader> getHeaders() {
// return headers;
// }
//
// public static Builder builder() {
// return new Builder(new CastleHeaders());
// }
//
// public void setHeaders(List<CastleHeader> headers) {
// this.headers = headers;
// }
//
// public CastleHeaders(List<CastleHeader> headers) { this.headers = headers; }
//
// public CastleHeaders() {}
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// CastleHeaders that = (CastleHeaders) o;
// return Objects.equals(headers, that.headers);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(headers);
// }
//
// @Override
// public String toString() {
// return "CastleHeaders{" +
// "headers=" + headers +
// '}';
// }
//
// public static class Builder {
// private CastleHeaders headers;
// private ArrayList<CastleHeader> headerList;
//
// public Builder(CastleHeaders headers) {
// this.headers = headers;
// this.headerList = new ArrayList<>();
// }
//
// public CastleHeaders build() {
// headers.setHeaders(headerList);
// return headers;
// }
//
// public Builder add(String key, String value) {
// this.headerList.add(new CastleHeader(key, value));
// return this;
// }
// }
// }
| import com.google.common.collect.ImmutableList;
import com.google.gson.*;
import io.castle.client.model.CastleHeader;
import io.castle.client.model.CastleHeaders;
import java.lang.reflect.Type;
import java.util.Iterator;
import java.util.Set; | package io.castle.client.internal.json;
public class CastleHeadersDeserializer implements JsonDeserializer<CastleHeaders> {
@Override
public CastleHeaders deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
CastleHeaders headers = new CastleHeaders(); | // Path: src/main/java/io/castle/client/model/CastleHeader.java
// public class CastleHeader {
// private String key;
// private String value;
//
// public CastleHeader() {
// }
//
// public CastleHeader(String key, String value) {
// this.key = key;
// this.value = value;
// }
//
// public String getKey() {
// return key;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// CastleHeader that = (CastleHeader) o;
// return Objects.equals(key, that.key) &&
// Objects.equals(value, that.value);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(key, value);
// }
//
// @Override
// public String toString() {
// return "CastleHeader{" +
// "key='" + key + '\'' +
// ", value='" + value + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleHeaders.java
// public class CastleHeaders {
//
// private List<CastleHeader> headers;
//
// public List<CastleHeader> getHeaders() {
// return headers;
// }
//
// public static Builder builder() {
// return new Builder(new CastleHeaders());
// }
//
// public void setHeaders(List<CastleHeader> headers) {
// this.headers = headers;
// }
//
// public CastleHeaders(List<CastleHeader> headers) { this.headers = headers; }
//
// public CastleHeaders() {}
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// CastleHeaders that = (CastleHeaders) o;
// return Objects.equals(headers, that.headers);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(headers);
// }
//
// @Override
// public String toString() {
// return "CastleHeaders{" +
// "headers=" + headers +
// '}';
// }
//
// public static class Builder {
// private CastleHeaders headers;
// private ArrayList<CastleHeader> headerList;
//
// public Builder(CastleHeaders headers) {
// this.headers = headers;
// this.headerList = new ArrayList<>();
// }
//
// public CastleHeaders build() {
// headers.setHeaders(headerList);
// return headers;
// }
//
// public Builder add(String key, String value) {
// this.headerList.add(new CastleHeader(key, value));
// return this;
// }
// }
// }
// Path: src/main/java/io/castle/client/internal/json/CastleHeadersDeserializer.java
import com.google.common.collect.ImmutableList;
import com.google.gson.*;
import io.castle.client.model.CastleHeader;
import io.castle.client.model.CastleHeaders;
import java.lang.reflect.Type;
import java.util.Iterator;
import java.util.Set;
package io.castle.client.internal.json;
public class CastleHeadersDeserializer implements JsonDeserializer<CastleHeaders> {
@Override
public CastleHeaders deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
CastleHeaders headers = new CastleHeaders(); | ImmutableList.Builder<CastleHeader> builder = ImmutableList.builder(); |
castle/castle-java | src/main/java/io/castle/client/internal/config/CastleConfiguration.java | // Path: src/main/java/io/castle/client/internal/backend/CastleBackendProvider.java
// public enum CastleBackendProvider {
// OKHTTP
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleRuntimeException.java
// public class CastleRuntimeException extends RuntimeException {
//
// public CastleRuntimeException(Throwable throwable) {
// super(throwable);
// }
//
// public CastleRuntimeException(String message) {
// super(message);
// }
//
// public CastleRuntimeException(Response response) {
// super(response.toString());
// }
// }
| import io.castle.client.internal.backend.CastleBackendProvider;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleRuntimeException;
import java.util.List; | package io.castle.client.internal.config;
/**
* Application level settings used by the SDK singleton.
* <p>
* Configuration values will be loaded from the environment or from the class path by a call to
* {@link ConfigurationLoader#loadConfiguration()}.
*/
public class CastleConfiguration {
/**
* Endpoint of the Castle API.
*/
private final String apiBaseUrl;
/**
* Timeout after which a request fails.
*/
private final int timeout;
/**
* Strategy for returning a {@code verdict} when an authenticate call fails.
*/ | // Path: src/main/java/io/castle/client/internal/backend/CastleBackendProvider.java
// public enum CastleBackendProvider {
// OKHTTP
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleRuntimeException.java
// public class CastleRuntimeException extends RuntimeException {
//
// public CastleRuntimeException(Throwable throwable) {
// super(throwable);
// }
//
// public CastleRuntimeException(String message) {
// super(message);
// }
//
// public CastleRuntimeException(Response response) {
// super(response.toString());
// }
// }
// Path: src/main/java/io/castle/client/internal/config/CastleConfiguration.java
import io.castle.client.internal.backend.CastleBackendProvider;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleRuntimeException;
import java.util.List;
package io.castle.client.internal.config;
/**
* Application level settings used by the SDK singleton.
* <p>
* Configuration values will be loaded from the environment or from the class path by a call to
* {@link ConfigurationLoader#loadConfiguration()}.
*/
public class CastleConfiguration {
/**
* Endpoint of the Castle API.
*/
private final String apiBaseUrl;
/**
* Timeout after which a request fails.
*/
private final int timeout;
/**
* Strategy for returning a {@code verdict} when an authenticate call fails.
*/ | private final AuthenticateFailoverStrategy authenticateFailoverStrategy; |
castle/castle-java | src/main/java/io/castle/client/internal/config/CastleConfiguration.java | // Path: src/main/java/io/castle/client/internal/backend/CastleBackendProvider.java
// public enum CastleBackendProvider {
// OKHTTP
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleRuntimeException.java
// public class CastleRuntimeException extends RuntimeException {
//
// public CastleRuntimeException(Throwable throwable) {
// super(throwable);
// }
//
// public CastleRuntimeException(String message) {
// super(message);
// }
//
// public CastleRuntimeException(Response response) {
// super(response.toString());
// }
// }
| import io.castle.client.internal.backend.CastleBackendProvider;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleRuntimeException;
import java.util.List; | package io.castle.client.internal.config;
/**
* Application level settings used by the SDK singleton.
* <p>
* Configuration values will be loaded from the environment or from the class path by a call to
* {@link ConfigurationLoader#loadConfiguration()}.
*/
public class CastleConfiguration {
/**
* Endpoint of the Castle API.
*/
private final String apiBaseUrl;
/**
* Timeout after which a request fails.
*/
private final int timeout;
/**
* Strategy for returning a {@code verdict} when an authenticate call fails.
*/
private final AuthenticateFailoverStrategy authenticateFailoverStrategy;
/**
* List of headers that will get passed to the {@code CastleContext} unless they are denyListed.
*/
private final List<String> allowListHeaders;
/**
* List of headers that will never get passed to the {@code CastleContext} when built from an HTTP request.
*/
private final List<String> denyListHeaders;
/**
* Secret associated to a Castle account.
*/
private final String apiSecret;
/**
* Identifier used for authentication purposes for requests to the Castle API.
*/
private final String castleAppId;
/**
* HTTP layer that will be used for calls to the Castle API
*/ | // Path: src/main/java/io/castle/client/internal/backend/CastleBackendProvider.java
// public enum CastleBackendProvider {
// OKHTTP
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleRuntimeException.java
// public class CastleRuntimeException extends RuntimeException {
//
// public CastleRuntimeException(Throwable throwable) {
// super(throwable);
// }
//
// public CastleRuntimeException(String message) {
// super(message);
// }
//
// public CastleRuntimeException(Response response) {
// super(response.toString());
// }
// }
// Path: src/main/java/io/castle/client/internal/config/CastleConfiguration.java
import io.castle.client.internal.backend.CastleBackendProvider;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleRuntimeException;
import java.util.List;
package io.castle.client.internal.config;
/**
* Application level settings used by the SDK singleton.
* <p>
* Configuration values will be loaded from the environment or from the class path by a call to
* {@link ConfigurationLoader#loadConfiguration()}.
*/
public class CastleConfiguration {
/**
* Endpoint of the Castle API.
*/
private final String apiBaseUrl;
/**
* Timeout after which a request fails.
*/
private final int timeout;
/**
* Strategy for returning a {@code verdict} when an authenticate call fails.
*/
private final AuthenticateFailoverStrategy authenticateFailoverStrategy;
/**
* List of headers that will get passed to the {@code CastleContext} unless they are denyListed.
*/
private final List<String> allowListHeaders;
/**
* List of headers that will never get passed to the {@code CastleContext} when built from an HTTP request.
*/
private final List<String> denyListHeaders;
/**
* Secret associated to a Castle account.
*/
private final String apiSecret;
/**
* Identifier used for authentication purposes for requests to the Castle API.
*/
private final String castleAppId;
/**
* HTTP layer that will be used for calls to the Castle API
*/ | private final CastleBackendProvider backendProvider; |
castle/castle-java | src/main/java/io/castle/client/internal/config/CastleConfiguration.java | // Path: src/main/java/io/castle/client/internal/backend/CastleBackendProvider.java
// public enum CastleBackendProvider {
// OKHTTP
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleRuntimeException.java
// public class CastleRuntimeException extends RuntimeException {
//
// public CastleRuntimeException(Throwable throwable) {
// super(throwable);
// }
//
// public CastleRuntimeException(String message) {
// super(message);
// }
//
// public CastleRuntimeException(Response response) {
// super(response.toString());
// }
// }
| import io.castle.client.internal.backend.CastleBackendProvider;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleRuntimeException;
import java.util.List; | public String getApiBaseUrl() {
return apiBaseUrl;
}
public int getTimeout() {
return timeout;
}
public AuthenticateFailoverStrategy getAuthenticateFailoverStrategy() {
return authenticateFailoverStrategy;
}
public List<String> getAllowListHeaders() {
return allowListHeaders;
}
public List<String> getDenyListHeaders() {
return denyListHeaders;
}
public String getApiSecret() {
return apiSecret;
}
/**
* Gets the App Id, when it exists
*
* @return A string representing the AppID
* @throws CastleRuntimeException when there is no App Id
*/ | // Path: src/main/java/io/castle/client/internal/backend/CastleBackendProvider.java
// public enum CastleBackendProvider {
// OKHTTP
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleRuntimeException.java
// public class CastleRuntimeException extends RuntimeException {
//
// public CastleRuntimeException(Throwable throwable) {
// super(throwable);
// }
//
// public CastleRuntimeException(String message) {
// super(message);
// }
//
// public CastleRuntimeException(Response response) {
// super(response.toString());
// }
// }
// Path: src/main/java/io/castle/client/internal/config/CastleConfiguration.java
import io.castle.client.internal.backend.CastleBackendProvider;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleRuntimeException;
import java.util.List;
public String getApiBaseUrl() {
return apiBaseUrl;
}
public int getTimeout() {
return timeout;
}
public AuthenticateFailoverStrategy getAuthenticateFailoverStrategy() {
return authenticateFailoverStrategy;
}
public List<String> getAllowListHeaders() {
return allowListHeaders;
}
public List<String> getDenyListHeaders() {
return denyListHeaders;
}
public String getApiSecret() {
return apiSecret;
}
/**
* Gets the App Id, when it exists
*
* @return A string representing the AppID
* @throws CastleRuntimeException when there is no App Id
*/ | public String getCastleAppId() throws CastleRuntimeException { |
castle/castle-java | src/test/java/io/castle/client/CastleDeviceHttpTest.java | // Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
//
// Path: src/test/java/io/castle/client/utils/DeviceUtils.java
// public class DeviceUtils {
//
// public static final String DEVICE_TOKEN = "abcdefg12345";
// public static final double DEVICE_RISK = 0.000154;
// public static final String DEVICE_CREATED_AT = "2018-06-15T16:36:22.916Z";
// public static final String DEVICE_LAST_SEEN_AT = "2018-07-19T23:09:29.681Z";
// public static final String DEVICE_APPROVED_AT = null;
// public static final String DEVICE_ESCALATED_AT = null;
// public static final String DEVICE_MITIGATED_AT = null;
//
// public static final String CONTEXT_TYPE = "desktop";
// public static final String CONTEXT_IP = "1.1.1.1";
//
// public static final String USER_AGENT_FAMILY = "Opera";
// public static final String USER_AGENT_DEVICE = "Unknown";
// public static final String USER_AGENT_PLATFORM = "Mac OS X";
// public static final String USER_AGENT_OS = "Mac OS X 10.13.6";
// public static final String USER_AGENT_VERSION = "54.0.2952";
// public static final String USER_AGENT_BROWSER = "Opera";
// public static final String USER_AGENT_RAW = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51";
// public static final boolean USER_AGENT_MOBILE = false;
//
// public static CastleUserDevice createExpectedDevice() {
// CastleUserDevice device = new CastleUserDevice();
// device.setToken(DEVICE_TOKEN);
// device.setRisk(DEVICE_RISK);
// device.setCreatedAt(DEVICE_CREATED_AT);
// device.setLastSeenAt(DEVICE_LAST_SEEN_AT);
// device.setApprovedAt(null);
// device.setEscalatedAt(null);
// device.setMitigatedAt(null);
//
// CastleUserDeviceContext deviceContext = new CastleUserDeviceContext();
// deviceContext.setIp(CONTEXT_IP);
// deviceContext.setType(CONTEXT_TYPE);
//
// DeviceUserAgent userAgent = new DeviceUserAgent();
// userAgent.setFamily(USER_AGENT_FAMILY);
// userAgent.setDevice(USER_AGENT_DEVICE);
// userAgent.setPlatform(USER_AGENT_PLATFORM);
// userAgent.setOs(USER_AGENT_OS);
// userAgent.setVersion(USER_AGENT_VERSION);
// userAgent.setBrowser(USER_AGENT_BROWSER);
// userAgent.setRaw(USER_AGENT_RAW);
// userAgent.setMobile(USER_AGENT_MOBILE);
//
// deviceContext.setUserAgent(userAgent);
//
// device.setContext(deviceContext);
//
// return device;
// }
//
// public static CastleUserDevices createExpectedDevices() {
// CastleUserDevices devices = new CastleUserDevices();
// devices.setDevices(Arrays.asList(createExpectedDevice()));
// return devices;
// }
//
// public static String getDefaultDeviceJSON() {
// return "{\"token\":\"abcdefg12345\",\"risk\":0.000154,\"created_at\":\"2018-06-15T16:36:22.916Z\",\"last_seen_at\":\"2018-07-19T23:09:29.681Z\",\"approved_at\":null,\"escalated_at\":null,\"mitigated_at\":null,\"context\":{\"ip\":\"1.1.1.1\",\"location\":{\"country_code\":\"US\",\"country\":\"United States\",\"region\":\"New Jersey\",\"region_code\":\"NJ\",\"city\":\"Lyndhurst\",\"lat\":40.7923,\"lon\":-74.1001},\"user_agent\":{\"raw\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51\",\"browser\":\"Opera\",\"version\":\"54.0.2952\",\"os\":\"Mac OS X 10.13.6\",\"mobile\":false,\"platform\":\"Mac OS X\",\"device\":\"Unknown\",\"family\":\"Opera\"},\"type\":\"desktop\"}}";
// }
// }
| import io.castle.client.internal.json.CastleGsonModel;
import io.castle.client.model.*;
import io.castle.client.utils.DeviceUtils;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import static okhttp3.mockwebserver.SocketPolicy.NO_RESPONSE; | package io.castle.client;
public class CastleDeviceHttpTest extends AbstractCastleHttpLayerTest {
public CastleDeviceHttpTest() {
super(new AuthenticateFailoverStrategy(AuthenticateAction.CHALLENGE));
}
@Test public void getDevice() throws Exception {
MockResponse mockResponse = new MockResponse(); | // Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
//
// Path: src/test/java/io/castle/client/utils/DeviceUtils.java
// public class DeviceUtils {
//
// public static final String DEVICE_TOKEN = "abcdefg12345";
// public static final double DEVICE_RISK = 0.000154;
// public static final String DEVICE_CREATED_AT = "2018-06-15T16:36:22.916Z";
// public static final String DEVICE_LAST_SEEN_AT = "2018-07-19T23:09:29.681Z";
// public static final String DEVICE_APPROVED_AT = null;
// public static final String DEVICE_ESCALATED_AT = null;
// public static final String DEVICE_MITIGATED_AT = null;
//
// public static final String CONTEXT_TYPE = "desktop";
// public static final String CONTEXT_IP = "1.1.1.1";
//
// public static final String USER_AGENT_FAMILY = "Opera";
// public static final String USER_AGENT_DEVICE = "Unknown";
// public static final String USER_AGENT_PLATFORM = "Mac OS X";
// public static final String USER_AGENT_OS = "Mac OS X 10.13.6";
// public static final String USER_AGENT_VERSION = "54.0.2952";
// public static final String USER_AGENT_BROWSER = "Opera";
// public static final String USER_AGENT_RAW = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51";
// public static final boolean USER_AGENT_MOBILE = false;
//
// public static CastleUserDevice createExpectedDevice() {
// CastleUserDevice device = new CastleUserDevice();
// device.setToken(DEVICE_TOKEN);
// device.setRisk(DEVICE_RISK);
// device.setCreatedAt(DEVICE_CREATED_AT);
// device.setLastSeenAt(DEVICE_LAST_SEEN_AT);
// device.setApprovedAt(null);
// device.setEscalatedAt(null);
// device.setMitigatedAt(null);
//
// CastleUserDeviceContext deviceContext = new CastleUserDeviceContext();
// deviceContext.setIp(CONTEXT_IP);
// deviceContext.setType(CONTEXT_TYPE);
//
// DeviceUserAgent userAgent = new DeviceUserAgent();
// userAgent.setFamily(USER_AGENT_FAMILY);
// userAgent.setDevice(USER_AGENT_DEVICE);
// userAgent.setPlatform(USER_AGENT_PLATFORM);
// userAgent.setOs(USER_AGENT_OS);
// userAgent.setVersion(USER_AGENT_VERSION);
// userAgent.setBrowser(USER_AGENT_BROWSER);
// userAgent.setRaw(USER_AGENT_RAW);
// userAgent.setMobile(USER_AGENT_MOBILE);
//
// deviceContext.setUserAgent(userAgent);
//
// device.setContext(deviceContext);
//
// return device;
// }
//
// public static CastleUserDevices createExpectedDevices() {
// CastleUserDevices devices = new CastleUserDevices();
// devices.setDevices(Arrays.asList(createExpectedDevice()));
// return devices;
// }
//
// public static String getDefaultDeviceJSON() {
// return "{\"token\":\"abcdefg12345\",\"risk\":0.000154,\"created_at\":\"2018-06-15T16:36:22.916Z\",\"last_seen_at\":\"2018-07-19T23:09:29.681Z\",\"approved_at\":null,\"escalated_at\":null,\"mitigated_at\":null,\"context\":{\"ip\":\"1.1.1.1\",\"location\":{\"country_code\":\"US\",\"country\":\"United States\",\"region\":\"New Jersey\",\"region_code\":\"NJ\",\"city\":\"Lyndhurst\",\"lat\":40.7923,\"lon\":-74.1001},\"user_agent\":{\"raw\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51\",\"browser\":\"Opera\",\"version\":\"54.0.2952\",\"os\":\"Mac OS X 10.13.6\",\"mobile\":false,\"platform\":\"Mac OS X\",\"device\":\"Unknown\",\"family\":\"Opera\"},\"type\":\"desktop\"}}";
// }
// }
// Path: src/test/java/io/castle/client/CastleDeviceHttpTest.java
import io.castle.client.internal.json.CastleGsonModel;
import io.castle.client.model.*;
import io.castle.client.utils.DeviceUtils;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import static okhttp3.mockwebserver.SocketPolicy.NO_RESPONSE;
package io.castle.client;
public class CastleDeviceHttpTest extends AbstractCastleHttpLayerTest {
public CastleDeviceHttpTest() {
super(new AuthenticateFailoverStrategy(AuthenticateAction.CHALLENGE));
}
@Test public void getDevice() throws Exception {
MockResponse mockResponse = new MockResponse(); | mockResponse.setBody(DeviceUtils.getDefaultDeviceJSON()); |
castle/castle-java | src/test/java/io/castle/client/CastleTest.java | // Path: src/main/java/io/castle/client/internal/backend/RestApiFactory.java
// public interface RestApiFactory {
//
// RestApi buildBackend();
// }
//
// Path: src/main/java/io/castle/client/internal/config/CastleConfiguration.java
// public class CastleConfiguration {
//
// /**
// * Endpoint of the Castle API.
// */
// private final String apiBaseUrl;
//
// /**
// * Timeout after which a request fails.
// */
// private final int timeout;
//
// /**
// * Strategy for returning a {@code verdict} when an authenticate call fails.
// */
// private final AuthenticateFailoverStrategy authenticateFailoverStrategy;
//
// /**
// * List of headers that will get passed to the {@code CastleContext} unless they are denyListed.
// */
// private final List<String> allowListHeaders;
//
// /**
// * List of headers that will never get passed to the {@code CastleContext} when built from an HTTP request.
// */
// private final List<String> denyListHeaders;
//
// /**
// * Secret associated to a Castle account.
// */
// private final String apiSecret;
//
// /**
// * Identifier used for authentication purposes for requests to the Castle API.
// */
// private final String castleAppId;
//
// /**
// * HTTP layer that will be used for calls to the Castle API
// */
// private final CastleBackendProvider backendProvider;
//
// /**
// * Flag to add logging information on HTTP backend.
// */
// private final boolean logHttpRequests;
//
// private final List<String> ipHeaders;
//
// /**
// * Max number of simultaneous requests to Castle
// */
// private final int maxRequests;
//
// public CastleConfiguration(String apiBaseUrl, int timeout, AuthenticateFailoverStrategy authenticateFailoverStrategy, List<String> allowListHeaders, List<String> denyListHeaders, String apiSecret, String castleAppId, CastleBackendProvider backendProvider, boolean logHttpRequests, List<String> ipHeaders, Integer maxRequests) {
// this.apiBaseUrl = apiBaseUrl;
// this.timeout = timeout;
// this.authenticateFailoverStrategy = authenticateFailoverStrategy;
// this.allowListHeaders = allowListHeaders;
// this.denyListHeaders = denyListHeaders;
// this.apiSecret = apiSecret;
// this.castleAppId = castleAppId;
// this.backendProvider = backendProvider;
// this.logHttpRequests = logHttpRequests;
// this.ipHeaders = ipHeaders;
// this.maxRequests = maxRequests;
// }
//
// public String getApiBaseUrl() {
// return apiBaseUrl;
// }
//
// public int getTimeout() {
// return timeout;
// }
//
// public AuthenticateFailoverStrategy getAuthenticateFailoverStrategy() {
// return authenticateFailoverStrategy;
// }
//
// public List<String> getAllowListHeaders() {
// return allowListHeaders;
// }
//
// public List<String> getDenyListHeaders() {
// return denyListHeaders;
// }
//
// public String getApiSecret() {
// return apiSecret;
// }
//
// /**
// * Gets the App Id, when it exists
// *
// * @return A string representing the AppID
// * @throws CastleRuntimeException when there is no App Id
// */
// public String getCastleAppId() throws CastleRuntimeException {
// if (castleAppId == null || castleAppId.isEmpty()) {
// throw new CastleRuntimeException("AppId was not specified");
// } else {
// return castleAppId;
// }
// }
//
// public CastleBackendProvider getBackendProvider() {
// return backendProvider;
// }
//
// public boolean isLogHttpRequests() {
// return logHttpRequests;
// }
//
// public List<String> getIpHeaders() {
// return ipHeaders;
// }
//
// public int getMaxRequests() {
// return maxRequests;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
| import io.castle.client.internal.backend.RestApiFactory;
import io.castle.client.internal.config.CastleConfiguration;
import io.castle.client.model.CastleSdkConfigurationException;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.Mockito; | package io.castle.client;
public class CastleTest {
@Test | // Path: src/main/java/io/castle/client/internal/backend/RestApiFactory.java
// public interface RestApiFactory {
//
// RestApi buildBackend();
// }
//
// Path: src/main/java/io/castle/client/internal/config/CastleConfiguration.java
// public class CastleConfiguration {
//
// /**
// * Endpoint of the Castle API.
// */
// private final String apiBaseUrl;
//
// /**
// * Timeout after which a request fails.
// */
// private final int timeout;
//
// /**
// * Strategy for returning a {@code verdict} when an authenticate call fails.
// */
// private final AuthenticateFailoverStrategy authenticateFailoverStrategy;
//
// /**
// * List of headers that will get passed to the {@code CastleContext} unless they are denyListed.
// */
// private final List<String> allowListHeaders;
//
// /**
// * List of headers that will never get passed to the {@code CastleContext} when built from an HTTP request.
// */
// private final List<String> denyListHeaders;
//
// /**
// * Secret associated to a Castle account.
// */
// private final String apiSecret;
//
// /**
// * Identifier used for authentication purposes for requests to the Castle API.
// */
// private final String castleAppId;
//
// /**
// * HTTP layer that will be used for calls to the Castle API
// */
// private final CastleBackendProvider backendProvider;
//
// /**
// * Flag to add logging information on HTTP backend.
// */
// private final boolean logHttpRequests;
//
// private final List<String> ipHeaders;
//
// /**
// * Max number of simultaneous requests to Castle
// */
// private final int maxRequests;
//
// public CastleConfiguration(String apiBaseUrl, int timeout, AuthenticateFailoverStrategy authenticateFailoverStrategy, List<String> allowListHeaders, List<String> denyListHeaders, String apiSecret, String castleAppId, CastleBackendProvider backendProvider, boolean logHttpRequests, List<String> ipHeaders, Integer maxRequests) {
// this.apiBaseUrl = apiBaseUrl;
// this.timeout = timeout;
// this.authenticateFailoverStrategy = authenticateFailoverStrategy;
// this.allowListHeaders = allowListHeaders;
// this.denyListHeaders = denyListHeaders;
// this.apiSecret = apiSecret;
// this.castleAppId = castleAppId;
// this.backendProvider = backendProvider;
// this.logHttpRequests = logHttpRequests;
// this.ipHeaders = ipHeaders;
// this.maxRequests = maxRequests;
// }
//
// public String getApiBaseUrl() {
// return apiBaseUrl;
// }
//
// public int getTimeout() {
// return timeout;
// }
//
// public AuthenticateFailoverStrategy getAuthenticateFailoverStrategy() {
// return authenticateFailoverStrategy;
// }
//
// public List<String> getAllowListHeaders() {
// return allowListHeaders;
// }
//
// public List<String> getDenyListHeaders() {
// return denyListHeaders;
// }
//
// public String getApiSecret() {
// return apiSecret;
// }
//
// /**
// * Gets the App Id, when it exists
// *
// * @return A string representing the AppID
// * @throws CastleRuntimeException when there is no App Id
// */
// public String getCastleAppId() throws CastleRuntimeException {
// if (castleAppId == null || castleAppId.isEmpty()) {
// throw new CastleRuntimeException("AppId was not specified");
// } else {
// return castleAppId;
// }
// }
//
// public CastleBackendProvider getBackendProvider() {
// return backendProvider;
// }
//
// public boolean isLogHttpRequests() {
// return logHttpRequests;
// }
//
// public List<String> getIpHeaders() {
// return ipHeaders;
// }
//
// public int getMaxRequests() {
// return maxRequests;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
// Path: src/test/java/io/castle/client/CastleTest.java
import io.castle.client.internal.backend.RestApiFactory;
import io.castle.client.internal.config.CastleConfiguration;
import io.castle.client.model.CastleSdkConfigurationException;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.Mockito;
package io.castle.client;
public class CastleTest {
@Test | public void sdkVerificationPassBecauseOfClassPathConfiguration() throws CastleSdkConfigurationException { |
castle/castle-java | src/test/java/io/castle/client/CastleTest.java | // Path: src/main/java/io/castle/client/internal/backend/RestApiFactory.java
// public interface RestApiFactory {
//
// RestApi buildBackend();
// }
//
// Path: src/main/java/io/castle/client/internal/config/CastleConfiguration.java
// public class CastleConfiguration {
//
// /**
// * Endpoint of the Castle API.
// */
// private final String apiBaseUrl;
//
// /**
// * Timeout after which a request fails.
// */
// private final int timeout;
//
// /**
// * Strategy for returning a {@code verdict} when an authenticate call fails.
// */
// private final AuthenticateFailoverStrategy authenticateFailoverStrategy;
//
// /**
// * List of headers that will get passed to the {@code CastleContext} unless they are denyListed.
// */
// private final List<String> allowListHeaders;
//
// /**
// * List of headers that will never get passed to the {@code CastleContext} when built from an HTTP request.
// */
// private final List<String> denyListHeaders;
//
// /**
// * Secret associated to a Castle account.
// */
// private final String apiSecret;
//
// /**
// * Identifier used for authentication purposes for requests to the Castle API.
// */
// private final String castleAppId;
//
// /**
// * HTTP layer that will be used for calls to the Castle API
// */
// private final CastleBackendProvider backendProvider;
//
// /**
// * Flag to add logging information on HTTP backend.
// */
// private final boolean logHttpRequests;
//
// private final List<String> ipHeaders;
//
// /**
// * Max number of simultaneous requests to Castle
// */
// private final int maxRequests;
//
// public CastleConfiguration(String apiBaseUrl, int timeout, AuthenticateFailoverStrategy authenticateFailoverStrategy, List<String> allowListHeaders, List<String> denyListHeaders, String apiSecret, String castleAppId, CastleBackendProvider backendProvider, boolean logHttpRequests, List<String> ipHeaders, Integer maxRequests) {
// this.apiBaseUrl = apiBaseUrl;
// this.timeout = timeout;
// this.authenticateFailoverStrategy = authenticateFailoverStrategy;
// this.allowListHeaders = allowListHeaders;
// this.denyListHeaders = denyListHeaders;
// this.apiSecret = apiSecret;
// this.castleAppId = castleAppId;
// this.backendProvider = backendProvider;
// this.logHttpRequests = logHttpRequests;
// this.ipHeaders = ipHeaders;
// this.maxRequests = maxRequests;
// }
//
// public String getApiBaseUrl() {
// return apiBaseUrl;
// }
//
// public int getTimeout() {
// return timeout;
// }
//
// public AuthenticateFailoverStrategy getAuthenticateFailoverStrategy() {
// return authenticateFailoverStrategy;
// }
//
// public List<String> getAllowListHeaders() {
// return allowListHeaders;
// }
//
// public List<String> getDenyListHeaders() {
// return denyListHeaders;
// }
//
// public String getApiSecret() {
// return apiSecret;
// }
//
// /**
// * Gets the App Id, when it exists
// *
// * @return A string representing the AppID
// * @throws CastleRuntimeException when there is no App Id
// */
// public String getCastleAppId() throws CastleRuntimeException {
// if (castleAppId == null || castleAppId.isEmpty()) {
// throw new CastleRuntimeException("AppId was not specified");
// } else {
// return castleAppId;
// }
// }
//
// public CastleBackendProvider getBackendProvider() {
// return backendProvider;
// }
//
// public boolean isLogHttpRequests() {
// return logHttpRequests;
// }
//
// public List<String> getIpHeaders() {
// return ipHeaders;
// }
//
// public int getMaxRequests() {
// return maxRequests;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
| import io.castle.client.internal.backend.RestApiFactory;
import io.castle.client.internal.config.CastleConfiguration;
import io.castle.client.model.CastleSdkConfigurationException;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.Mockito; | package io.castle.client;
public class CastleTest {
@Test
public void sdkVerificationPassBecauseOfClassPathConfiguration() throws CastleSdkConfigurationException {
//Given
//When
Castle.verifySdkConfigurationAndInitialize();
//Then
// No exception is throw, because the tests classpath contains the file castle_sdk.properties
}
/**
*
* Properties are loaded from the default configuration file in test/resources/castle_sdk.properties
*
* @throws CastleSdkConfigurationException
*/
@Test
public void sdkOnTestLoadTheCorrectConfiguration() throws CastleSdkConfigurationException {
//When the sdk is initiated
Castle sdk = Castle.verifySdkConfigurationAndInitialize();
//Then the configuration match the expected values from the class path properties | // Path: src/main/java/io/castle/client/internal/backend/RestApiFactory.java
// public interface RestApiFactory {
//
// RestApi buildBackend();
// }
//
// Path: src/main/java/io/castle/client/internal/config/CastleConfiguration.java
// public class CastleConfiguration {
//
// /**
// * Endpoint of the Castle API.
// */
// private final String apiBaseUrl;
//
// /**
// * Timeout after which a request fails.
// */
// private final int timeout;
//
// /**
// * Strategy for returning a {@code verdict} when an authenticate call fails.
// */
// private final AuthenticateFailoverStrategy authenticateFailoverStrategy;
//
// /**
// * List of headers that will get passed to the {@code CastleContext} unless they are denyListed.
// */
// private final List<String> allowListHeaders;
//
// /**
// * List of headers that will never get passed to the {@code CastleContext} when built from an HTTP request.
// */
// private final List<String> denyListHeaders;
//
// /**
// * Secret associated to a Castle account.
// */
// private final String apiSecret;
//
// /**
// * Identifier used for authentication purposes for requests to the Castle API.
// */
// private final String castleAppId;
//
// /**
// * HTTP layer that will be used for calls to the Castle API
// */
// private final CastleBackendProvider backendProvider;
//
// /**
// * Flag to add logging information on HTTP backend.
// */
// private final boolean logHttpRequests;
//
// private final List<String> ipHeaders;
//
// /**
// * Max number of simultaneous requests to Castle
// */
// private final int maxRequests;
//
// public CastleConfiguration(String apiBaseUrl, int timeout, AuthenticateFailoverStrategy authenticateFailoverStrategy, List<String> allowListHeaders, List<String> denyListHeaders, String apiSecret, String castleAppId, CastleBackendProvider backendProvider, boolean logHttpRequests, List<String> ipHeaders, Integer maxRequests) {
// this.apiBaseUrl = apiBaseUrl;
// this.timeout = timeout;
// this.authenticateFailoverStrategy = authenticateFailoverStrategy;
// this.allowListHeaders = allowListHeaders;
// this.denyListHeaders = denyListHeaders;
// this.apiSecret = apiSecret;
// this.castleAppId = castleAppId;
// this.backendProvider = backendProvider;
// this.logHttpRequests = logHttpRequests;
// this.ipHeaders = ipHeaders;
// this.maxRequests = maxRequests;
// }
//
// public String getApiBaseUrl() {
// return apiBaseUrl;
// }
//
// public int getTimeout() {
// return timeout;
// }
//
// public AuthenticateFailoverStrategy getAuthenticateFailoverStrategy() {
// return authenticateFailoverStrategy;
// }
//
// public List<String> getAllowListHeaders() {
// return allowListHeaders;
// }
//
// public List<String> getDenyListHeaders() {
// return denyListHeaders;
// }
//
// public String getApiSecret() {
// return apiSecret;
// }
//
// /**
// * Gets the App Id, when it exists
// *
// * @return A string representing the AppID
// * @throws CastleRuntimeException when there is no App Id
// */
// public String getCastleAppId() throws CastleRuntimeException {
// if (castleAppId == null || castleAppId.isEmpty()) {
// throw new CastleRuntimeException("AppId was not specified");
// } else {
// return castleAppId;
// }
// }
//
// public CastleBackendProvider getBackendProvider() {
// return backendProvider;
// }
//
// public boolean isLogHttpRequests() {
// return logHttpRequests;
// }
//
// public List<String> getIpHeaders() {
// return ipHeaders;
// }
//
// public int getMaxRequests() {
// return maxRequests;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
// Path: src/test/java/io/castle/client/CastleTest.java
import io.castle.client.internal.backend.RestApiFactory;
import io.castle.client.internal.config.CastleConfiguration;
import io.castle.client.model.CastleSdkConfigurationException;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.Mockito;
package io.castle.client;
public class CastleTest {
@Test
public void sdkVerificationPassBecauseOfClassPathConfiguration() throws CastleSdkConfigurationException {
//Given
//When
Castle.verifySdkConfigurationAndInitialize();
//Then
// No exception is throw, because the tests classpath contains the file castle_sdk.properties
}
/**
*
* Properties are loaded from the default configuration file in test/resources/castle_sdk.properties
*
* @throws CastleSdkConfigurationException
*/
@Test
public void sdkOnTestLoadTheCorrectConfiguration() throws CastleSdkConfigurationException {
//When the sdk is initiated
Castle sdk = Castle.verifySdkConfigurationAndInitialize();
//Then the configuration match the expected values from the class path properties | CastleConfiguration sdkConfiguration = sdk.getSdkConfiguration(); |
castle/castle-java | src/test/java/io/castle/client/CastleTest.java | // Path: src/main/java/io/castle/client/internal/backend/RestApiFactory.java
// public interface RestApiFactory {
//
// RestApi buildBackend();
// }
//
// Path: src/main/java/io/castle/client/internal/config/CastleConfiguration.java
// public class CastleConfiguration {
//
// /**
// * Endpoint of the Castle API.
// */
// private final String apiBaseUrl;
//
// /**
// * Timeout after which a request fails.
// */
// private final int timeout;
//
// /**
// * Strategy for returning a {@code verdict} when an authenticate call fails.
// */
// private final AuthenticateFailoverStrategy authenticateFailoverStrategy;
//
// /**
// * List of headers that will get passed to the {@code CastleContext} unless they are denyListed.
// */
// private final List<String> allowListHeaders;
//
// /**
// * List of headers that will never get passed to the {@code CastleContext} when built from an HTTP request.
// */
// private final List<String> denyListHeaders;
//
// /**
// * Secret associated to a Castle account.
// */
// private final String apiSecret;
//
// /**
// * Identifier used for authentication purposes for requests to the Castle API.
// */
// private final String castleAppId;
//
// /**
// * HTTP layer that will be used for calls to the Castle API
// */
// private final CastleBackendProvider backendProvider;
//
// /**
// * Flag to add logging information on HTTP backend.
// */
// private final boolean logHttpRequests;
//
// private final List<String> ipHeaders;
//
// /**
// * Max number of simultaneous requests to Castle
// */
// private final int maxRequests;
//
// public CastleConfiguration(String apiBaseUrl, int timeout, AuthenticateFailoverStrategy authenticateFailoverStrategy, List<String> allowListHeaders, List<String> denyListHeaders, String apiSecret, String castleAppId, CastleBackendProvider backendProvider, boolean logHttpRequests, List<String> ipHeaders, Integer maxRequests) {
// this.apiBaseUrl = apiBaseUrl;
// this.timeout = timeout;
// this.authenticateFailoverStrategy = authenticateFailoverStrategy;
// this.allowListHeaders = allowListHeaders;
// this.denyListHeaders = denyListHeaders;
// this.apiSecret = apiSecret;
// this.castleAppId = castleAppId;
// this.backendProvider = backendProvider;
// this.logHttpRequests = logHttpRequests;
// this.ipHeaders = ipHeaders;
// this.maxRequests = maxRequests;
// }
//
// public String getApiBaseUrl() {
// return apiBaseUrl;
// }
//
// public int getTimeout() {
// return timeout;
// }
//
// public AuthenticateFailoverStrategy getAuthenticateFailoverStrategy() {
// return authenticateFailoverStrategy;
// }
//
// public List<String> getAllowListHeaders() {
// return allowListHeaders;
// }
//
// public List<String> getDenyListHeaders() {
// return denyListHeaders;
// }
//
// public String getApiSecret() {
// return apiSecret;
// }
//
// /**
// * Gets the App Id, when it exists
// *
// * @return A string representing the AppID
// * @throws CastleRuntimeException when there is no App Id
// */
// public String getCastleAppId() throws CastleRuntimeException {
// if (castleAppId == null || castleAppId.isEmpty()) {
// throw new CastleRuntimeException("AppId was not specified");
// } else {
// return castleAppId;
// }
// }
//
// public CastleBackendProvider getBackendProvider() {
// return backendProvider;
// }
//
// public boolean isLogHttpRequests() {
// return logHttpRequests;
// }
//
// public List<String> getIpHeaders() {
// return ipHeaders;
// }
//
// public int getMaxRequests() {
// return maxRequests;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
| import io.castle.client.internal.backend.RestApiFactory;
import io.castle.client.internal.config.CastleConfiguration;
import io.castle.client.model.CastleSdkConfigurationException;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.Mockito; | "accept",
"accept-datetime",
"x-forwarded-for",
"forwarded",
"x-forwarded",
"x-real-ip",
"remote-addr"
);
}
@Test
public void sdkProvideASingleton() throws CastleSdkConfigurationException {
//Given
Castle sdk = Castle.verifySdkConfigurationAndInitialize();
Castle.setSingletonInstance(sdk);
//When the sdk is loaded two times
Castle sdk1 = Castle.instance();
Castle sdk2 = Castle.instance();
//Then the same singleton instance is returned
Assertions.assertThat(sdk1).isSameAs(sdk2);
}
@Test
public void sdkInstanceCanBeModifiedForTestProposes() throws CastleSdkConfigurationException, NoSuchFieldException, IllegalAccessException {
//Given a SDK instance
Castle sdk = Castle.verifySdkConfigurationAndInitialize(); | // Path: src/main/java/io/castle/client/internal/backend/RestApiFactory.java
// public interface RestApiFactory {
//
// RestApi buildBackend();
// }
//
// Path: src/main/java/io/castle/client/internal/config/CastleConfiguration.java
// public class CastleConfiguration {
//
// /**
// * Endpoint of the Castle API.
// */
// private final String apiBaseUrl;
//
// /**
// * Timeout after which a request fails.
// */
// private final int timeout;
//
// /**
// * Strategy for returning a {@code verdict} when an authenticate call fails.
// */
// private final AuthenticateFailoverStrategy authenticateFailoverStrategy;
//
// /**
// * List of headers that will get passed to the {@code CastleContext} unless they are denyListed.
// */
// private final List<String> allowListHeaders;
//
// /**
// * List of headers that will never get passed to the {@code CastleContext} when built from an HTTP request.
// */
// private final List<String> denyListHeaders;
//
// /**
// * Secret associated to a Castle account.
// */
// private final String apiSecret;
//
// /**
// * Identifier used for authentication purposes for requests to the Castle API.
// */
// private final String castleAppId;
//
// /**
// * HTTP layer that will be used for calls to the Castle API
// */
// private final CastleBackendProvider backendProvider;
//
// /**
// * Flag to add logging information on HTTP backend.
// */
// private final boolean logHttpRequests;
//
// private final List<String> ipHeaders;
//
// /**
// * Max number of simultaneous requests to Castle
// */
// private final int maxRequests;
//
// public CastleConfiguration(String apiBaseUrl, int timeout, AuthenticateFailoverStrategy authenticateFailoverStrategy, List<String> allowListHeaders, List<String> denyListHeaders, String apiSecret, String castleAppId, CastleBackendProvider backendProvider, boolean logHttpRequests, List<String> ipHeaders, Integer maxRequests) {
// this.apiBaseUrl = apiBaseUrl;
// this.timeout = timeout;
// this.authenticateFailoverStrategy = authenticateFailoverStrategy;
// this.allowListHeaders = allowListHeaders;
// this.denyListHeaders = denyListHeaders;
// this.apiSecret = apiSecret;
// this.castleAppId = castleAppId;
// this.backendProvider = backendProvider;
// this.logHttpRequests = logHttpRequests;
// this.ipHeaders = ipHeaders;
// this.maxRequests = maxRequests;
// }
//
// public String getApiBaseUrl() {
// return apiBaseUrl;
// }
//
// public int getTimeout() {
// return timeout;
// }
//
// public AuthenticateFailoverStrategy getAuthenticateFailoverStrategy() {
// return authenticateFailoverStrategy;
// }
//
// public List<String> getAllowListHeaders() {
// return allowListHeaders;
// }
//
// public List<String> getDenyListHeaders() {
// return denyListHeaders;
// }
//
// public String getApiSecret() {
// return apiSecret;
// }
//
// /**
// * Gets the App Id, when it exists
// *
// * @return A string representing the AppID
// * @throws CastleRuntimeException when there is no App Id
// */
// public String getCastleAppId() throws CastleRuntimeException {
// if (castleAppId == null || castleAppId.isEmpty()) {
// throw new CastleRuntimeException("AppId was not specified");
// } else {
// return castleAppId;
// }
// }
//
// public CastleBackendProvider getBackendProvider() {
// return backendProvider;
// }
//
// public boolean isLogHttpRequests() {
// return logHttpRequests;
// }
//
// public List<String> getIpHeaders() {
// return ipHeaders;
// }
//
// public int getMaxRequests() {
// return maxRequests;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
// Path: src/test/java/io/castle/client/CastleTest.java
import io.castle.client.internal.backend.RestApiFactory;
import io.castle.client.internal.config.CastleConfiguration;
import io.castle.client.model.CastleSdkConfigurationException;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.Mockito;
"accept",
"accept-datetime",
"x-forwarded-for",
"forwarded",
"x-forwarded",
"x-real-ip",
"remote-addr"
);
}
@Test
public void sdkProvideASingleton() throws CastleSdkConfigurationException {
//Given
Castle sdk = Castle.verifySdkConfigurationAndInitialize();
Castle.setSingletonInstance(sdk);
//When the sdk is loaded two times
Castle sdk1 = Castle.instance();
Castle sdk2 = Castle.instance();
//Then the same singleton instance is returned
Assertions.assertThat(sdk1).isSameAs(sdk2);
}
@Test
public void sdkInstanceCanBeModifiedForTestProposes() throws CastleSdkConfigurationException, NoSuchFieldException, IllegalAccessException {
//Given a SDK instance
Castle sdk = Castle.verifySdkConfigurationAndInitialize(); | RestApiFactory mockFactory = Mockito.mock(RestApiFactory.class); |
castle/castle-java | src/main/java/io/castle/client/internal/config/CastleConfigurationBuilder.java | // Path: src/main/java/io/castle/client/internal/backend/CastleBackendProvider.java
// public enum CastleBackendProvider {
// OKHTTP
// }
//
// Path: src/main/java/io/castle/client/internal/utils/HeaderNormalizer.java
// public class HeaderNormalizer {
//
// public String normalize(String headerName) {
// if (headerName == null) {
// return null;
// }
// return headerName.toLowerCase().replaceAll("_", "-");
// }
//
//
// public List<String> normalizeList(List<String> headers) {
// if (headers == null) {
// return null;
// }
// ImmutableList.Builder<String> builder = ImmutableList.builder();
// for (Iterator<String> iterator = headers.iterator(); iterator.hasNext(); ) {
// String value = iterator.next();
// builder.add(normalize(value));
// }
// return builder.build();
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
| import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import io.castle.client.internal.backend.CastleBackendProvider;
import io.castle.client.internal.utils.HeaderNormalizer;
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleSdkConfigurationException;
import java.util.LinkedList;
import java.util.List; | package io.castle.client.internal.config;
/**
* Allows to programmatically create and validate a castleConfiguration through a DSL.
* <p>
* CastleConfigurationBuilder has methods for creating a castleConfiguration instance from scratch.
* Furthermore, there are also methods for creating a configuration from sensible default values.
* The fields that can be set in a CastleConfiguration:
* <ul>
* <li> timeout
* <li> failoverStrategy
* <li> allowListHeaders
* <li> denyListHeaders
* <li> apiSecret
* <li> castleAppId
* <li> backendProvider
* </ul>
* The {@code build} method provides a layer of validation.
* It will throw a {@link CastleSdkConfigurationException} if one of the fields is left unset.
* {@code apiSecret} and {@code castleAppId} do not have defaults.
* A value for the Api Secret should be provided before calling {@code build}.
* <h2>How to use AllowList and DenyList</h2>
* When {@link io.castle.client.Castle#onRequest} is called, allowListed headers and denyListed headers are checked.
* Headers are only passed to the context if they are in the allowList, but not in the denyList.
* That is, if a header is in both lists, the denyListed value takes precedence, and the header is not passed to the
* context object.
*/
public class CastleConfigurationBuilder {
/**
* Represents the milliseconds after which a request fails.
*/
private int timeout = 500;
/**
* Strategy used when an authenticate call to the Castle API fails.
*/ | // Path: src/main/java/io/castle/client/internal/backend/CastleBackendProvider.java
// public enum CastleBackendProvider {
// OKHTTP
// }
//
// Path: src/main/java/io/castle/client/internal/utils/HeaderNormalizer.java
// public class HeaderNormalizer {
//
// public String normalize(String headerName) {
// if (headerName == null) {
// return null;
// }
// return headerName.toLowerCase().replaceAll("_", "-");
// }
//
//
// public List<String> normalizeList(List<String> headers) {
// if (headers == null) {
// return null;
// }
// ImmutableList.Builder<String> builder = ImmutableList.builder();
// for (Iterator<String> iterator = headers.iterator(); iterator.hasNext(); ) {
// String value = iterator.next();
// builder.add(normalize(value));
// }
// return builder.build();
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
// Path: src/main/java/io/castle/client/internal/config/CastleConfigurationBuilder.java
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import io.castle.client.internal.backend.CastleBackendProvider;
import io.castle.client.internal.utils.HeaderNormalizer;
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleSdkConfigurationException;
import java.util.LinkedList;
import java.util.List;
package io.castle.client.internal.config;
/**
* Allows to programmatically create and validate a castleConfiguration through a DSL.
* <p>
* CastleConfigurationBuilder has methods for creating a castleConfiguration instance from scratch.
* Furthermore, there are also methods for creating a configuration from sensible default values.
* The fields that can be set in a CastleConfiguration:
* <ul>
* <li> timeout
* <li> failoverStrategy
* <li> allowListHeaders
* <li> denyListHeaders
* <li> apiSecret
* <li> castleAppId
* <li> backendProvider
* </ul>
* The {@code build} method provides a layer of validation.
* It will throw a {@link CastleSdkConfigurationException} if one of the fields is left unset.
* {@code apiSecret} and {@code castleAppId} do not have defaults.
* A value for the Api Secret should be provided before calling {@code build}.
* <h2>How to use AllowList and DenyList</h2>
* When {@link io.castle.client.Castle#onRequest} is called, allowListed headers and denyListed headers are checked.
* Headers are only passed to the context if they are in the allowList, but not in the denyList.
* That is, if a header is in both lists, the denyListed value takes precedence, and the header is not passed to the
* context object.
*/
public class CastleConfigurationBuilder {
/**
* Represents the milliseconds after which a request fails.
*/
private int timeout = 500;
/**
* Strategy used when an authenticate call to the Castle API fails.
*/ | private AuthenticateFailoverStrategy failoverStrategy; |
castle/castle-java | src/main/java/io/castle/client/internal/config/CastleConfigurationBuilder.java | // Path: src/main/java/io/castle/client/internal/backend/CastleBackendProvider.java
// public enum CastleBackendProvider {
// OKHTTP
// }
//
// Path: src/main/java/io/castle/client/internal/utils/HeaderNormalizer.java
// public class HeaderNormalizer {
//
// public String normalize(String headerName) {
// if (headerName == null) {
// return null;
// }
// return headerName.toLowerCase().replaceAll("_", "-");
// }
//
//
// public List<String> normalizeList(List<String> headers) {
// if (headers == null) {
// return null;
// }
// ImmutableList.Builder<String> builder = ImmutableList.builder();
// for (Iterator<String> iterator = headers.iterator(); iterator.hasNext(); ) {
// String value = iterator.next();
// builder.add(normalize(value));
// }
// return builder.build();
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
| import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import io.castle.client.internal.backend.CastleBackendProvider;
import io.castle.client.internal.utils.HeaderNormalizer;
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleSdkConfigurationException;
import java.util.LinkedList;
import java.util.List; | package io.castle.client.internal.config;
/**
* Allows to programmatically create and validate a castleConfiguration through a DSL.
* <p>
* CastleConfigurationBuilder has methods for creating a castleConfiguration instance from scratch.
* Furthermore, there are also methods for creating a configuration from sensible default values.
* The fields that can be set in a CastleConfiguration:
* <ul>
* <li> timeout
* <li> failoverStrategy
* <li> allowListHeaders
* <li> denyListHeaders
* <li> apiSecret
* <li> castleAppId
* <li> backendProvider
* </ul>
* The {@code build} method provides a layer of validation.
* It will throw a {@link CastleSdkConfigurationException} if one of the fields is left unset.
* {@code apiSecret} and {@code castleAppId} do not have defaults.
* A value for the Api Secret should be provided before calling {@code build}.
* <h2>How to use AllowList and DenyList</h2>
* When {@link io.castle.client.Castle#onRequest} is called, allowListed headers and denyListed headers are checked.
* Headers are only passed to the context if they are in the allowList, but not in the denyList.
* That is, if a header is in both lists, the denyListed value takes precedence, and the header is not passed to the
* context object.
*/
public class CastleConfigurationBuilder {
/**
* Represents the milliseconds after which a request fails.
*/
private int timeout = 500;
/**
* Strategy used when an authenticate call to the Castle API fails.
*/
private AuthenticateFailoverStrategy failoverStrategy;
/**
* Strings representing headers that should be passed to the context object unless they are also denyListed.
*/
private List<String> allowListHeaders;
/**
* Strings representing headers that should never be passed to the context object.
*/
private List<String> denyListHeaders;
/**
* String represented the API secret associated with a Castle account.
*/
private String apiSecret;
/**
* String representing an AppID associated with a Castle account.
*/
private String castleAppId;
/**
* The HTTP layer chosen to make requests.
*/ | // Path: src/main/java/io/castle/client/internal/backend/CastleBackendProvider.java
// public enum CastleBackendProvider {
// OKHTTP
// }
//
// Path: src/main/java/io/castle/client/internal/utils/HeaderNormalizer.java
// public class HeaderNormalizer {
//
// public String normalize(String headerName) {
// if (headerName == null) {
// return null;
// }
// return headerName.toLowerCase().replaceAll("_", "-");
// }
//
//
// public List<String> normalizeList(List<String> headers) {
// if (headers == null) {
// return null;
// }
// ImmutableList.Builder<String> builder = ImmutableList.builder();
// for (Iterator<String> iterator = headers.iterator(); iterator.hasNext(); ) {
// String value = iterator.next();
// builder.add(normalize(value));
// }
// return builder.build();
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
// Path: src/main/java/io/castle/client/internal/config/CastleConfigurationBuilder.java
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import io.castle.client.internal.backend.CastleBackendProvider;
import io.castle.client.internal.utils.HeaderNormalizer;
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleSdkConfigurationException;
import java.util.LinkedList;
import java.util.List;
package io.castle.client.internal.config;
/**
* Allows to programmatically create and validate a castleConfiguration through a DSL.
* <p>
* CastleConfigurationBuilder has methods for creating a castleConfiguration instance from scratch.
* Furthermore, there are also methods for creating a configuration from sensible default values.
* The fields that can be set in a CastleConfiguration:
* <ul>
* <li> timeout
* <li> failoverStrategy
* <li> allowListHeaders
* <li> denyListHeaders
* <li> apiSecret
* <li> castleAppId
* <li> backendProvider
* </ul>
* The {@code build} method provides a layer of validation.
* It will throw a {@link CastleSdkConfigurationException} if one of the fields is left unset.
* {@code apiSecret} and {@code castleAppId} do not have defaults.
* A value for the Api Secret should be provided before calling {@code build}.
* <h2>How to use AllowList and DenyList</h2>
* When {@link io.castle.client.Castle#onRequest} is called, allowListed headers and denyListed headers are checked.
* Headers are only passed to the context if they are in the allowList, but not in the denyList.
* That is, if a header is in both lists, the denyListed value takes precedence, and the header is not passed to the
* context object.
*/
public class CastleConfigurationBuilder {
/**
* Represents the milliseconds after which a request fails.
*/
private int timeout = 500;
/**
* Strategy used when an authenticate call to the Castle API fails.
*/
private AuthenticateFailoverStrategy failoverStrategy;
/**
* Strings representing headers that should be passed to the context object unless they are also denyListed.
*/
private List<String> allowListHeaders;
/**
* Strings representing headers that should never be passed to the context object.
*/
private List<String> denyListHeaders;
/**
* String represented the API secret associated with a Castle account.
*/
private String apiSecret;
/**
* String representing an AppID associated with a Castle account.
*/
private String castleAppId;
/**
* The HTTP layer chosen to make requests.
*/ | private CastleBackendProvider backendProvider = CastleBackendProvider.OKHTTP; //Unique available backend on the current version |
castle/castle-java | src/main/java/io/castle/client/internal/config/CastleConfigurationBuilder.java | // Path: src/main/java/io/castle/client/internal/backend/CastleBackendProvider.java
// public enum CastleBackendProvider {
// OKHTTP
// }
//
// Path: src/main/java/io/castle/client/internal/utils/HeaderNormalizer.java
// public class HeaderNormalizer {
//
// public String normalize(String headerName) {
// if (headerName == null) {
// return null;
// }
// return headerName.toLowerCase().replaceAll("_", "-");
// }
//
//
// public List<String> normalizeList(List<String> headers) {
// if (headers == null) {
// return null;
// }
// ImmutableList.Builder<String> builder = ImmutableList.builder();
// for (Iterator<String> iterator = headers.iterator(); iterator.hasNext(); ) {
// String value = iterator.next();
// builder.add(normalize(value));
// }
// return builder.build();
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
| import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import io.castle.client.internal.backend.CastleBackendProvider;
import io.castle.client.internal.utils.HeaderNormalizer;
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleSdkConfigurationException;
import java.util.LinkedList;
import java.util.List; | * Sets the timeout in milliseconds for a request.
*
* @param timeout milliseconds after which a request times out
* @return a castleConfigurationBuilder with a timeout set to a new value
*/
public CastleConfigurationBuilder withTimeout(int timeout) {
this.timeout = timeout;
return this;
}
/**
* Establishes the authentication strategy that will be used in case of a timeout when performing a
* {@code CastleApi#authenticate} call.
*
* @param failoverStrategy strategy to use for failed authenticate API calls; not null.
* @return a castleConfigurationBuilder with the chosen AuthenticationStrategy set
*/
public CastleConfigurationBuilder withAuthenticateFailoverStrategy(AuthenticateFailoverStrategy failoverStrategy) {
this.failoverStrategy = failoverStrategy;
return this;
}
/**
* Sets the failover strategy for the authenticate Castle API call to allow.
* <p>
* The authenticate failover strategy for the default configuration is to return {@link AuthenticateAction#ALLOW}.
*
* @return a castleConfigurationBuilder with allow as the authenticate failover strategy
*/
public CastleConfigurationBuilder withDefaultAuthenticateFailoverStrategy() { | // Path: src/main/java/io/castle/client/internal/backend/CastleBackendProvider.java
// public enum CastleBackendProvider {
// OKHTTP
// }
//
// Path: src/main/java/io/castle/client/internal/utils/HeaderNormalizer.java
// public class HeaderNormalizer {
//
// public String normalize(String headerName) {
// if (headerName == null) {
// return null;
// }
// return headerName.toLowerCase().replaceAll("_", "-");
// }
//
//
// public List<String> normalizeList(List<String> headers) {
// if (headers == null) {
// return null;
// }
// ImmutableList.Builder<String> builder = ImmutableList.builder();
// for (Iterator<String> iterator = headers.iterator(); iterator.hasNext(); ) {
// String value = iterator.next();
// builder.add(normalize(value));
// }
// return builder.build();
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
// Path: src/main/java/io/castle/client/internal/config/CastleConfigurationBuilder.java
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import io.castle.client.internal.backend.CastleBackendProvider;
import io.castle.client.internal.utils.HeaderNormalizer;
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleSdkConfigurationException;
import java.util.LinkedList;
import java.util.List;
* Sets the timeout in milliseconds for a request.
*
* @param timeout milliseconds after which a request times out
* @return a castleConfigurationBuilder with a timeout set to a new value
*/
public CastleConfigurationBuilder withTimeout(int timeout) {
this.timeout = timeout;
return this;
}
/**
* Establishes the authentication strategy that will be used in case of a timeout when performing a
* {@code CastleApi#authenticate} call.
*
* @param failoverStrategy strategy to use for failed authenticate API calls; not null.
* @return a castleConfigurationBuilder with the chosen AuthenticationStrategy set
*/
public CastleConfigurationBuilder withAuthenticateFailoverStrategy(AuthenticateFailoverStrategy failoverStrategy) {
this.failoverStrategy = failoverStrategy;
return this;
}
/**
* Sets the failover strategy for the authenticate Castle API call to allow.
* <p>
* The authenticate failover strategy for the default configuration is to return {@link AuthenticateAction#ALLOW}.
*
* @return a castleConfigurationBuilder with allow as the authenticate failover strategy
*/
public CastleConfigurationBuilder withDefaultAuthenticateFailoverStrategy() { | return this.withAuthenticateFailoverStrategy(new AuthenticateFailoverStrategy(AuthenticateAction.ALLOW)); |
castle/castle-java | src/main/java/io/castle/client/internal/config/CastleConfigurationBuilder.java | // Path: src/main/java/io/castle/client/internal/backend/CastleBackendProvider.java
// public enum CastleBackendProvider {
// OKHTTP
// }
//
// Path: src/main/java/io/castle/client/internal/utils/HeaderNormalizer.java
// public class HeaderNormalizer {
//
// public String normalize(String headerName) {
// if (headerName == null) {
// return null;
// }
// return headerName.toLowerCase().replaceAll("_", "-");
// }
//
//
// public List<String> normalizeList(List<String> headers) {
// if (headers == null) {
// return null;
// }
// ImmutableList.Builder<String> builder = ImmutableList.builder();
// for (Iterator<String> iterator = headers.iterator(); iterator.hasNext(); ) {
// String value = iterator.next();
// builder.add(normalize(value));
// }
// return builder.build();
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
| import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import io.castle.client.internal.backend.CastleBackendProvider;
import io.castle.client.internal.utils.HeaderNormalizer;
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleSdkConfigurationException;
import java.util.LinkedList;
import java.util.List; | *
* @param apiSecret the API secret of the account calling the Castle API
* @return a castleConfigurationBuilder with the API secret set
*/
public CastleConfigurationBuilder withApiSecret(String apiSecret) {
this.apiSecret = apiSecret;
return this;
}
/* alias for withApiSecret */
public CastleConfigurationBuilder apiSecret(String apiSecret) {
return withApiSecret(apiSecret);
}
/**
* Validates and returns a configuration object, if all required fields have the required values, or an exception
* otherwise.
* <p>
* Validation consists in checking that no field in the configuration is set tu null.
* Furthermore, the build method also makes sure that the API secret is not an empty string.
* An additional layer of validation is given further along the line by {@link HeaderNormalizer}, which will ensure
* that the provided list of strings can contain both, upper and lower case letters.
* This method will not detect wrong headers, API secrets or APP ID's.
*
* @return a castleConfiguration with all fields set to some meaningful value
* @throws CastleSdkConfigurationException if at least one of castleAppId, apiSecret, allowListHeaders,
* denyListHeaders, failoverStrategy, backendProvider is not provided
* during the building stage of the
* CastleConfiguration instance.
*/ | // Path: src/main/java/io/castle/client/internal/backend/CastleBackendProvider.java
// public enum CastleBackendProvider {
// OKHTTP
// }
//
// Path: src/main/java/io/castle/client/internal/utils/HeaderNormalizer.java
// public class HeaderNormalizer {
//
// public String normalize(String headerName) {
// if (headerName == null) {
// return null;
// }
// return headerName.toLowerCase().replaceAll("_", "-");
// }
//
//
// public List<String> normalizeList(List<String> headers) {
// if (headers == null) {
// return null;
// }
// ImmutableList.Builder<String> builder = ImmutableList.builder();
// for (Iterator<String> iterator = headers.iterator(); iterator.hasNext(); ) {
// String value = iterator.next();
// builder.add(normalize(value));
// }
// return builder.build();
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
// Path: src/main/java/io/castle/client/internal/config/CastleConfigurationBuilder.java
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import io.castle.client.internal.backend.CastleBackendProvider;
import io.castle.client.internal.utils.HeaderNormalizer;
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleSdkConfigurationException;
import java.util.LinkedList;
import java.util.List;
*
* @param apiSecret the API secret of the account calling the Castle API
* @return a castleConfigurationBuilder with the API secret set
*/
public CastleConfigurationBuilder withApiSecret(String apiSecret) {
this.apiSecret = apiSecret;
return this;
}
/* alias for withApiSecret */
public CastleConfigurationBuilder apiSecret(String apiSecret) {
return withApiSecret(apiSecret);
}
/**
* Validates and returns a configuration object, if all required fields have the required values, or an exception
* otherwise.
* <p>
* Validation consists in checking that no field in the configuration is set tu null.
* Furthermore, the build method also makes sure that the API secret is not an empty string.
* An additional layer of validation is given further along the line by {@link HeaderNormalizer}, which will ensure
* that the provided list of strings can contain both, upper and lower case letters.
* This method will not detect wrong headers, API secrets or APP ID's.
*
* @return a castleConfiguration with all fields set to some meaningful value
* @throws CastleSdkConfigurationException if at least one of castleAppId, apiSecret, allowListHeaders,
* denyListHeaders, failoverStrategy, backendProvider is not provided
* during the building stage of the
* CastleConfiguration instance.
*/ | public CastleConfiguration build() throws CastleSdkConfigurationException { |
castle/castle-java | src/main/java/io/castle/client/internal/config/CastleConfigurationBuilder.java | // Path: src/main/java/io/castle/client/internal/backend/CastleBackendProvider.java
// public enum CastleBackendProvider {
// OKHTTP
// }
//
// Path: src/main/java/io/castle/client/internal/utils/HeaderNormalizer.java
// public class HeaderNormalizer {
//
// public String normalize(String headerName) {
// if (headerName == null) {
// return null;
// }
// return headerName.toLowerCase().replaceAll("_", "-");
// }
//
//
// public List<String> normalizeList(List<String> headers) {
// if (headers == null) {
// return null;
// }
// ImmutableList.Builder<String> builder = ImmutableList.builder();
// for (Iterator<String> iterator = headers.iterator(); iterator.hasNext(); ) {
// String value = iterator.next();
// builder.add(normalize(value));
// }
// return builder.build();
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
| import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import io.castle.client.internal.backend.CastleBackendProvider;
import io.castle.client.internal.utils.HeaderNormalizer;
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleSdkConfigurationException;
import java.util.LinkedList;
import java.util.List; | */
public CastleConfiguration build() throws CastleSdkConfigurationException {
ImmutableList.Builder<String> builder = ImmutableList.builder();
if (apiSecret == null || apiSecret.isEmpty()) {
builder.add("The apiSecret for the castleSDK must be provided in the configuration. Read documentation " +
"for further details.");
}
if (allowListHeaders == null) {
builder.add("An allowList of headers must be provided. If not sure, then use the default values provided " +
"by method withDefaultAllowList. Read documentation for further details.");
}
if (denyListHeaders == null) {
builder.add("A denyList of headers must be provided. If not sure, then use the default values provided " +
"by method withDefaultDenyList. Read documentation for further details.");
}
if (failoverStrategy == null) {
builder.add("A failover strategy must be provided. If not sure, then use the default values provided " +
"by method withDefaultAuthenticateFailoverStrategy. Read documentation for further details.");
}
if (backendProvider == null) {
builder.add("A backend provider must be selected. If not sure, then use the default values provided " +
"by method withDefaultBackendProvider. Read documentation for further details.");
}
if (apiBaseUrl == null) {
builder.add("A apiBaseUrl value must be selected. If not sure, then use the default values provided by method withDefaultApiBaseUrl. Read documentation for further details.");
}
ImmutableList<String> errorMessages = builder.build();
if (!errorMessages.isEmpty()) {
throw new CastleSdkConfigurationException(Joiner.on(System.lineSeparator()).join(errorMessages));
} | // Path: src/main/java/io/castle/client/internal/backend/CastleBackendProvider.java
// public enum CastleBackendProvider {
// OKHTTP
// }
//
// Path: src/main/java/io/castle/client/internal/utils/HeaderNormalizer.java
// public class HeaderNormalizer {
//
// public String normalize(String headerName) {
// if (headerName == null) {
// return null;
// }
// return headerName.toLowerCase().replaceAll("_", "-");
// }
//
//
// public List<String> normalizeList(List<String> headers) {
// if (headers == null) {
// return null;
// }
// ImmutableList.Builder<String> builder = ImmutableList.builder();
// for (Iterator<String> iterator = headers.iterator(); iterator.hasNext(); ) {
// String value = iterator.next();
// builder.add(normalize(value));
// }
// return builder.build();
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateFailoverStrategy.java
// public class AuthenticateFailoverStrategy {
//
// private final AuthenticateAction defaultAction;
// private final boolean throwTimeoutException;
//
// private AuthenticateFailoverStrategy(AuthenticateAction defaultAction, boolean throwTimeoutException) {
// this.defaultAction = defaultAction;
// this.throwTimeoutException = throwTimeoutException;
// }
//
// /**
// * Sets the default authenticationAction for failed requests.
// *
// * @param action the authenticateAction that will be used as a default for failed requests
// */
// public AuthenticateFailoverStrategy(AuthenticateAction action) {
// this(action, false);
// }
//
// /**
// * Creates an authenticationStrategy whose policy is to throw a timeoutException.
// */
// public AuthenticateFailoverStrategy() {
// this(null, true);
// }
//
//
// /**
// * Gets the authenticateAction that this strategy uses for failover.
// *
// * @return the authenticateAction configured as default; null if there is no default AuthenticateAction
// */
// public AuthenticateAction getDefaultAction() {
// return defaultAction;
// }
//
// /**
// * Checks whether the failover strategy is configured to throw a timeoutException.
// *
// * @return true if the failover strategy is set to throw a timeoutException, false otherwise
// */
// public boolean isThrowTimeoutException() {
// return throwTimeoutException;
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
// Path: src/main/java/io/castle/client/internal/config/CastleConfigurationBuilder.java
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import io.castle.client.internal.backend.CastleBackendProvider;
import io.castle.client.internal.utils.HeaderNormalizer;
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.model.CastleSdkConfigurationException;
import java.util.LinkedList;
import java.util.List;
*/
public CastleConfiguration build() throws CastleSdkConfigurationException {
ImmutableList.Builder<String> builder = ImmutableList.builder();
if (apiSecret == null || apiSecret.isEmpty()) {
builder.add("The apiSecret for the castleSDK must be provided in the configuration. Read documentation " +
"for further details.");
}
if (allowListHeaders == null) {
builder.add("An allowList of headers must be provided. If not sure, then use the default values provided " +
"by method withDefaultAllowList. Read documentation for further details.");
}
if (denyListHeaders == null) {
builder.add("A denyList of headers must be provided. If not sure, then use the default values provided " +
"by method withDefaultDenyList. Read documentation for further details.");
}
if (failoverStrategy == null) {
builder.add("A failover strategy must be provided. If not sure, then use the default values provided " +
"by method withDefaultAuthenticateFailoverStrategy. Read documentation for further details.");
}
if (backendProvider == null) {
builder.add("A backend provider must be selected. If not sure, then use the default values provided " +
"by method withDefaultBackendProvider. Read documentation for further details.");
}
if (apiBaseUrl == null) {
builder.add("A apiBaseUrl value must be selected. If not sure, then use the default values provided by method withDefaultApiBaseUrl. Read documentation for further details.");
}
ImmutableList<String> errorMessages = builder.build();
if (!errorMessages.isEmpty()) {
throw new CastleSdkConfigurationException(Joiner.on(System.lineSeparator()).join(errorMessages));
} | HeaderNormalizer normalizer = new HeaderNormalizer(); |
castle/castle-java | src/main/java/io/castle/client/internal/backend/OkHttpFactory.java | // Path: src/main/java/io/castle/client/internal/config/CastleConfiguration.java
// public class CastleConfiguration {
//
// /**
// * Endpoint of the Castle API.
// */
// private final String apiBaseUrl;
//
// /**
// * Timeout after which a request fails.
// */
// private final int timeout;
//
// /**
// * Strategy for returning a {@code verdict} when an authenticate call fails.
// */
// private final AuthenticateFailoverStrategy authenticateFailoverStrategy;
//
// /**
// * List of headers that will get passed to the {@code CastleContext} unless they are denyListed.
// */
// private final List<String> allowListHeaders;
//
// /**
// * List of headers that will never get passed to the {@code CastleContext} when built from an HTTP request.
// */
// private final List<String> denyListHeaders;
//
// /**
// * Secret associated to a Castle account.
// */
// private final String apiSecret;
//
// /**
// * Identifier used for authentication purposes for requests to the Castle API.
// */
// private final String castleAppId;
//
// /**
// * HTTP layer that will be used for calls to the Castle API
// */
// private final CastleBackendProvider backendProvider;
//
// /**
// * Flag to add logging information on HTTP backend.
// */
// private final boolean logHttpRequests;
//
// private final List<String> ipHeaders;
//
// /**
// * Max number of simultaneous requests to Castle
// */
// private final int maxRequests;
//
// public CastleConfiguration(String apiBaseUrl, int timeout, AuthenticateFailoverStrategy authenticateFailoverStrategy, List<String> allowListHeaders, List<String> denyListHeaders, String apiSecret, String castleAppId, CastleBackendProvider backendProvider, boolean logHttpRequests, List<String> ipHeaders, Integer maxRequests) {
// this.apiBaseUrl = apiBaseUrl;
// this.timeout = timeout;
// this.authenticateFailoverStrategy = authenticateFailoverStrategy;
// this.allowListHeaders = allowListHeaders;
// this.denyListHeaders = denyListHeaders;
// this.apiSecret = apiSecret;
// this.castleAppId = castleAppId;
// this.backendProvider = backendProvider;
// this.logHttpRequests = logHttpRequests;
// this.ipHeaders = ipHeaders;
// this.maxRequests = maxRequests;
// }
//
// public String getApiBaseUrl() {
// return apiBaseUrl;
// }
//
// public int getTimeout() {
// return timeout;
// }
//
// public AuthenticateFailoverStrategy getAuthenticateFailoverStrategy() {
// return authenticateFailoverStrategy;
// }
//
// public List<String> getAllowListHeaders() {
// return allowListHeaders;
// }
//
// public List<String> getDenyListHeaders() {
// return denyListHeaders;
// }
//
// public String getApiSecret() {
// return apiSecret;
// }
//
// /**
// * Gets the App Id, when it exists
// *
// * @return A string representing the AppID
// * @throws CastleRuntimeException when there is no App Id
// */
// public String getCastleAppId() throws CastleRuntimeException {
// if (castleAppId == null || castleAppId.isEmpty()) {
// throw new CastleRuntimeException("AppId was not specified");
// } else {
// return castleAppId;
// }
// }
//
// public CastleBackendProvider getBackendProvider() {
// return backendProvider;
// }
//
// public boolean isLogHttpRequests() {
// return logHttpRequests;
// }
//
// public List<String> getIpHeaders() {
// return ipHeaders;
// }
//
// public int getMaxRequests() {
// return maxRequests;
// }
// }
//
// Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
| import com.google.common.collect.ImmutableList;
import io.castle.client.internal.config.CastleConfiguration;
import io.castle.client.internal.json.CastleGsonModel;
import okhttp3.*;
import okhttp3.logging.HttpLoggingInterceptor;
import java.io.IOException;
import java.util.Collections;
import java.util.concurrent.TimeUnit; | package io.castle.client.internal.backend;
public class OkHttpFactory implements RestApiFactory {
private final OkHttpClient client; | // Path: src/main/java/io/castle/client/internal/config/CastleConfiguration.java
// public class CastleConfiguration {
//
// /**
// * Endpoint of the Castle API.
// */
// private final String apiBaseUrl;
//
// /**
// * Timeout after which a request fails.
// */
// private final int timeout;
//
// /**
// * Strategy for returning a {@code verdict} when an authenticate call fails.
// */
// private final AuthenticateFailoverStrategy authenticateFailoverStrategy;
//
// /**
// * List of headers that will get passed to the {@code CastleContext} unless they are denyListed.
// */
// private final List<String> allowListHeaders;
//
// /**
// * List of headers that will never get passed to the {@code CastleContext} when built from an HTTP request.
// */
// private final List<String> denyListHeaders;
//
// /**
// * Secret associated to a Castle account.
// */
// private final String apiSecret;
//
// /**
// * Identifier used for authentication purposes for requests to the Castle API.
// */
// private final String castleAppId;
//
// /**
// * HTTP layer that will be used for calls to the Castle API
// */
// private final CastleBackendProvider backendProvider;
//
// /**
// * Flag to add logging information on HTTP backend.
// */
// private final boolean logHttpRequests;
//
// private final List<String> ipHeaders;
//
// /**
// * Max number of simultaneous requests to Castle
// */
// private final int maxRequests;
//
// public CastleConfiguration(String apiBaseUrl, int timeout, AuthenticateFailoverStrategy authenticateFailoverStrategy, List<String> allowListHeaders, List<String> denyListHeaders, String apiSecret, String castleAppId, CastleBackendProvider backendProvider, boolean logHttpRequests, List<String> ipHeaders, Integer maxRequests) {
// this.apiBaseUrl = apiBaseUrl;
// this.timeout = timeout;
// this.authenticateFailoverStrategy = authenticateFailoverStrategy;
// this.allowListHeaders = allowListHeaders;
// this.denyListHeaders = denyListHeaders;
// this.apiSecret = apiSecret;
// this.castleAppId = castleAppId;
// this.backendProvider = backendProvider;
// this.logHttpRequests = logHttpRequests;
// this.ipHeaders = ipHeaders;
// this.maxRequests = maxRequests;
// }
//
// public String getApiBaseUrl() {
// return apiBaseUrl;
// }
//
// public int getTimeout() {
// return timeout;
// }
//
// public AuthenticateFailoverStrategy getAuthenticateFailoverStrategy() {
// return authenticateFailoverStrategy;
// }
//
// public List<String> getAllowListHeaders() {
// return allowListHeaders;
// }
//
// public List<String> getDenyListHeaders() {
// return denyListHeaders;
// }
//
// public String getApiSecret() {
// return apiSecret;
// }
//
// /**
// * Gets the App Id, when it exists
// *
// * @return A string representing the AppID
// * @throws CastleRuntimeException when there is no App Id
// */
// public String getCastleAppId() throws CastleRuntimeException {
// if (castleAppId == null || castleAppId.isEmpty()) {
// throw new CastleRuntimeException("AppId was not specified");
// } else {
// return castleAppId;
// }
// }
//
// public CastleBackendProvider getBackendProvider() {
// return backendProvider;
// }
//
// public boolean isLogHttpRequests() {
// return logHttpRequests;
// }
//
// public List<String> getIpHeaders() {
// return ipHeaders;
// }
//
// public int getMaxRequests() {
// return maxRequests;
// }
// }
//
// Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
// Path: src/main/java/io/castle/client/internal/backend/OkHttpFactory.java
import com.google.common.collect.ImmutableList;
import io.castle.client.internal.config.CastleConfiguration;
import io.castle.client.internal.json.CastleGsonModel;
import okhttp3.*;
import okhttp3.logging.HttpLoggingInterceptor;
import java.io.IOException;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
package io.castle.client.internal.backend;
public class OkHttpFactory implements RestApiFactory {
private final OkHttpClient client; | private final CastleGsonModel modelInstance; |
castle/castle-java | src/main/java/io/castle/client/internal/backend/OkHttpFactory.java | // Path: src/main/java/io/castle/client/internal/config/CastleConfiguration.java
// public class CastleConfiguration {
//
// /**
// * Endpoint of the Castle API.
// */
// private final String apiBaseUrl;
//
// /**
// * Timeout after which a request fails.
// */
// private final int timeout;
//
// /**
// * Strategy for returning a {@code verdict} when an authenticate call fails.
// */
// private final AuthenticateFailoverStrategy authenticateFailoverStrategy;
//
// /**
// * List of headers that will get passed to the {@code CastleContext} unless they are denyListed.
// */
// private final List<String> allowListHeaders;
//
// /**
// * List of headers that will never get passed to the {@code CastleContext} when built from an HTTP request.
// */
// private final List<String> denyListHeaders;
//
// /**
// * Secret associated to a Castle account.
// */
// private final String apiSecret;
//
// /**
// * Identifier used for authentication purposes for requests to the Castle API.
// */
// private final String castleAppId;
//
// /**
// * HTTP layer that will be used for calls to the Castle API
// */
// private final CastleBackendProvider backendProvider;
//
// /**
// * Flag to add logging information on HTTP backend.
// */
// private final boolean logHttpRequests;
//
// private final List<String> ipHeaders;
//
// /**
// * Max number of simultaneous requests to Castle
// */
// private final int maxRequests;
//
// public CastleConfiguration(String apiBaseUrl, int timeout, AuthenticateFailoverStrategy authenticateFailoverStrategy, List<String> allowListHeaders, List<String> denyListHeaders, String apiSecret, String castleAppId, CastleBackendProvider backendProvider, boolean logHttpRequests, List<String> ipHeaders, Integer maxRequests) {
// this.apiBaseUrl = apiBaseUrl;
// this.timeout = timeout;
// this.authenticateFailoverStrategy = authenticateFailoverStrategy;
// this.allowListHeaders = allowListHeaders;
// this.denyListHeaders = denyListHeaders;
// this.apiSecret = apiSecret;
// this.castleAppId = castleAppId;
// this.backendProvider = backendProvider;
// this.logHttpRequests = logHttpRequests;
// this.ipHeaders = ipHeaders;
// this.maxRequests = maxRequests;
// }
//
// public String getApiBaseUrl() {
// return apiBaseUrl;
// }
//
// public int getTimeout() {
// return timeout;
// }
//
// public AuthenticateFailoverStrategy getAuthenticateFailoverStrategy() {
// return authenticateFailoverStrategy;
// }
//
// public List<String> getAllowListHeaders() {
// return allowListHeaders;
// }
//
// public List<String> getDenyListHeaders() {
// return denyListHeaders;
// }
//
// public String getApiSecret() {
// return apiSecret;
// }
//
// /**
// * Gets the App Id, when it exists
// *
// * @return A string representing the AppID
// * @throws CastleRuntimeException when there is no App Id
// */
// public String getCastleAppId() throws CastleRuntimeException {
// if (castleAppId == null || castleAppId.isEmpty()) {
// throw new CastleRuntimeException("AppId was not specified");
// } else {
// return castleAppId;
// }
// }
//
// public CastleBackendProvider getBackendProvider() {
// return backendProvider;
// }
//
// public boolean isLogHttpRequests() {
// return logHttpRequests;
// }
//
// public List<String> getIpHeaders() {
// return ipHeaders;
// }
//
// public int getMaxRequests() {
// return maxRequests;
// }
// }
//
// Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
| import com.google.common.collect.ImmutableList;
import io.castle.client.internal.config.CastleConfiguration;
import io.castle.client.internal.json.CastleGsonModel;
import okhttp3.*;
import okhttp3.logging.HttpLoggingInterceptor;
import java.io.IOException;
import java.util.Collections;
import java.util.concurrent.TimeUnit; | package io.castle.client.internal.backend;
public class OkHttpFactory implements RestApiFactory {
private final OkHttpClient client;
private final CastleGsonModel modelInstance; | // Path: src/main/java/io/castle/client/internal/config/CastleConfiguration.java
// public class CastleConfiguration {
//
// /**
// * Endpoint of the Castle API.
// */
// private final String apiBaseUrl;
//
// /**
// * Timeout after which a request fails.
// */
// private final int timeout;
//
// /**
// * Strategy for returning a {@code verdict} when an authenticate call fails.
// */
// private final AuthenticateFailoverStrategy authenticateFailoverStrategy;
//
// /**
// * List of headers that will get passed to the {@code CastleContext} unless they are denyListed.
// */
// private final List<String> allowListHeaders;
//
// /**
// * List of headers that will never get passed to the {@code CastleContext} when built from an HTTP request.
// */
// private final List<String> denyListHeaders;
//
// /**
// * Secret associated to a Castle account.
// */
// private final String apiSecret;
//
// /**
// * Identifier used for authentication purposes for requests to the Castle API.
// */
// private final String castleAppId;
//
// /**
// * HTTP layer that will be used for calls to the Castle API
// */
// private final CastleBackendProvider backendProvider;
//
// /**
// * Flag to add logging information on HTTP backend.
// */
// private final boolean logHttpRequests;
//
// private final List<String> ipHeaders;
//
// /**
// * Max number of simultaneous requests to Castle
// */
// private final int maxRequests;
//
// public CastleConfiguration(String apiBaseUrl, int timeout, AuthenticateFailoverStrategy authenticateFailoverStrategy, List<String> allowListHeaders, List<String> denyListHeaders, String apiSecret, String castleAppId, CastleBackendProvider backendProvider, boolean logHttpRequests, List<String> ipHeaders, Integer maxRequests) {
// this.apiBaseUrl = apiBaseUrl;
// this.timeout = timeout;
// this.authenticateFailoverStrategy = authenticateFailoverStrategy;
// this.allowListHeaders = allowListHeaders;
// this.denyListHeaders = denyListHeaders;
// this.apiSecret = apiSecret;
// this.castleAppId = castleAppId;
// this.backendProvider = backendProvider;
// this.logHttpRequests = logHttpRequests;
// this.ipHeaders = ipHeaders;
// this.maxRequests = maxRequests;
// }
//
// public String getApiBaseUrl() {
// return apiBaseUrl;
// }
//
// public int getTimeout() {
// return timeout;
// }
//
// public AuthenticateFailoverStrategy getAuthenticateFailoverStrategy() {
// return authenticateFailoverStrategy;
// }
//
// public List<String> getAllowListHeaders() {
// return allowListHeaders;
// }
//
// public List<String> getDenyListHeaders() {
// return denyListHeaders;
// }
//
// public String getApiSecret() {
// return apiSecret;
// }
//
// /**
// * Gets the App Id, when it exists
// *
// * @return A string representing the AppID
// * @throws CastleRuntimeException when there is no App Id
// */
// public String getCastleAppId() throws CastleRuntimeException {
// if (castleAppId == null || castleAppId.isEmpty()) {
// throw new CastleRuntimeException("AppId was not specified");
// } else {
// return castleAppId;
// }
// }
//
// public CastleBackendProvider getBackendProvider() {
// return backendProvider;
// }
//
// public boolean isLogHttpRequests() {
// return logHttpRequests;
// }
//
// public List<String> getIpHeaders() {
// return ipHeaders;
// }
//
// public int getMaxRequests() {
// return maxRequests;
// }
// }
//
// Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
// Path: src/main/java/io/castle/client/internal/backend/OkHttpFactory.java
import com.google.common.collect.ImmutableList;
import io.castle.client.internal.config.CastleConfiguration;
import io.castle.client.internal.json.CastleGsonModel;
import okhttp3.*;
import okhttp3.logging.HttpLoggingInterceptor;
import java.io.IOException;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
package io.castle.client.internal.backend;
public class OkHttpFactory implements RestApiFactory {
private final OkHttpClient client;
private final CastleGsonModel modelInstance; | private final CastleConfiguration configuration; |
castle/castle-java | src/test/java/io/castle/client/SdkMockUtil.java | // Path: src/main/java/io/castle/client/internal/backend/RestApiFactory.java
// public interface RestApiFactory {
//
// RestApi buildBackend();
// }
//
// Path: src/main/java/io/castle/client/internal/config/CastleSdkInternalConfiguration.java
// public class CastleSdkInternalConfiguration {
//
// private final RestApiFactory restApiFactory;
// private final CastleGsonModel model;
// private final CastleConfiguration configuration;
//
// private final SecretKey sha256Key;
//
// private CastleSdkInternalConfiguration(RestApiFactory restApiFactory, CastleGsonModel model, CastleConfiguration configuration) {
// this.restApiFactory = restApiFactory;
// this.model = model;
// this.configuration = configuration;
// this.sha256Key = new SecretKeySpec(configuration.getApiSecret().getBytes(Charsets.UTF_8), "HmacSHA256");
// }
//
// public static CastleSdkInternalConfiguration getInternalConfiguration() throws CastleSdkConfigurationException {
// CastleGsonModel modelInstance = new CastleGsonModel();
// CastleConfiguration configuration = new ConfigurationLoader().loadConfiguration();
// RestApiFactory apiFactory = loadRestApiFactory(modelInstance, configuration);
// return new CastleSdkInternalConfiguration(apiFactory, modelInstance, configuration);
// }
//
// public static CastleSdkInternalConfiguration buildFromConfiguration(CastleConfiguration config) {
// CastleGsonModel modelInstance = new CastleGsonModel();
// RestApiFactory apiFactory = loadRestApiFactory(modelInstance, config);
// return new CastleSdkInternalConfiguration(apiFactory, modelInstance, config);
// }
//
// public static CastleConfigurationBuilder builderFromConfigurationLoader() {
// return new ConfigurationLoader().loadConfigurationBuilder();
// }
//
// /**
// * Currently only the okHttp backend is available.
// *
// * @param modelInstance GSON model instance to use.
// * @param configuration CastleConfiguration instance.
// * @return The configured RestApiFactory to make backend REST calls.
// */
// private static RestApiFactory loadRestApiFactory(final CastleGsonModel modelInstance, final CastleConfiguration configuration) {
// return new OkHttpFactory(configuration, modelInstance);
// }
//
//
// public CastleGsonModel getModel() {
// return model;
// }
//
// public RestApiFactory getRestApiFactory() {
// return restApiFactory;
// }
//
// public CastleConfiguration getConfiguration() {
// return configuration;
// }
//
// public HashFunction getSecureHashFunction() {
// return Hashing.hmacSha256(sha256Key);
// }
// }
| import io.castle.client.internal.backend.RestApiFactory;
import io.castle.client.internal.config.CastleSdkInternalConfiguration;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier; | package io.castle.client;
public class SdkMockUtil {
public static void modifyInternalBackendFactory(Castle sdkInstance, RestApiFactory restApiFactoryToReplace) throws NoSuchFieldException, IllegalAccessException { | // Path: src/main/java/io/castle/client/internal/backend/RestApiFactory.java
// public interface RestApiFactory {
//
// RestApi buildBackend();
// }
//
// Path: src/main/java/io/castle/client/internal/config/CastleSdkInternalConfiguration.java
// public class CastleSdkInternalConfiguration {
//
// private final RestApiFactory restApiFactory;
// private final CastleGsonModel model;
// private final CastleConfiguration configuration;
//
// private final SecretKey sha256Key;
//
// private CastleSdkInternalConfiguration(RestApiFactory restApiFactory, CastleGsonModel model, CastleConfiguration configuration) {
// this.restApiFactory = restApiFactory;
// this.model = model;
// this.configuration = configuration;
// this.sha256Key = new SecretKeySpec(configuration.getApiSecret().getBytes(Charsets.UTF_8), "HmacSHA256");
// }
//
// public static CastleSdkInternalConfiguration getInternalConfiguration() throws CastleSdkConfigurationException {
// CastleGsonModel modelInstance = new CastleGsonModel();
// CastleConfiguration configuration = new ConfigurationLoader().loadConfiguration();
// RestApiFactory apiFactory = loadRestApiFactory(modelInstance, configuration);
// return new CastleSdkInternalConfiguration(apiFactory, modelInstance, configuration);
// }
//
// public static CastleSdkInternalConfiguration buildFromConfiguration(CastleConfiguration config) {
// CastleGsonModel modelInstance = new CastleGsonModel();
// RestApiFactory apiFactory = loadRestApiFactory(modelInstance, config);
// return new CastleSdkInternalConfiguration(apiFactory, modelInstance, config);
// }
//
// public static CastleConfigurationBuilder builderFromConfigurationLoader() {
// return new ConfigurationLoader().loadConfigurationBuilder();
// }
//
// /**
// * Currently only the okHttp backend is available.
// *
// * @param modelInstance GSON model instance to use.
// * @param configuration CastleConfiguration instance.
// * @return The configured RestApiFactory to make backend REST calls.
// */
// private static RestApiFactory loadRestApiFactory(final CastleGsonModel modelInstance, final CastleConfiguration configuration) {
// return new OkHttpFactory(configuration, modelInstance);
// }
//
//
// public CastleGsonModel getModel() {
// return model;
// }
//
// public RestApiFactory getRestApiFactory() {
// return restApiFactory;
// }
//
// public CastleConfiguration getConfiguration() {
// return configuration;
// }
//
// public HashFunction getSecureHashFunction() {
// return Hashing.hmacSha256(sha256Key);
// }
// }
// Path: src/test/java/io/castle/client/SdkMockUtil.java
import io.castle.client.internal.backend.RestApiFactory;
import io.castle.client.internal.config.CastleSdkInternalConfiguration;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
package io.castle.client;
public class SdkMockUtil {
public static void modifyInternalBackendFactory(Castle sdkInstance, RestApiFactory restApiFactoryToReplace) throws NoSuchFieldException, IllegalAccessException { | CastleSdkInternalConfiguration internalConfiguration = sdkInstance.getInternalConfiguration(); |
castle/castle-java | src/main/java/io/castle/client/model/CastleResponse.java | // Path: src/main/java/io/castle/client/internal/utils/OkHttpExceptionUtil.java
// public class OkHttpExceptionUtil {
//
// public static CastleRuntimeException handle(IOException e) {
// if (e instanceof SocketTimeoutException) {
// return new CastleApiTimeoutException(e);
// }
// return new CastleRuntimeException(e);
// }
//
// public static void handle(Response response) throws CastleServerErrorException {
// if (!response.isSuccessful() && !response.isRedirect()) {
// if (response.code() == 500) {
// throw new CastleApiInternalServerErrorException(response);
// }
// if (response.code() == 422) {
// try {
// String body = response.peekBody(Long.MAX_VALUE).string();
// JsonParser jsonParser = new JsonParser();
// JsonObject json = (JsonObject) jsonParser.parse(body);
// String type = json.get("type").getAsString();
//
// if (type.equals("invalid_request_token")) {
// throw new CastleApiInvalidRequestTokenErrorException(response);
// }
// } catch (IOException | JsonSyntaxException |JsonIOException ignored) {}
// throw new CastleApiInvalidParametersErrorException(response);
// }
// throw new CastleServerErrorException(response);
// }
// }
// }
| import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import io.castle.client.internal.utils.OkHttpExceptionUtil;
import okhttp3.Response;
import java.io.IOException; | package io.castle.client.model;
public class CastleResponse {
private final int code;
private final JsonElement json;
public CastleResponse(Response response) throws IOException {
code = response.code();
String body = response.body().string();
JsonParser gson = new JsonParser();
json = gson.parse(body);
| // Path: src/main/java/io/castle/client/internal/utils/OkHttpExceptionUtil.java
// public class OkHttpExceptionUtil {
//
// public static CastleRuntimeException handle(IOException e) {
// if (e instanceof SocketTimeoutException) {
// return new CastleApiTimeoutException(e);
// }
// return new CastleRuntimeException(e);
// }
//
// public static void handle(Response response) throws CastleServerErrorException {
// if (!response.isSuccessful() && !response.isRedirect()) {
// if (response.code() == 500) {
// throw new CastleApiInternalServerErrorException(response);
// }
// if (response.code() == 422) {
// try {
// String body = response.peekBody(Long.MAX_VALUE).string();
// JsonParser jsonParser = new JsonParser();
// JsonObject json = (JsonObject) jsonParser.parse(body);
// String type = json.get("type").getAsString();
//
// if (type.equals("invalid_request_token")) {
// throw new CastleApiInvalidRequestTokenErrorException(response);
// }
// } catch (IOException | JsonSyntaxException |JsonIOException ignored) {}
// throw new CastleApiInvalidParametersErrorException(response);
// }
// throw new CastleServerErrorException(response);
// }
// }
// }
// Path: src/main/java/io/castle/client/model/CastleResponse.java
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import io.castle.client.internal.utils.OkHttpExceptionUtil;
import okhttp3.Response;
import java.io.IOException;
package io.castle.client.model;
public class CastleResponse {
private final int code;
private final JsonElement json;
public CastleResponse(Response response) throws IOException {
code = response.code();
String body = response.body().string();
JsonParser gson = new JsonParser();
json = gson.parse(body);
| OkHttpExceptionUtil.handle(response); |
castle/castle-java | src/main/java/io/castle/client/internal/config/CastleSdkInternalConfiguration.java | // Path: src/main/java/io/castle/client/internal/backend/OkHttpFactory.java
// public class OkHttpFactory implements RestApiFactory {
//
// private final OkHttpClient client;
// private final CastleGsonModel modelInstance;
// private final CastleConfiguration configuration;
//
// public OkHttpFactory(CastleConfiguration configuration, CastleGsonModel modelInstance) {
// this.configuration = configuration;
// this.modelInstance = modelInstance;
// client = createOkHttpClient();
// }
//
// private OkHttpClient createOkHttpClient() {
// final String credential = Credentials.basic("", configuration.getApiSecret());
//
// Dispatcher dispatcher = new Dispatcher();
// dispatcher.setMaxRequests(configuration.getMaxRequests());
// dispatcher.setMaxRequestsPerHost(configuration.getMaxRequests());
//
// OkHttpClient.Builder builder = new OkHttpClient()
// .newBuilder()
// .connectTimeout(configuration.getTimeout(), TimeUnit.MILLISECONDS)
// .readTimeout(configuration.getTimeout(), TimeUnit.MILLISECONDS)
// .dispatcher(dispatcher)
// .writeTimeout(configuration.getTimeout(), TimeUnit.MILLISECONDS);
// if (configuration.isLogHttpRequests()) {
// HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// // TODO provide more configurable logging features.
// logging.setLevel(HttpLoggingInterceptor.Level.BODY);
// builder = builder.addInterceptor(logging);
// }
//
// OkHttpClient client = builder
// .addInterceptor(new Interceptor() {
// @Override
// public Response intercept(Chain chain) throws IOException {
// Request request = chain.request();
// Request authenticatedRequest = request.newBuilder()
// .header("Authorization", credential).build();
// return chain.proceed(authenticatedRequest);
// }
// })
// .connectionSpecs(ImmutableList.of(ConnectionSpec.COMPATIBLE_TLS, ConnectionSpec.CLEARTEXT))
// .build();
//
// return client;
// }
//
// @Override
// public RestApi buildBackend() {
// return new OkRestApiBackend(client, modelInstance, configuration);
// }
// }
//
// Path: src/main/java/io/castle/client/internal/backend/RestApiFactory.java
// public interface RestApiFactory {
//
// RestApi buildBackend();
// }
//
// Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
| import com.google.common.base.Charsets;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import io.castle.client.internal.backend.OkHttpFactory;
import io.castle.client.internal.backend.RestApiFactory;
import io.castle.client.internal.json.CastleGsonModel;
import io.castle.client.model.CastleSdkConfigurationException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec; | package io.castle.client.internal.config;
public class CastleSdkInternalConfiguration {
private final RestApiFactory restApiFactory; | // Path: src/main/java/io/castle/client/internal/backend/OkHttpFactory.java
// public class OkHttpFactory implements RestApiFactory {
//
// private final OkHttpClient client;
// private final CastleGsonModel modelInstance;
// private final CastleConfiguration configuration;
//
// public OkHttpFactory(CastleConfiguration configuration, CastleGsonModel modelInstance) {
// this.configuration = configuration;
// this.modelInstance = modelInstance;
// client = createOkHttpClient();
// }
//
// private OkHttpClient createOkHttpClient() {
// final String credential = Credentials.basic("", configuration.getApiSecret());
//
// Dispatcher dispatcher = new Dispatcher();
// dispatcher.setMaxRequests(configuration.getMaxRequests());
// dispatcher.setMaxRequestsPerHost(configuration.getMaxRequests());
//
// OkHttpClient.Builder builder = new OkHttpClient()
// .newBuilder()
// .connectTimeout(configuration.getTimeout(), TimeUnit.MILLISECONDS)
// .readTimeout(configuration.getTimeout(), TimeUnit.MILLISECONDS)
// .dispatcher(dispatcher)
// .writeTimeout(configuration.getTimeout(), TimeUnit.MILLISECONDS);
// if (configuration.isLogHttpRequests()) {
// HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// // TODO provide more configurable logging features.
// logging.setLevel(HttpLoggingInterceptor.Level.BODY);
// builder = builder.addInterceptor(logging);
// }
//
// OkHttpClient client = builder
// .addInterceptor(new Interceptor() {
// @Override
// public Response intercept(Chain chain) throws IOException {
// Request request = chain.request();
// Request authenticatedRequest = request.newBuilder()
// .header("Authorization", credential).build();
// return chain.proceed(authenticatedRequest);
// }
// })
// .connectionSpecs(ImmutableList.of(ConnectionSpec.COMPATIBLE_TLS, ConnectionSpec.CLEARTEXT))
// .build();
//
// return client;
// }
//
// @Override
// public RestApi buildBackend() {
// return new OkRestApiBackend(client, modelInstance, configuration);
// }
// }
//
// Path: src/main/java/io/castle/client/internal/backend/RestApiFactory.java
// public interface RestApiFactory {
//
// RestApi buildBackend();
// }
//
// Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
// Path: src/main/java/io/castle/client/internal/config/CastleSdkInternalConfiguration.java
import com.google.common.base.Charsets;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import io.castle.client.internal.backend.OkHttpFactory;
import io.castle.client.internal.backend.RestApiFactory;
import io.castle.client.internal.json.CastleGsonModel;
import io.castle.client.model.CastleSdkConfigurationException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
package io.castle.client.internal.config;
public class CastleSdkInternalConfiguration {
private final RestApiFactory restApiFactory; | private final CastleGsonModel model; |
castle/castle-java | src/main/java/io/castle/client/internal/config/CastleSdkInternalConfiguration.java | // Path: src/main/java/io/castle/client/internal/backend/OkHttpFactory.java
// public class OkHttpFactory implements RestApiFactory {
//
// private final OkHttpClient client;
// private final CastleGsonModel modelInstance;
// private final CastleConfiguration configuration;
//
// public OkHttpFactory(CastleConfiguration configuration, CastleGsonModel modelInstance) {
// this.configuration = configuration;
// this.modelInstance = modelInstance;
// client = createOkHttpClient();
// }
//
// private OkHttpClient createOkHttpClient() {
// final String credential = Credentials.basic("", configuration.getApiSecret());
//
// Dispatcher dispatcher = new Dispatcher();
// dispatcher.setMaxRequests(configuration.getMaxRequests());
// dispatcher.setMaxRequestsPerHost(configuration.getMaxRequests());
//
// OkHttpClient.Builder builder = new OkHttpClient()
// .newBuilder()
// .connectTimeout(configuration.getTimeout(), TimeUnit.MILLISECONDS)
// .readTimeout(configuration.getTimeout(), TimeUnit.MILLISECONDS)
// .dispatcher(dispatcher)
// .writeTimeout(configuration.getTimeout(), TimeUnit.MILLISECONDS);
// if (configuration.isLogHttpRequests()) {
// HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// // TODO provide more configurable logging features.
// logging.setLevel(HttpLoggingInterceptor.Level.BODY);
// builder = builder.addInterceptor(logging);
// }
//
// OkHttpClient client = builder
// .addInterceptor(new Interceptor() {
// @Override
// public Response intercept(Chain chain) throws IOException {
// Request request = chain.request();
// Request authenticatedRequest = request.newBuilder()
// .header("Authorization", credential).build();
// return chain.proceed(authenticatedRequest);
// }
// })
// .connectionSpecs(ImmutableList.of(ConnectionSpec.COMPATIBLE_TLS, ConnectionSpec.CLEARTEXT))
// .build();
//
// return client;
// }
//
// @Override
// public RestApi buildBackend() {
// return new OkRestApiBackend(client, modelInstance, configuration);
// }
// }
//
// Path: src/main/java/io/castle/client/internal/backend/RestApiFactory.java
// public interface RestApiFactory {
//
// RestApi buildBackend();
// }
//
// Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
| import com.google.common.base.Charsets;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import io.castle.client.internal.backend.OkHttpFactory;
import io.castle.client.internal.backend.RestApiFactory;
import io.castle.client.internal.json.CastleGsonModel;
import io.castle.client.model.CastleSdkConfigurationException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec; | package io.castle.client.internal.config;
public class CastleSdkInternalConfiguration {
private final RestApiFactory restApiFactory;
private final CastleGsonModel model;
private final CastleConfiguration configuration;
private final SecretKey sha256Key;
private CastleSdkInternalConfiguration(RestApiFactory restApiFactory, CastleGsonModel model, CastleConfiguration configuration) {
this.restApiFactory = restApiFactory;
this.model = model;
this.configuration = configuration;
this.sha256Key = new SecretKeySpec(configuration.getApiSecret().getBytes(Charsets.UTF_8), "HmacSHA256");
}
| // Path: src/main/java/io/castle/client/internal/backend/OkHttpFactory.java
// public class OkHttpFactory implements RestApiFactory {
//
// private final OkHttpClient client;
// private final CastleGsonModel modelInstance;
// private final CastleConfiguration configuration;
//
// public OkHttpFactory(CastleConfiguration configuration, CastleGsonModel modelInstance) {
// this.configuration = configuration;
// this.modelInstance = modelInstance;
// client = createOkHttpClient();
// }
//
// private OkHttpClient createOkHttpClient() {
// final String credential = Credentials.basic("", configuration.getApiSecret());
//
// Dispatcher dispatcher = new Dispatcher();
// dispatcher.setMaxRequests(configuration.getMaxRequests());
// dispatcher.setMaxRequestsPerHost(configuration.getMaxRequests());
//
// OkHttpClient.Builder builder = new OkHttpClient()
// .newBuilder()
// .connectTimeout(configuration.getTimeout(), TimeUnit.MILLISECONDS)
// .readTimeout(configuration.getTimeout(), TimeUnit.MILLISECONDS)
// .dispatcher(dispatcher)
// .writeTimeout(configuration.getTimeout(), TimeUnit.MILLISECONDS);
// if (configuration.isLogHttpRequests()) {
// HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// // TODO provide more configurable logging features.
// logging.setLevel(HttpLoggingInterceptor.Level.BODY);
// builder = builder.addInterceptor(logging);
// }
//
// OkHttpClient client = builder
// .addInterceptor(new Interceptor() {
// @Override
// public Response intercept(Chain chain) throws IOException {
// Request request = chain.request();
// Request authenticatedRequest = request.newBuilder()
// .header("Authorization", credential).build();
// return chain.proceed(authenticatedRequest);
// }
// })
// .connectionSpecs(ImmutableList.of(ConnectionSpec.COMPATIBLE_TLS, ConnectionSpec.CLEARTEXT))
// .build();
//
// return client;
// }
//
// @Override
// public RestApi buildBackend() {
// return new OkRestApiBackend(client, modelInstance, configuration);
// }
// }
//
// Path: src/main/java/io/castle/client/internal/backend/RestApiFactory.java
// public interface RestApiFactory {
//
// RestApi buildBackend();
// }
//
// Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
// Path: src/main/java/io/castle/client/internal/config/CastleSdkInternalConfiguration.java
import com.google.common.base.Charsets;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import io.castle.client.internal.backend.OkHttpFactory;
import io.castle.client.internal.backend.RestApiFactory;
import io.castle.client.internal.json.CastleGsonModel;
import io.castle.client.model.CastleSdkConfigurationException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
package io.castle.client.internal.config;
public class CastleSdkInternalConfiguration {
private final RestApiFactory restApiFactory;
private final CastleGsonModel model;
private final CastleConfiguration configuration;
private final SecretKey sha256Key;
private CastleSdkInternalConfiguration(RestApiFactory restApiFactory, CastleGsonModel model, CastleConfiguration configuration) {
this.restApiFactory = restApiFactory;
this.model = model;
this.configuration = configuration;
this.sha256Key = new SecretKeySpec(configuration.getApiSecret().getBytes(Charsets.UTF_8), "HmacSHA256");
}
| public static CastleSdkInternalConfiguration getInternalConfiguration() throws CastleSdkConfigurationException { |
castle/castle-java | src/main/java/io/castle/client/internal/config/CastleSdkInternalConfiguration.java | // Path: src/main/java/io/castle/client/internal/backend/OkHttpFactory.java
// public class OkHttpFactory implements RestApiFactory {
//
// private final OkHttpClient client;
// private final CastleGsonModel modelInstance;
// private final CastleConfiguration configuration;
//
// public OkHttpFactory(CastleConfiguration configuration, CastleGsonModel modelInstance) {
// this.configuration = configuration;
// this.modelInstance = modelInstance;
// client = createOkHttpClient();
// }
//
// private OkHttpClient createOkHttpClient() {
// final String credential = Credentials.basic("", configuration.getApiSecret());
//
// Dispatcher dispatcher = new Dispatcher();
// dispatcher.setMaxRequests(configuration.getMaxRequests());
// dispatcher.setMaxRequestsPerHost(configuration.getMaxRequests());
//
// OkHttpClient.Builder builder = new OkHttpClient()
// .newBuilder()
// .connectTimeout(configuration.getTimeout(), TimeUnit.MILLISECONDS)
// .readTimeout(configuration.getTimeout(), TimeUnit.MILLISECONDS)
// .dispatcher(dispatcher)
// .writeTimeout(configuration.getTimeout(), TimeUnit.MILLISECONDS);
// if (configuration.isLogHttpRequests()) {
// HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// // TODO provide more configurable logging features.
// logging.setLevel(HttpLoggingInterceptor.Level.BODY);
// builder = builder.addInterceptor(logging);
// }
//
// OkHttpClient client = builder
// .addInterceptor(new Interceptor() {
// @Override
// public Response intercept(Chain chain) throws IOException {
// Request request = chain.request();
// Request authenticatedRequest = request.newBuilder()
// .header("Authorization", credential).build();
// return chain.proceed(authenticatedRequest);
// }
// })
// .connectionSpecs(ImmutableList.of(ConnectionSpec.COMPATIBLE_TLS, ConnectionSpec.CLEARTEXT))
// .build();
//
// return client;
// }
//
// @Override
// public RestApi buildBackend() {
// return new OkRestApiBackend(client, modelInstance, configuration);
// }
// }
//
// Path: src/main/java/io/castle/client/internal/backend/RestApiFactory.java
// public interface RestApiFactory {
//
// RestApi buildBackend();
// }
//
// Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
| import com.google.common.base.Charsets;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import io.castle.client.internal.backend.OkHttpFactory;
import io.castle.client.internal.backend.RestApiFactory;
import io.castle.client.internal.json.CastleGsonModel;
import io.castle.client.model.CastleSdkConfigurationException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec; | package io.castle.client.internal.config;
public class CastleSdkInternalConfiguration {
private final RestApiFactory restApiFactory;
private final CastleGsonModel model;
private final CastleConfiguration configuration;
private final SecretKey sha256Key;
private CastleSdkInternalConfiguration(RestApiFactory restApiFactory, CastleGsonModel model, CastleConfiguration configuration) {
this.restApiFactory = restApiFactory;
this.model = model;
this.configuration = configuration;
this.sha256Key = new SecretKeySpec(configuration.getApiSecret().getBytes(Charsets.UTF_8), "HmacSHA256");
}
public static CastleSdkInternalConfiguration getInternalConfiguration() throws CastleSdkConfigurationException {
CastleGsonModel modelInstance = new CastleGsonModel();
CastleConfiguration configuration = new ConfigurationLoader().loadConfiguration();
RestApiFactory apiFactory = loadRestApiFactory(modelInstance, configuration);
return new CastleSdkInternalConfiguration(apiFactory, modelInstance, configuration);
}
public static CastleSdkInternalConfiguration buildFromConfiguration(CastleConfiguration config) {
CastleGsonModel modelInstance = new CastleGsonModel();
RestApiFactory apiFactory = loadRestApiFactory(modelInstance, config);
return new CastleSdkInternalConfiguration(apiFactory, modelInstance, config);
}
public static CastleConfigurationBuilder builderFromConfigurationLoader() {
return new ConfigurationLoader().loadConfigurationBuilder();
}
/**
* Currently only the okHttp backend is available.
*
* @param modelInstance GSON model instance to use.
* @param configuration CastleConfiguration instance.
* @return The configured RestApiFactory to make backend REST calls.
*/
private static RestApiFactory loadRestApiFactory(final CastleGsonModel modelInstance, final CastleConfiguration configuration) { | // Path: src/main/java/io/castle/client/internal/backend/OkHttpFactory.java
// public class OkHttpFactory implements RestApiFactory {
//
// private final OkHttpClient client;
// private final CastleGsonModel modelInstance;
// private final CastleConfiguration configuration;
//
// public OkHttpFactory(CastleConfiguration configuration, CastleGsonModel modelInstance) {
// this.configuration = configuration;
// this.modelInstance = modelInstance;
// client = createOkHttpClient();
// }
//
// private OkHttpClient createOkHttpClient() {
// final String credential = Credentials.basic("", configuration.getApiSecret());
//
// Dispatcher dispatcher = new Dispatcher();
// dispatcher.setMaxRequests(configuration.getMaxRequests());
// dispatcher.setMaxRequestsPerHost(configuration.getMaxRequests());
//
// OkHttpClient.Builder builder = new OkHttpClient()
// .newBuilder()
// .connectTimeout(configuration.getTimeout(), TimeUnit.MILLISECONDS)
// .readTimeout(configuration.getTimeout(), TimeUnit.MILLISECONDS)
// .dispatcher(dispatcher)
// .writeTimeout(configuration.getTimeout(), TimeUnit.MILLISECONDS);
// if (configuration.isLogHttpRequests()) {
// HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// // TODO provide more configurable logging features.
// logging.setLevel(HttpLoggingInterceptor.Level.BODY);
// builder = builder.addInterceptor(logging);
// }
//
// OkHttpClient client = builder
// .addInterceptor(new Interceptor() {
// @Override
// public Response intercept(Chain chain) throws IOException {
// Request request = chain.request();
// Request authenticatedRequest = request.newBuilder()
// .header("Authorization", credential).build();
// return chain.proceed(authenticatedRequest);
// }
// })
// .connectionSpecs(ImmutableList.of(ConnectionSpec.COMPATIBLE_TLS, ConnectionSpec.CLEARTEXT))
// .build();
//
// return client;
// }
//
// @Override
// public RestApi buildBackend() {
// return new OkRestApiBackend(client, modelInstance, configuration);
// }
// }
//
// Path: src/main/java/io/castle/client/internal/backend/RestApiFactory.java
// public interface RestApiFactory {
//
// RestApi buildBackend();
// }
//
// Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
// Path: src/main/java/io/castle/client/internal/config/CastleSdkInternalConfiguration.java
import com.google.common.base.Charsets;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import io.castle.client.internal.backend.OkHttpFactory;
import io.castle.client.internal.backend.RestApiFactory;
import io.castle.client.internal.json.CastleGsonModel;
import io.castle.client.model.CastleSdkConfigurationException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
package io.castle.client.internal.config;
public class CastleSdkInternalConfiguration {
private final RestApiFactory restApiFactory;
private final CastleGsonModel model;
private final CastleConfiguration configuration;
private final SecretKey sha256Key;
private CastleSdkInternalConfiguration(RestApiFactory restApiFactory, CastleGsonModel model, CastleConfiguration configuration) {
this.restApiFactory = restApiFactory;
this.model = model;
this.configuration = configuration;
this.sha256Key = new SecretKeySpec(configuration.getApiSecret().getBytes(Charsets.UTF_8), "HmacSHA256");
}
public static CastleSdkInternalConfiguration getInternalConfiguration() throws CastleSdkConfigurationException {
CastleGsonModel modelInstance = new CastleGsonModel();
CastleConfiguration configuration = new ConfigurationLoader().loadConfiguration();
RestApiFactory apiFactory = loadRestApiFactory(modelInstance, configuration);
return new CastleSdkInternalConfiguration(apiFactory, modelInstance, configuration);
}
public static CastleSdkInternalConfiguration buildFromConfiguration(CastleConfiguration config) {
CastleGsonModel modelInstance = new CastleGsonModel();
RestApiFactory apiFactory = loadRestApiFactory(modelInstance, config);
return new CastleSdkInternalConfiguration(apiFactory, modelInstance, config);
}
public static CastleConfigurationBuilder builderFromConfigurationLoader() {
return new ConfigurationLoader().loadConfigurationBuilder();
}
/**
* Currently only the okHttp backend is available.
*
* @param modelInstance GSON model instance to use.
* @param configuration CastleConfiguration instance.
* @return The configured RestApiFactory to make backend REST calls.
*/
private static RestApiFactory loadRestApiFactory(final CastleGsonModel modelInstance, final CastleConfiguration configuration) { | return new OkHttpFactory(configuration, modelInstance); |
castle/castle-java | src/test/java/io/castle/client/CastleExceptionTest.java | // Path: src/main/java/io/castle/client/internal/utils/OkHttpExceptionUtil.java
// public class OkHttpExceptionUtil {
//
// public static CastleRuntimeException handle(IOException e) {
// if (e instanceof SocketTimeoutException) {
// return new CastleApiTimeoutException(e);
// }
// return new CastleRuntimeException(e);
// }
//
// public static void handle(Response response) throws CastleServerErrorException {
// if (!response.isSuccessful() && !response.isRedirect()) {
// if (response.code() == 500) {
// throw new CastleApiInternalServerErrorException(response);
// }
// if (response.code() == 422) {
// try {
// String body = response.peekBody(Long.MAX_VALUE).string();
// JsonParser jsonParser = new JsonParser();
// JsonObject json = (JsonObject) jsonParser.parse(body);
// String type = json.get("type").getAsString();
//
// if (type.equals("invalid_request_token")) {
// throw new CastleApiInvalidRequestTokenErrorException(response);
// }
// } catch (IOException | JsonSyntaxException |JsonIOException ignored) {}
// throw new CastleApiInvalidParametersErrorException(response);
// }
// throw new CastleServerErrorException(response);
// }
// }
// }
| import io.castle.client.internal.utils.OkHttpExceptionUtil;
import io.castle.client.model.*;
import okhttp3.*;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.net.SocketTimeoutException; | package io.castle.client;
public class CastleExceptionTest {
private final MediaType JsonMediaType = MediaType.parse("application/json; charset=utf-8");
@Test(expected = CastleApiInternalServerErrorException.class)
public void serverError() {
//Given
Response response = new Response.Builder()
.code(500)
.request(new Request.Builder().url("http://localhost").build())
.protocol(Protocol.HTTP_1_1)
.message("Message")
.build();
| // Path: src/main/java/io/castle/client/internal/utils/OkHttpExceptionUtil.java
// public class OkHttpExceptionUtil {
//
// public static CastleRuntimeException handle(IOException e) {
// if (e instanceof SocketTimeoutException) {
// return new CastleApiTimeoutException(e);
// }
// return new CastleRuntimeException(e);
// }
//
// public static void handle(Response response) throws CastleServerErrorException {
// if (!response.isSuccessful() && !response.isRedirect()) {
// if (response.code() == 500) {
// throw new CastleApiInternalServerErrorException(response);
// }
// if (response.code() == 422) {
// try {
// String body = response.peekBody(Long.MAX_VALUE).string();
// JsonParser jsonParser = new JsonParser();
// JsonObject json = (JsonObject) jsonParser.parse(body);
// String type = json.get("type").getAsString();
//
// if (type.equals("invalid_request_token")) {
// throw new CastleApiInvalidRequestTokenErrorException(response);
// }
// } catch (IOException | JsonSyntaxException |JsonIOException ignored) {}
// throw new CastleApiInvalidParametersErrorException(response);
// }
// throw new CastleServerErrorException(response);
// }
// }
// }
// Path: src/test/java/io/castle/client/CastleExceptionTest.java
import io.castle.client.internal.utils.OkHttpExceptionUtil;
import io.castle.client.model.*;
import okhttp3.*;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.net.SocketTimeoutException;
package io.castle.client;
public class CastleExceptionTest {
private final MediaType JsonMediaType = MediaType.parse("application/json; charset=utf-8");
@Test(expected = CastleApiInternalServerErrorException.class)
public void serverError() {
//Given
Response response = new Response.Builder()
.code(500)
.request(new Request.Builder().url("http://localhost").build())
.protocol(Protocol.HTTP_1_1)
.message("Message")
.build();
| OkHttpExceptionUtil.handle(response); |
castle/castle-java | src/test/java/io/castle/client/CastleDeviceReportHttpTest.java | // Path: src/test/java/io/castle/client/utils/DeviceUtils.java
// public class DeviceUtils {
//
// public static final String DEVICE_TOKEN = "abcdefg12345";
// public static final double DEVICE_RISK = 0.000154;
// public static final String DEVICE_CREATED_AT = "2018-06-15T16:36:22.916Z";
// public static final String DEVICE_LAST_SEEN_AT = "2018-07-19T23:09:29.681Z";
// public static final String DEVICE_APPROVED_AT = null;
// public static final String DEVICE_ESCALATED_AT = null;
// public static final String DEVICE_MITIGATED_AT = null;
//
// public static final String CONTEXT_TYPE = "desktop";
// public static final String CONTEXT_IP = "1.1.1.1";
//
// public static final String USER_AGENT_FAMILY = "Opera";
// public static final String USER_AGENT_DEVICE = "Unknown";
// public static final String USER_AGENT_PLATFORM = "Mac OS X";
// public static final String USER_AGENT_OS = "Mac OS X 10.13.6";
// public static final String USER_AGENT_VERSION = "54.0.2952";
// public static final String USER_AGENT_BROWSER = "Opera";
// public static final String USER_AGENT_RAW = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51";
// public static final boolean USER_AGENT_MOBILE = false;
//
// public static CastleUserDevice createExpectedDevice() {
// CastleUserDevice device = new CastleUserDevice();
// device.setToken(DEVICE_TOKEN);
// device.setRisk(DEVICE_RISK);
// device.setCreatedAt(DEVICE_CREATED_AT);
// device.setLastSeenAt(DEVICE_LAST_SEEN_AT);
// device.setApprovedAt(null);
// device.setEscalatedAt(null);
// device.setMitigatedAt(null);
//
// CastleUserDeviceContext deviceContext = new CastleUserDeviceContext();
// deviceContext.setIp(CONTEXT_IP);
// deviceContext.setType(CONTEXT_TYPE);
//
// DeviceUserAgent userAgent = new DeviceUserAgent();
// userAgent.setFamily(USER_AGENT_FAMILY);
// userAgent.setDevice(USER_AGENT_DEVICE);
// userAgent.setPlatform(USER_AGENT_PLATFORM);
// userAgent.setOs(USER_AGENT_OS);
// userAgent.setVersion(USER_AGENT_VERSION);
// userAgent.setBrowser(USER_AGENT_BROWSER);
// userAgent.setRaw(USER_AGENT_RAW);
// userAgent.setMobile(USER_AGENT_MOBILE);
//
// deviceContext.setUserAgent(userAgent);
//
// device.setContext(deviceContext);
//
// return device;
// }
//
// public static CastleUserDevices createExpectedDevices() {
// CastleUserDevices devices = new CastleUserDevices();
// devices.setDevices(Arrays.asList(createExpectedDevice()));
// return devices;
// }
//
// public static String getDefaultDeviceJSON() {
// return "{\"token\":\"abcdefg12345\",\"risk\":0.000154,\"created_at\":\"2018-06-15T16:36:22.916Z\",\"last_seen_at\":\"2018-07-19T23:09:29.681Z\",\"approved_at\":null,\"escalated_at\":null,\"mitigated_at\":null,\"context\":{\"ip\":\"1.1.1.1\",\"location\":{\"country_code\":\"US\",\"country\":\"United States\",\"region\":\"New Jersey\",\"region_code\":\"NJ\",\"city\":\"Lyndhurst\",\"lat\":40.7923,\"lon\":-74.1001},\"user_agent\":{\"raw\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51\",\"browser\":\"Opera\",\"version\":\"54.0.2952\",\"os\":\"Mac OS X 10.13.6\",\"mobile\":false,\"platform\":\"Mac OS X\",\"device\":\"Unknown\",\"family\":\"Opera\"},\"type\":\"desktop\"}}";
// }
// }
| import io.castle.client.model.*;
import io.castle.client.utils.DeviceUtils;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import static okhttp3.mockwebserver.SocketPolicy.NO_RESPONSE; | package io.castle.client;
public class CastleDeviceReportHttpTest extends AbstractCastleHttpLayerTest {
public CastleDeviceReportHttpTest() {
super(new AuthenticateFailoverStrategy(AuthenticateAction.CHALLENGE));
}
@Test public void reportDevice() throws InterruptedException {
MockResponse mockResponse = new MockResponse(); | // Path: src/test/java/io/castle/client/utils/DeviceUtils.java
// public class DeviceUtils {
//
// public static final String DEVICE_TOKEN = "abcdefg12345";
// public static final double DEVICE_RISK = 0.000154;
// public static final String DEVICE_CREATED_AT = "2018-06-15T16:36:22.916Z";
// public static final String DEVICE_LAST_SEEN_AT = "2018-07-19T23:09:29.681Z";
// public static final String DEVICE_APPROVED_AT = null;
// public static final String DEVICE_ESCALATED_AT = null;
// public static final String DEVICE_MITIGATED_AT = null;
//
// public static final String CONTEXT_TYPE = "desktop";
// public static final String CONTEXT_IP = "1.1.1.1";
//
// public static final String USER_AGENT_FAMILY = "Opera";
// public static final String USER_AGENT_DEVICE = "Unknown";
// public static final String USER_AGENT_PLATFORM = "Mac OS X";
// public static final String USER_AGENT_OS = "Mac OS X 10.13.6";
// public static final String USER_AGENT_VERSION = "54.0.2952";
// public static final String USER_AGENT_BROWSER = "Opera";
// public static final String USER_AGENT_RAW = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51";
// public static final boolean USER_AGENT_MOBILE = false;
//
// public static CastleUserDevice createExpectedDevice() {
// CastleUserDevice device = new CastleUserDevice();
// device.setToken(DEVICE_TOKEN);
// device.setRisk(DEVICE_RISK);
// device.setCreatedAt(DEVICE_CREATED_AT);
// device.setLastSeenAt(DEVICE_LAST_SEEN_AT);
// device.setApprovedAt(null);
// device.setEscalatedAt(null);
// device.setMitigatedAt(null);
//
// CastleUserDeviceContext deviceContext = new CastleUserDeviceContext();
// deviceContext.setIp(CONTEXT_IP);
// deviceContext.setType(CONTEXT_TYPE);
//
// DeviceUserAgent userAgent = new DeviceUserAgent();
// userAgent.setFamily(USER_AGENT_FAMILY);
// userAgent.setDevice(USER_AGENT_DEVICE);
// userAgent.setPlatform(USER_AGENT_PLATFORM);
// userAgent.setOs(USER_AGENT_OS);
// userAgent.setVersion(USER_AGENT_VERSION);
// userAgent.setBrowser(USER_AGENT_BROWSER);
// userAgent.setRaw(USER_AGENT_RAW);
// userAgent.setMobile(USER_AGENT_MOBILE);
//
// deviceContext.setUserAgent(userAgent);
//
// device.setContext(deviceContext);
//
// return device;
// }
//
// public static CastleUserDevices createExpectedDevices() {
// CastleUserDevices devices = new CastleUserDevices();
// devices.setDevices(Arrays.asList(createExpectedDevice()));
// return devices;
// }
//
// public static String getDefaultDeviceJSON() {
// return "{\"token\":\"abcdefg12345\",\"risk\":0.000154,\"created_at\":\"2018-06-15T16:36:22.916Z\",\"last_seen_at\":\"2018-07-19T23:09:29.681Z\",\"approved_at\":null,\"escalated_at\":null,\"mitigated_at\":null,\"context\":{\"ip\":\"1.1.1.1\",\"location\":{\"country_code\":\"US\",\"country\":\"United States\",\"region\":\"New Jersey\",\"region_code\":\"NJ\",\"city\":\"Lyndhurst\",\"lat\":40.7923,\"lon\":-74.1001},\"user_agent\":{\"raw\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51\",\"browser\":\"Opera\",\"version\":\"54.0.2952\",\"os\":\"Mac OS X 10.13.6\",\"mobile\":false,\"platform\":\"Mac OS X\",\"device\":\"Unknown\",\"family\":\"Opera\"},\"type\":\"desktop\"}}";
// }
// }
// Path: src/test/java/io/castle/client/CastleDeviceReportHttpTest.java
import io.castle.client.model.*;
import io.castle.client.utils.DeviceUtils;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import static okhttp3.mockwebserver.SocketPolicy.NO_RESPONSE;
package io.castle.client;
public class CastleDeviceReportHttpTest extends AbstractCastleHttpLayerTest {
public CastleDeviceReportHttpTest() {
super(new AuthenticateFailoverStrategy(AuthenticateAction.CHALLENGE));
}
@Test public void reportDevice() throws InterruptedException {
MockResponse mockResponse = new MockResponse(); | mockResponse.setBody(DeviceUtils.getDefaultDeviceJSON()); |
castle/castle-java | src/test/java/io/castle/client/model/DeviceUserAgentTest.java | // Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
//
// Path: src/test/java/io/castle/client/utils/DeviceUtils.java
// public class DeviceUtils {
//
// public static final String DEVICE_TOKEN = "abcdefg12345";
// public static final double DEVICE_RISK = 0.000154;
// public static final String DEVICE_CREATED_AT = "2018-06-15T16:36:22.916Z";
// public static final String DEVICE_LAST_SEEN_AT = "2018-07-19T23:09:29.681Z";
// public static final String DEVICE_APPROVED_AT = null;
// public static final String DEVICE_ESCALATED_AT = null;
// public static final String DEVICE_MITIGATED_AT = null;
//
// public static final String CONTEXT_TYPE = "desktop";
// public static final String CONTEXT_IP = "1.1.1.1";
//
// public static final String USER_AGENT_FAMILY = "Opera";
// public static final String USER_AGENT_DEVICE = "Unknown";
// public static final String USER_AGENT_PLATFORM = "Mac OS X";
// public static final String USER_AGENT_OS = "Mac OS X 10.13.6";
// public static final String USER_AGENT_VERSION = "54.0.2952";
// public static final String USER_AGENT_BROWSER = "Opera";
// public static final String USER_AGENT_RAW = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51";
// public static final boolean USER_AGENT_MOBILE = false;
//
// public static CastleUserDevice createExpectedDevice() {
// CastleUserDevice device = new CastleUserDevice();
// device.setToken(DEVICE_TOKEN);
// device.setRisk(DEVICE_RISK);
// device.setCreatedAt(DEVICE_CREATED_AT);
// device.setLastSeenAt(DEVICE_LAST_SEEN_AT);
// device.setApprovedAt(null);
// device.setEscalatedAt(null);
// device.setMitigatedAt(null);
//
// CastleUserDeviceContext deviceContext = new CastleUserDeviceContext();
// deviceContext.setIp(CONTEXT_IP);
// deviceContext.setType(CONTEXT_TYPE);
//
// DeviceUserAgent userAgent = new DeviceUserAgent();
// userAgent.setFamily(USER_AGENT_FAMILY);
// userAgent.setDevice(USER_AGENT_DEVICE);
// userAgent.setPlatform(USER_AGENT_PLATFORM);
// userAgent.setOs(USER_AGENT_OS);
// userAgent.setVersion(USER_AGENT_VERSION);
// userAgent.setBrowser(USER_AGENT_BROWSER);
// userAgent.setRaw(USER_AGENT_RAW);
// userAgent.setMobile(USER_AGENT_MOBILE);
//
// deviceContext.setUserAgent(userAgent);
//
// device.setContext(deviceContext);
//
// return device;
// }
//
// public static CastleUserDevices createExpectedDevices() {
// CastleUserDevices devices = new CastleUserDevices();
// devices.setDevices(Arrays.asList(createExpectedDevice()));
// return devices;
// }
//
// public static String getDefaultDeviceJSON() {
// return "{\"token\":\"abcdefg12345\",\"risk\":0.000154,\"created_at\":\"2018-06-15T16:36:22.916Z\",\"last_seen_at\":\"2018-07-19T23:09:29.681Z\",\"approved_at\":null,\"escalated_at\":null,\"mitigated_at\":null,\"context\":{\"ip\":\"1.1.1.1\",\"location\":{\"country_code\":\"US\",\"country\":\"United States\",\"region\":\"New Jersey\",\"region_code\":\"NJ\",\"city\":\"Lyndhurst\",\"lat\":40.7923,\"lon\":-74.1001},\"user_agent\":{\"raw\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51\",\"browser\":\"Opera\",\"version\":\"54.0.2952\",\"os\":\"Mac OS X 10.13.6\",\"mobile\":false,\"platform\":\"Mac OS X\",\"device\":\"Unknown\",\"family\":\"Opera\"},\"type\":\"desktop\"}}";
// }
// }
| import io.castle.client.internal.json.CastleGsonModel;
import io.castle.client.utils.DeviceUtils;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Test; | package io.castle.client.model;
public class DeviceUserAgentTest {
private CastleGsonModel model = new CastleGsonModel();
@Test
public void jsonSerialized() {
// Given
DeviceUserAgent userAgent = new DeviceUserAgent();
// When
String payloadJson = model.getGson().toJson(userAgent);
// Then
Assertions.assertThat(payloadJson).isEqualTo("{\"mobile\":false}");
}
@Test
public void fullBuilderJson() {
// Given
DeviceUserAgent userAgent = new DeviceUserAgent(); | // Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
//
// Path: src/test/java/io/castle/client/utils/DeviceUtils.java
// public class DeviceUtils {
//
// public static final String DEVICE_TOKEN = "abcdefg12345";
// public static final double DEVICE_RISK = 0.000154;
// public static final String DEVICE_CREATED_AT = "2018-06-15T16:36:22.916Z";
// public static final String DEVICE_LAST_SEEN_AT = "2018-07-19T23:09:29.681Z";
// public static final String DEVICE_APPROVED_AT = null;
// public static final String DEVICE_ESCALATED_AT = null;
// public static final String DEVICE_MITIGATED_AT = null;
//
// public static final String CONTEXT_TYPE = "desktop";
// public static final String CONTEXT_IP = "1.1.1.1";
//
// public static final String USER_AGENT_FAMILY = "Opera";
// public static final String USER_AGENT_DEVICE = "Unknown";
// public static final String USER_AGENT_PLATFORM = "Mac OS X";
// public static final String USER_AGENT_OS = "Mac OS X 10.13.6";
// public static final String USER_AGENT_VERSION = "54.0.2952";
// public static final String USER_AGENT_BROWSER = "Opera";
// public static final String USER_AGENT_RAW = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51";
// public static final boolean USER_AGENT_MOBILE = false;
//
// public static CastleUserDevice createExpectedDevice() {
// CastleUserDevice device = new CastleUserDevice();
// device.setToken(DEVICE_TOKEN);
// device.setRisk(DEVICE_RISK);
// device.setCreatedAt(DEVICE_CREATED_AT);
// device.setLastSeenAt(DEVICE_LAST_SEEN_AT);
// device.setApprovedAt(null);
// device.setEscalatedAt(null);
// device.setMitigatedAt(null);
//
// CastleUserDeviceContext deviceContext = new CastleUserDeviceContext();
// deviceContext.setIp(CONTEXT_IP);
// deviceContext.setType(CONTEXT_TYPE);
//
// DeviceUserAgent userAgent = new DeviceUserAgent();
// userAgent.setFamily(USER_AGENT_FAMILY);
// userAgent.setDevice(USER_AGENT_DEVICE);
// userAgent.setPlatform(USER_AGENT_PLATFORM);
// userAgent.setOs(USER_AGENT_OS);
// userAgent.setVersion(USER_AGENT_VERSION);
// userAgent.setBrowser(USER_AGENT_BROWSER);
// userAgent.setRaw(USER_AGENT_RAW);
// userAgent.setMobile(USER_AGENT_MOBILE);
//
// deviceContext.setUserAgent(userAgent);
//
// device.setContext(deviceContext);
//
// return device;
// }
//
// public static CastleUserDevices createExpectedDevices() {
// CastleUserDevices devices = new CastleUserDevices();
// devices.setDevices(Arrays.asList(createExpectedDevice()));
// return devices;
// }
//
// public static String getDefaultDeviceJSON() {
// return "{\"token\":\"abcdefg12345\",\"risk\":0.000154,\"created_at\":\"2018-06-15T16:36:22.916Z\",\"last_seen_at\":\"2018-07-19T23:09:29.681Z\",\"approved_at\":null,\"escalated_at\":null,\"mitigated_at\":null,\"context\":{\"ip\":\"1.1.1.1\",\"location\":{\"country_code\":\"US\",\"country\":\"United States\",\"region\":\"New Jersey\",\"region_code\":\"NJ\",\"city\":\"Lyndhurst\",\"lat\":40.7923,\"lon\":-74.1001},\"user_agent\":{\"raw\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51\",\"browser\":\"Opera\",\"version\":\"54.0.2952\",\"os\":\"Mac OS X 10.13.6\",\"mobile\":false,\"platform\":\"Mac OS X\",\"device\":\"Unknown\",\"family\":\"Opera\"},\"type\":\"desktop\"}}";
// }
// }
// Path: src/test/java/io/castle/client/model/DeviceUserAgentTest.java
import io.castle.client.internal.json.CastleGsonModel;
import io.castle.client.utils.DeviceUtils;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Test;
package io.castle.client.model;
public class DeviceUserAgentTest {
private CastleGsonModel model = new CastleGsonModel();
@Test
public void jsonSerialized() {
// Given
DeviceUserAgent userAgent = new DeviceUserAgent();
// When
String payloadJson = model.getGson().toJson(userAgent);
// Then
Assertions.assertThat(payloadJson).isEqualTo("{\"mobile\":false}");
}
@Test
public void fullBuilderJson() {
// Given
DeviceUserAgent userAgent = new DeviceUserAgent(); | userAgent.setBrowser(DeviceUtils.USER_AGENT_BROWSER); |
castle/castle-java | src/test/java/io/castle/client/internal/utils/VerdictTransportModelTest.java | // Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/RiskPolicyType.java
// public enum RiskPolicyType {
// BOT, AUTHENTICATION;
//
// /**
// * Returns an RiskPolicyType from a string representing its name.
// *
// * @param type string representing the name of the RiskPolicyType, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static RiskPolicyType fromType(String type) {
// for (RiskPolicyType kind : RiskPolicyType.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(type)) {
// return kind;
// }
// }
// return null;
// }
// }
| import io.castle.client.internal.json.CastleGsonModel;
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.RiskPolicyType;
import org.assertj.core.api.Assertions;
import org.junit.Test; | package io.castle.client.internal.utils;
public class VerdictTransportModelTest {
@Test
public void transportProtocolIsWellDeserialized() {
// given a json input value
String json = "{\n" +
" \"action\": \"deny\",\n" +
" \"user_id\": \"12345\",\n" +
" \"device_token\": \"abcdefg1234\",\n" +
" \"risk_policy\": {\n" +
" \"id\": \"q-rbeMzBTdW2Fd09sbz55A\",\n" +
" \"revision_id\": \"pke4zqO2TnqVr-NHJOAHEg\",\n" +
" \"name\": \"Block Users from X\",\n" +
" \"type\": \"bot\"\n" +
" }\n" +
"}";
// and castle gson model | // Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/RiskPolicyType.java
// public enum RiskPolicyType {
// BOT, AUTHENTICATION;
//
// /**
// * Returns an RiskPolicyType from a string representing its name.
// *
// * @param type string representing the name of the RiskPolicyType, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static RiskPolicyType fromType(String type) {
// for (RiskPolicyType kind : RiskPolicyType.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(type)) {
// return kind;
// }
// }
// return null;
// }
// }
// Path: src/test/java/io/castle/client/internal/utils/VerdictTransportModelTest.java
import io.castle.client.internal.json.CastleGsonModel;
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.RiskPolicyType;
import org.assertj.core.api.Assertions;
import org.junit.Test;
package io.castle.client.internal.utils;
public class VerdictTransportModelTest {
@Test
public void transportProtocolIsWellDeserialized() {
// given a json input value
String json = "{\n" +
" \"action\": \"deny\",\n" +
" \"user_id\": \"12345\",\n" +
" \"device_token\": \"abcdefg1234\",\n" +
" \"risk_policy\": {\n" +
" \"id\": \"q-rbeMzBTdW2Fd09sbz55A\",\n" +
" \"revision_id\": \"pke4zqO2TnqVr-NHJOAHEg\",\n" +
" \"name\": \"Block Users from X\",\n" +
" \"type\": \"bot\"\n" +
" }\n" +
"}";
// and castle gson model | CastleGsonModel model = new CastleGsonModel(); |
castle/castle-java | src/test/java/io/castle/client/internal/utils/VerdictTransportModelTest.java | // Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/RiskPolicyType.java
// public enum RiskPolicyType {
// BOT, AUTHENTICATION;
//
// /**
// * Returns an RiskPolicyType from a string representing its name.
// *
// * @param type string representing the name of the RiskPolicyType, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static RiskPolicyType fromType(String type) {
// for (RiskPolicyType kind : RiskPolicyType.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(type)) {
// return kind;
// }
// }
// return null;
// }
// }
| import io.castle.client.internal.json.CastleGsonModel;
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.RiskPolicyType;
import org.assertj.core.api.Assertions;
import org.junit.Test; | package io.castle.client.internal.utils;
public class VerdictTransportModelTest {
@Test
public void transportProtocolIsWellDeserialized() {
// given a json input value
String json = "{\n" +
" \"action\": \"deny\",\n" +
" \"user_id\": \"12345\",\n" +
" \"device_token\": \"abcdefg1234\",\n" +
" \"risk_policy\": {\n" +
" \"id\": \"q-rbeMzBTdW2Fd09sbz55A\",\n" +
" \"revision_id\": \"pke4zqO2TnqVr-NHJOAHEg\",\n" +
" \"name\": \"Block Users from X\",\n" +
" \"type\": \"bot\"\n" +
" }\n" +
"}";
// and castle gson model
CastleGsonModel model = new CastleGsonModel();
// when the Verdict transport object is deserialized
VerdictTransportModel loaded = model.getGson().fromJson(json, VerdictTransportModel.class);
| // Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/RiskPolicyType.java
// public enum RiskPolicyType {
// BOT, AUTHENTICATION;
//
// /**
// * Returns an RiskPolicyType from a string representing its name.
// *
// * @param type string representing the name of the RiskPolicyType, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static RiskPolicyType fromType(String type) {
// for (RiskPolicyType kind : RiskPolicyType.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(type)) {
// return kind;
// }
// }
// return null;
// }
// }
// Path: src/test/java/io/castle/client/internal/utils/VerdictTransportModelTest.java
import io.castle.client.internal.json.CastleGsonModel;
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.RiskPolicyType;
import org.assertj.core.api.Assertions;
import org.junit.Test;
package io.castle.client.internal.utils;
public class VerdictTransportModelTest {
@Test
public void transportProtocolIsWellDeserialized() {
// given a json input value
String json = "{\n" +
" \"action\": \"deny\",\n" +
" \"user_id\": \"12345\",\n" +
" \"device_token\": \"abcdefg1234\",\n" +
" \"risk_policy\": {\n" +
" \"id\": \"q-rbeMzBTdW2Fd09sbz55A\",\n" +
" \"revision_id\": \"pke4zqO2TnqVr-NHJOAHEg\",\n" +
" \"name\": \"Block Users from X\",\n" +
" \"type\": \"bot\"\n" +
" }\n" +
"}";
// and castle gson model
CastleGsonModel model = new CastleGsonModel();
// when the Verdict transport object is deserialized
VerdictTransportModel loaded = model.getGson().fromJson(json, VerdictTransportModel.class);
| Assertions.assertThat(loaded.getAction()).isEqualTo(AuthenticateAction.DENY); |
castle/castle-java | src/test/java/io/castle/client/internal/utils/VerdictTransportModelTest.java | // Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/RiskPolicyType.java
// public enum RiskPolicyType {
// BOT, AUTHENTICATION;
//
// /**
// * Returns an RiskPolicyType from a string representing its name.
// *
// * @param type string representing the name of the RiskPolicyType, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static RiskPolicyType fromType(String type) {
// for (RiskPolicyType kind : RiskPolicyType.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(type)) {
// return kind;
// }
// }
// return null;
// }
// }
| import io.castle.client.internal.json.CastleGsonModel;
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.RiskPolicyType;
import org.assertj.core.api.Assertions;
import org.junit.Test; | package io.castle.client.internal.utils;
public class VerdictTransportModelTest {
@Test
public void transportProtocolIsWellDeserialized() {
// given a json input value
String json = "{\n" +
" \"action\": \"deny\",\n" +
" \"user_id\": \"12345\",\n" +
" \"device_token\": \"abcdefg1234\",\n" +
" \"risk_policy\": {\n" +
" \"id\": \"q-rbeMzBTdW2Fd09sbz55A\",\n" +
" \"revision_id\": \"pke4zqO2TnqVr-NHJOAHEg\",\n" +
" \"name\": \"Block Users from X\",\n" +
" \"type\": \"bot\"\n" +
" }\n" +
"}";
// and castle gson model
CastleGsonModel model = new CastleGsonModel();
// when the Verdict transport object is deserialized
VerdictTransportModel loaded = model.getGson().fromJson(json, VerdictTransportModel.class);
Assertions.assertThat(loaded.getAction()).isEqualTo(AuthenticateAction.DENY);
Assertions.assertThat(loaded.getDeviceToken()).isEqualTo("abcdefg1234");
Assertions.assertThat(loaded.getUserId()).isEqualTo("12345");
Assertions.assertThat(loaded.getRiskPolicy().getId()).isEqualTo("q-rbeMzBTdW2Fd09sbz55A");
Assertions.assertThat(loaded.getRiskPolicy().getRevisionId()).isEqualTo("pke4zqO2TnqVr-NHJOAHEg");
Assertions.assertThat(loaded.getRiskPolicy().getName()).isEqualTo("Block Users from X"); | // Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
//
// Path: src/main/java/io/castle/client/model/AuthenticateAction.java
// public enum AuthenticateAction {
// ALLOW, DENY, CHALLENGE;
//
// /**
// * Returns an AuthenticateAction from a string representing its name.
// *
// * @param action string representing the name of the AuthenticateAction, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static AuthenticateAction fromAction(String action) {
// for (AuthenticateAction kind : AuthenticateAction.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(action)) {
// return kind;
// }
// }
// return null;
// }
// }
//
// Path: src/main/java/io/castle/client/model/RiskPolicyType.java
// public enum RiskPolicyType {
// BOT, AUTHENTICATION;
//
// /**
// * Returns an RiskPolicyType from a string representing its name.
// *
// * @param type string representing the name of the RiskPolicyType, case-insensitive
// * @return the enum value matching the name, or null if it does not match any enum
// */
// public static RiskPolicyType fromType(String type) {
// for (RiskPolicyType kind : RiskPolicyType.class.getEnumConstants()) {
// if (kind.name().equalsIgnoreCase(type)) {
// return kind;
// }
// }
// return null;
// }
// }
// Path: src/test/java/io/castle/client/internal/utils/VerdictTransportModelTest.java
import io.castle.client.internal.json.CastleGsonModel;
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.RiskPolicyType;
import org.assertj.core.api.Assertions;
import org.junit.Test;
package io.castle.client.internal.utils;
public class VerdictTransportModelTest {
@Test
public void transportProtocolIsWellDeserialized() {
// given a json input value
String json = "{\n" +
" \"action\": \"deny\",\n" +
" \"user_id\": \"12345\",\n" +
" \"device_token\": \"abcdefg1234\",\n" +
" \"risk_policy\": {\n" +
" \"id\": \"q-rbeMzBTdW2Fd09sbz55A\",\n" +
" \"revision_id\": \"pke4zqO2TnqVr-NHJOAHEg\",\n" +
" \"name\": \"Block Users from X\",\n" +
" \"type\": \"bot\"\n" +
" }\n" +
"}";
// and castle gson model
CastleGsonModel model = new CastleGsonModel();
// when the Verdict transport object is deserialized
VerdictTransportModel loaded = model.getGson().fromJson(json, VerdictTransportModel.class);
Assertions.assertThat(loaded.getAction()).isEqualTo(AuthenticateAction.DENY);
Assertions.assertThat(loaded.getDeviceToken()).isEqualTo("abcdefg1234");
Assertions.assertThat(loaded.getUserId()).isEqualTo("12345");
Assertions.assertThat(loaded.getRiskPolicy().getId()).isEqualTo("q-rbeMzBTdW2Fd09sbz55A");
Assertions.assertThat(loaded.getRiskPolicy().getRevisionId()).isEqualTo("pke4zqO2TnqVr-NHJOAHEg");
Assertions.assertThat(loaded.getRiskPolicy().getName()).isEqualTo("Block Users from X"); | Assertions.assertThat(loaded.getRiskPolicy().getType()).isEqualTo(RiskPolicyType.BOT); |
castle/castle-java | src/test/java/io/castle/client/CastleHMACTest.java | // Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
| import io.castle.client.model.CastleSdkConfigurationException;
import org.assertj.core.api.Assertions;
import org.junit.Test; | package io.castle.client;
public class CastleHMACTest {
@Test | // Path: src/main/java/io/castle/client/model/CastleSdkConfigurationException.java
// public class CastleSdkConfigurationException extends Exception {
//
// public CastleSdkConfigurationException(String message) {
// super(message);
// }
// }
// Path: src/test/java/io/castle/client/CastleHMACTest.java
import io.castle.client.model.CastleSdkConfigurationException;
import org.assertj.core.api.Assertions;
import org.junit.Test;
package io.castle.client;
public class CastleHMACTest {
@Test | public void calculateHMACSecureValue() throws CastleSdkConfigurationException { |
castle/castle-java | src/test/java/io/castle/client/CastleDevicesHttpTest.java | // Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
//
// Path: src/test/java/io/castle/client/utils/DeviceUtils.java
// public class DeviceUtils {
//
// public static final String DEVICE_TOKEN = "abcdefg12345";
// public static final double DEVICE_RISK = 0.000154;
// public static final String DEVICE_CREATED_AT = "2018-06-15T16:36:22.916Z";
// public static final String DEVICE_LAST_SEEN_AT = "2018-07-19T23:09:29.681Z";
// public static final String DEVICE_APPROVED_AT = null;
// public static final String DEVICE_ESCALATED_AT = null;
// public static final String DEVICE_MITIGATED_AT = null;
//
// public static final String CONTEXT_TYPE = "desktop";
// public static final String CONTEXT_IP = "1.1.1.1";
//
// public static final String USER_AGENT_FAMILY = "Opera";
// public static final String USER_AGENT_DEVICE = "Unknown";
// public static final String USER_AGENT_PLATFORM = "Mac OS X";
// public static final String USER_AGENT_OS = "Mac OS X 10.13.6";
// public static final String USER_AGENT_VERSION = "54.0.2952";
// public static final String USER_AGENT_BROWSER = "Opera";
// public static final String USER_AGENT_RAW = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51";
// public static final boolean USER_AGENT_MOBILE = false;
//
// public static CastleUserDevice createExpectedDevice() {
// CastleUserDevice device = new CastleUserDevice();
// device.setToken(DEVICE_TOKEN);
// device.setRisk(DEVICE_RISK);
// device.setCreatedAt(DEVICE_CREATED_AT);
// device.setLastSeenAt(DEVICE_LAST_SEEN_AT);
// device.setApprovedAt(null);
// device.setEscalatedAt(null);
// device.setMitigatedAt(null);
//
// CastleUserDeviceContext deviceContext = new CastleUserDeviceContext();
// deviceContext.setIp(CONTEXT_IP);
// deviceContext.setType(CONTEXT_TYPE);
//
// DeviceUserAgent userAgent = new DeviceUserAgent();
// userAgent.setFamily(USER_AGENT_FAMILY);
// userAgent.setDevice(USER_AGENT_DEVICE);
// userAgent.setPlatform(USER_AGENT_PLATFORM);
// userAgent.setOs(USER_AGENT_OS);
// userAgent.setVersion(USER_AGENT_VERSION);
// userAgent.setBrowser(USER_AGENT_BROWSER);
// userAgent.setRaw(USER_AGENT_RAW);
// userAgent.setMobile(USER_AGENT_MOBILE);
//
// deviceContext.setUserAgent(userAgent);
//
// device.setContext(deviceContext);
//
// return device;
// }
//
// public static CastleUserDevices createExpectedDevices() {
// CastleUserDevices devices = new CastleUserDevices();
// devices.setDevices(Arrays.asList(createExpectedDevice()));
// return devices;
// }
//
// public static String getDefaultDeviceJSON() {
// return "{\"token\":\"abcdefg12345\",\"risk\":0.000154,\"created_at\":\"2018-06-15T16:36:22.916Z\",\"last_seen_at\":\"2018-07-19T23:09:29.681Z\",\"approved_at\":null,\"escalated_at\":null,\"mitigated_at\":null,\"context\":{\"ip\":\"1.1.1.1\",\"location\":{\"country_code\":\"US\",\"country\":\"United States\",\"region\":\"New Jersey\",\"region_code\":\"NJ\",\"city\":\"Lyndhurst\",\"lat\":40.7923,\"lon\":-74.1001},\"user_agent\":{\"raw\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51\",\"browser\":\"Opera\",\"version\":\"54.0.2952\",\"os\":\"Mac OS X 10.13.6\",\"mobile\":false,\"platform\":\"Mac OS X\",\"device\":\"Unknown\",\"family\":\"Opera\"},\"type\":\"desktop\"}}";
// }
// }
| import io.castle.client.internal.json.CastleGsonModel;
import io.castle.client.model.*;
import io.castle.client.utils.DeviceUtils;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import static okhttp3.mockwebserver.SocketPolicy.NO_RESPONSE; | package io.castle.client;
public class CastleDevicesHttpTest extends AbstractCastleHttpLayerTest {
private CastleGsonModel model = new CastleGsonModel();
public CastleDevicesHttpTest() {
super(new AuthenticateFailoverStrategy(AuthenticateAction.CHALLENGE));
}
@Test public void getDevices() throws Exception {
MockResponse mockResponse = new MockResponse(); | // Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
//
// Path: src/test/java/io/castle/client/utils/DeviceUtils.java
// public class DeviceUtils {
//
// public static final String DEVICE_TOKEN = "abcdefg12345";
// public static final double DEVICE_RISK = 0.000154;
// public static final String DEVICE_CREATED_AT = "2018-06-15T16:36:22.916Z";
// public static final String DEVICE_LAST_SEEN_AT = "2018-07-19T23:09:29.681Z";
// public static final String DEVICE_APPROVED_AT = null;
// public static final String DEVICE_ESCALATED_AT = null;
// public static final String DEVICE_MITIGATED_AT = null;
//
// public static final String CONTEXT_TYPE = "desktop";
// public static final String CONTEXT_IP = "1.1.1.1";
//
// public static final String USER_AGENT_FAMILY = "Opera";
// public static final String USER_AGENT_DEVICE = "Unknown";
// public static final String USER_AGENT_PLATFORM = "Mac OS X";
// public static final String USER_AGENT_OS = "Mac OS X 10.13.6";
// public static final String USER_AGENT_VERSION = "54.0.2952";
// public static final String USER_AGENT_BROWSER = "Opera";
// public static final String USER_AGENT_RAW = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51";
// public static final boolean USER_AGENT_MOBILE = false;
//
// public static CastleUserDevice createExpectedDevice() {
// CastleUserDevice device = new CastleUserDevice();
// device.setToken(DEVICE_TOKEN);
// device.setRisk(DEVICE_RISK);
// device.setCreatedAt(DEVICE_CREATED_AT);
// device.setLastSeenAt(DEVICE_LAST_SEEN_AT);
// device.setApprovedAt(null);
// device.setEscalatedAt(null);
// device.setMitigatedAt(null);
//
// CastleUserDeviceContext deviceContext = new CastleUserDeviceContext();
// deviceContext.setIp(CONTEXT_IP);
// deviceContext.setType(CONTEXT_TYPE);
//
// DeviceUserAgent userAgent = new DeviceUserAgent();
// userAgent.setFamily(USER_AGENT_FAMILY);
// userAgent.setDevice(USER_AGENT_DEVICE);
// userAgent.setPlatform(USER_AGENT_PLATFORM);
// userAgent.setOs(USER_AGENT_OS);
// userAgent.setVersion(USER_AGENT_VERSION);
// userAgent.setBrowser(USER_AGENT_BROWSER);
// userAgent.setRaw(USER_AGENT_RAW);
// userAgent.setMobile(USER_AGENT_MOBILE);
//
// deviceContext.setUserAgent(userAgent);
//
// device.setContext(deviceContext);
//
// return device;
// }
//
// public static CastleUserDevices createExpectedDevices() {
// CastleUserDevices devices = new CastleUserDevices();
// devices.setDevices(Arrays.asList(createExpectedDevice()));
// return devices;
// }
//
// public static String getDefaultDeviceJSON() {
// return "{\"token\":\"abcdefg12345\",\"risk\":0.000154,\"created_at\":\"2018-06-15T16:36:22.916Z\",\"last_seen_at\":\"2018-07-19T23:09:29.681Z\",\"approved_at\":null,\"escalated_at\":null,\"mitigated_at\":null,\"context\":{\"ip\":\"1.1.1.1\",\"location\":{\"country_code\":\"US\",\"country\":\"United States\",\"region\":\"New Jersey\",\"region_code\":\"NJ\",\"city\":\"Lyndhurst\",\"lat\":40.7923,\"lon\":-74.1001},\"user_agent\":{\"raw\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51\",\"browser\":\"Opera\",\"version\":\"54.0.2952\",\"os\":\"Mac OS X 10.13.6\",\"mobile\":false,\"platform\":\"Mac OS X\",\"device\":\"Unknown\",\"family\":\"Opera\"},\"type\":\"desktop\"}}";
// }
// }
// Path: src/test/java/io/castle/client/CastleDevicesHttpTest.java
import io.castle.client.internal.json.CastleGsonModel;
import io.castle.client.model.*;
import io.castle.client.utils.DeviceUtils;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import static okhttp3.mockwebserver.SocketPolicy.NO_RESPONSE;
package io.castle.client;
public class CastleDevicesHttpTest extends AbstractCastleHttpLayerTest {
private CastleGsonModel model = new CastleGsonModel();
public CastleDevicesHttpTest() {
super(new AuthenticateFailoverStrategy(AuthenticateAction.CHALLENGE));
}
@Test public void getDevices() throws Exception {
MockResponse mockResponse = new MockResponse(); | mockResponse.setBody("{\"total_count\":1,\"data\":[" + DeviceUtils.getDefaultDeviceJSON() + "]}"); |
castle/castle-java | src/test/java/io/castle/client/model/CastleUserDeviceTest.java | // Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
//
// Path: src/test/java/io/castle/client/utils/DeviceUtils.java
// public class DeviceUtils {
//
// public static final String DEVICE_TOKEN = "abcdefg12345";
// public static final double DEVICE_RISK = 0.000154;
// public static final String DEVICE_CREATED_AT = "2018-06-15T16:36:22.916Z";
// public static final String DEVICE_LAST_SEEN_AT = "2018-07-19T23:09:29.681Z";
// public static final String DEVICE_APPROVED_AT = null;
// public static final String DEVICE_ESCALATED_AT = null;
// public static final String DEVICE_MITIGATED_AT = null;
//
// public static final String CONTEXT_TYPE = "desktop";
// public static final String CONTEXT_IP = "1.1.1.1";
//
// public static final String USER_AGENT_FAMILY = "Opera";
// public static final String USER_AGENT_DEVICE = "Unknown";
// public static final String USER_AGENT_PLATFORM = "Mac OS X";
// public static final String USER_AGENT_OS = "Mac OS X 10.13.6";
// public static final String USER_AGENT_VERSION = "54.0.2952";
// public static final String USER_AGENT_BROWSER = "Opera";
// public static final String USER_AGENT_RAW = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51";
// public static final boolean USER_AGENT_MOBILE = false;
//
// public static CastleUserDevice createExpectedDevice() {
// CastleUserDevice device = new CastleUserDevice();
// device.setToken(DEVICE_TOKEN);
// device.setRisk(DEVICE_RISK);
// device.setCreatedAt(DEVICE_CREATED_AT);
// device.setLastSeenAt(DEVICE_LAST_SEEN_AT);
// device.setApprovedAt(null);
// device.setEscalatedAt(null);
// device.setMitigatedAt(null);
//
// CastleUserDeviceContext deviceContext = new CastleUserDeviceContext();
// deviceContext.setIp(CONTEXT_IP);
// deviceContext.setType(CONTEXT_TYPE);
//
// DeviceUserAgent userAgent = new DeviceUserAgent();
// userAgent.setFamily(USER_AGENT_FAMILY);
// userAgent.setDevice(USER_AGENT_DEVICE);
// userAgent.setPlatform(USER_AGENT_PLATFORM);
// userAgent.setOs(USER_AGENT_OS);
// userAgent.setVersion(USER_AGENT_VERSION);
// userAgent.setBrowser(USER_AGENT_BROWSER);
// userAgent.setRaw(USER_AGENT_RAW);
// userAgent.setMobile(USER_AGENT_MOBILE);
//
// deviceContext.setUserAgent(userAgent);
//
// device.setContext(deviceContext);
//
// return device;
// }
//
// public static CastleUserDevices createExpectedDevices() {
// CastleUserDevices devices = new CastleUserDevices();
// devices.setDevices(Arrays.asList(createExpectedDevice()));
// return devices;
// }
//
// public static String getDefaultDeviceJSON() {
// return "{\"token\":\"abcdefg12345\",\"risk\":0.000154,\"created_at\":\"2018-06-15T16:36:22.916Z\",\"last_seen_at\":\"2018-07-19T23:09:29.681Z\",\"approved_at\":null,\"escalated_at\":null,\"mitigated_at\":null,\"context\":{\"ip\":\"1.1.1.1\",\"location\":{\"country_code\":\"US\",\"country\":\"United States\",\"region\":\"New Jersey\",\"region_code\":\"NJ\",\"city\":\"Lyndhurst\",\"lat\":40.7923,\"lon\":-74.1001},\"user_agent\":{\"raw\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51\",\"browser\":\"Opera\",\"version\":\"54.0.2952\",\"os\":\"Mac OS X 10.13.6\",\"mobile\":false,\"platform\":\"Mac OS X\",\"device\":\"Unknown\",\"family\":\"Opera\"},\"type\":\"desktop\"}}";
// }
// }
| import com.google.common.collect.ImmutableMap;
import io.castle.client.internal.json.CastleGsonModel;
import io.castle.client.utils.DeviceUtils;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Test; | package io.castle.client.model;
public class CastleUserDeviceTest {
private CastleGsonModel model = new CastleGsonModel();
@Test
public void jsonSerialized() {
// Given
CastleUserDevice device = new CastleUserDevice();
// When
String payloadJson = model.getGson().toJson(device);
// Then
Assertions.assertThat(payloadJson).isEqualTo("{\"risk\":0.0,\"is_current_device\":false}");
}
@Test
public void fullBuilderJson() {
// Given
CastleUserDevice device = new CastleUserDevice(); | // Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
//
// Path: src/test/java/io/castle/client/utils/DeviceUtils.java
// public class DeviceUtils {
//
// public static final String DEVICE_TOKEN = "abcdefg12345";
// public static final double DEVICE_RISK = 0.000154;
// public static final String DEVICE_CREATED_AT = "2018-06-15T16:36:22.916Z";
// public static final String DEVICE_LAST_SEEN_AT = "2018-07-19T23:09:29.681Z";
// public static final String DEVICE_APPROVED_AT = null;
// public static final String DEVICE_ESCALATED_AT = null;
// public static final String DEVICE_MITIGATED_AT = null;
//
// public static final String CONTEXT_TYPE = "desktop";
// public static final String CONTEXT_IP = "1.1.1.1";
//
// public static final String USER_AGENT_FAMILY = "Opera";
// public static final String USER_AGENT_DEVICE = "Unknown";
// public static final String USER_AGENT_PLATFORM = "Mac OS X";
// public static final String USER_AGENT_OS = "Mac OS X 10.13.6";
// public static final String USER_AGENT_VERSION = "54.0.2952";
// public static final String USER_AGENT_BROWSER = "Opera";
// public static final String USER_AGENT_RAW = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51";
// public static final boolean USER_AGENT_MOBILE = false;
//
// public static CastleUserDevice createExpectedDevice() {
// CastleUserDevice device = new CastleUserDevice();
// device.setToken(DEVICE_TOKEN);
// device.setRisk(DEVICE_RISK);
// device.setCreatedAt(DEVICE_CREATED_AT);
// device.setLastSeenAt(DEVICE_LAST_SEEN_AT);
// device.setApprovedAt(null);
// device.setEscalatedAt(null);
// device.setMitigatedAt(null);
//
// CastleUserDeviceContext deviceContext = new CastleUserDeviceContext();
// deviceContext.setIp(CONTEXT_IP);
// deviceContext.setType(CONTEXT_TYPE);
//
// DeviceUserAgent userAgent = new DeviceUserAgent();
// userAgent.setFamily(USER_AGENT_FAMILY);
// userAgent.setDevice(USER_AGENT_DEVICE);
// userAgent.setPlatform(USER_AGENT_PLATFORM);
// userAgent.setOs(USER_AGENT_OS);
// userAgent.setVersion(USER_AGENT_VERSION);
// userAgent.setBrowser(USER_AGENT_BROWSER);
// userAgent.setRaw(USER_AGENT_RAW);
// userAgent.setMobile(USER_AGENT_MOBILE);
//
// deviceContext.setUserAgent(userAgent);
//
// device.setContext(deviceContext);
//
// return device;
// }
//
// public static CastleUserDevices createExpectedDevices() {
// CastleUserDevices devices = new CastleUserDevices();
// devices.setDevices(Arrays.asList(createExpectedDevice()));
// return devices;
// }
//
// public static String getDefaultDeviceJSON() {
// return "{\"token\":\"abcdefg12345\",\"risk\":0.000154,\"created_at\":\"2018-06-15T16:36:22.916Z\",\"last_seen_at\":\"2018-07-19T23:09:29.681Z\",\"approved_at\":null,\"escalated_at\":null,\"mitigated_at\":null,\"context\":{\"ip\":\"1.1.1.1\",\"location\":{\"country_code\":\"US\",\"country\":\"United States\",\"region\":\"New Jersey\",\"region_code\":\"NJ\",\"city\":\"Lyndhurst\",\"lat\":40.7923,\"lon\":-74.1001},\"user_agent\":{\"raw\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51\",\"browser\":\"Opera\",\"version\":\"54.0.2952\",\"os\":\"Mac OS X 10.13.6\",\"mobile\":false,\"platform\":\"Mac OS X\",\"device\":\"Unknown\",\"family\":\"Opera\"},\"type\":\"desktop\"}}";
// }
// }
// Path: src/test/java/io/castle/client/model/CastleUserDeviceTest.java
import com.google.common.collect.ImmutableMap;
import io.castle.client.internal.json.CastleGsonModel;
import io.castle.client.utils.DeviceUtils;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Test;
package io.castle.client.model;
public class CastleUserDeviceTest {
private CastleGsonModel model = new CastleGsonModel();
@Test
public void jsonSerialized() {
// Given
CastleUserDevice device = new CastleUserDevice();
// When
String payloadJson = model.getGson().toJson(device);
// Then
Assertions.assertThat(payloadJson).isEqualTo("{\"risk\":0.0,\"is_current_device\":false}");
}
@Test
public void fullBuilderJson() {
// Given
CastleUserDevice device = new CastleUserDevice(); | device.setToken(DeviceUtils.DEVICE_TOKEN); |
castle/castle-java | src/test/java/io/castle/client/model/CastleContextTest.java | // Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
//
// Path: src/test/java/io/castle/client/utils/SDKVersion.java
// public class SDKVersion {
//
// private static String libraryString = "\"library\":{\"name\":\"castle-java\",\"version\":\"" + getSDKVersion() + "\",\"platform\":\"" + getJavaPlatform() + "\",\"platform_version\":\"" + getJavaVersion() + "\"}";
//
// private static String version = getSDKVersion();
//
// public static String getLibraryString() {
// return libraryString;
// }
//
// public static String getVersion() {
// return version;
// }
//
// private static String getSDKVersion() {
// Properties versionProperties = new Properties();
// PropertiesReader reader = new PropertiesReader();
// InputStream resourceAsStream = Castle.class.getClassLoader().getResourceAsStream("version.properties");
// reader.loadPropertiesFromStream(versionProperties, resourceAsStream);
// return versionProperties.getProperty("sdk.version");
// }
//
// public static String getJavaVersion() {
// return System.getProperty("java.vm.version");
// }
//
// public static String getJavaPlatform() {
// return System.getProperty("java.vm.name");
// }
// }
| import com.google.common.collect.ImmutableList;
import io.castle.client.internal.json.CastleGsonModel;
import io.castle.client.utils.SDKVersion;
import org.assertj.core.api.Assertions;
import org.json.JSONException;
import org.junit.Assert;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import java.util.Comparator;
import java.util.List; | package io.castle.client.model;
public class CastleContextTest {
private CastleGsonModel model = new CastleGsonModel();
@Test
public void minimalContextAsJson() {
//given
CastleContext aContext = new CastleContext();
//when
String contextJson = model.getGson().toJson(aContext);
//Then | // Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
//
// Path: src/test/java/io/castle/client/utils/SDKVersion.java
// public class SDKVersion {
//
// private static String libraryString = "\"library\":{\"name\":\"castle-java\",\"version\":\"" + getSDKVersion() + "\",\"platform\":\"" + getJavaPlatform() + "\",\"platform_version\":\"" + getJavaVersion() + "\"}";
//
// private static String version = getSDKVersion();
//
// public static String getLibraryString() {
// return libraryString;
// }
//
// public static String getVersion() {
// return version;
// }
//
// private static String getSDKVersion() {
// Properties versionProperties = new Properties();
// PropertiesReader reader = new PropertiesReader();
// InputStream resourceAsStream = Castle.class.getClassLoader().getResourceAsStream("version.properties");
// reader.loadPropertiesFromStream(versionProperties, resourceAsStream);
// return versionProperties.getProperty("sdk.version");
// }
//
// public static String getJavaVersion() {
// return System.getProperty("java.vm.version");
// }
//
// public static String getJavaPlatform() {
// return System.getProperty("java.vm.name");
// }
// }
// Path: src/test/java/io/castle/client/model/CastleContextTest.java
import com.google.common.collect.ImmutableList;
import io.castle.client.internal.json.CastleGsonModel;
import io.castle.client.utils.SDKVersion;
import org.assertj.core.api.Assertions;
import org.json.JSONException;
import org.junit.Assert;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import java.util.Comparator;
import java.util.List;
package io.castle.client.model;
public class CastleContextTest {
private CastleGsonModel model = new CastleGsonModel();
@Test
public void minimalContextAsJson() {
//given
CastleContext aContext = new CastleContext();
//when
String contextJson = model.getGson().toJson(aContext);
//Then | Assertions.assertThat(contextJson).isEqualTo("{\"active\":true," + SDKVersion.getLibraryString() +"}"); |
castle/castle-java | src/test/java/io/castle/client/model/CastleUserDeviceContextTest.java | // Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
//
// Path: src/test/java/io/castle/client/utils/DeviceUtils.java
// public class DeviceUtils {
//
// public static final String DEVICE_TOKEN = "abcdefg12345";
// public static final double DEVICE_RISK = 0.000154;
// public static final String DEVICE_CREATED_AT = "2018-06-15T16:36:22.916Z";
// public static final String DEVICE_LAST_SEEN_AT = "2018-07-19T23:09:29.681Z";
// public static final String DEVICE_APPROVED_AT = null;
// public static final String DEVICE_ESCALATED_AT = null;
// public static final String DEVICE_MITIGATED_AT = null;
//
// public static final String CONTEXT_TYPE = "desktop";
// public static final String CONTEXT_IP = "1.1.1.1";
//
// public static final String USER_AGENT_FAMILY = "Opera";
// public static final String USER_AGENT_DEVICE = "Unknown";
// public static final String USER_AGENT_PLATFORM = "Mac OS X";
// public static final String USER_AGENT_OS = "Mac OS X 10.13.6";
// public static final String USER_AGENT_VERSION = "54.0.2952";
// public static final String USER_AGENT_BROWSER = "Opera";
// public static final String USER_AGENT_RAW = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51";
// public static final boolean USER_AGENT_MOBILE = false;
//
// public static CastleUserDevice createExpectedDevice() {
// CastleUserDevice device = new CastleUserDevice();
// device.setToken(DEVICE_TOKEN);
// device.setRisk(DEVICE_RISK);
// device.setCreatedAt(DEVICE_CREATED_AT);
// device.setLastSeenAt(DEVICE_LAST_SEEN_AT);
// device.setApprovedAt(null);
// device.setEscalatedAt(null);
// device.setMitigatedAt(null);
//
// CastleUserDeviceContext deviceContext = new CastleUserDeviceContext();
// deviceContext.setIp(CONTEXT_IP);
// deviceContext.setType(CONTEXT_TYPE);
//
// DeviceUserAgent userAgent = new DeviceUserAgent();
// userAgent.setFamily(USER_AGENT_FAMILY);
// userAgent.setDevice(USER_AGENT_DEVICE);
// userAgent.setPlatform(USER_AGENT_PLATFORM);
// userAgent.setOs(USER_AGENT_OS);
// userAgent.setVersion(USER_AGENT_VERSION);
// userAgent.setBrowser(USER_AGENT_BROWSER);
// userAgent.setRaw(USER_AGENT_RAW);
// userAgent.setMobile(USER_AGENT_MOBILE);
//
// deviceContext.setUserAgent(userAgent);
//
// device.setContext(deviceContext);
//
// return device;
// }
//
// public static CastleUserDevices createExpectedDevices() {
// CastleUserDevices devices = new CastleUserDevices();
// devices.setDevices(Arrays.asList(createExpectedDevice()));
// return devices;
// }
//
// public static String getDefaultDeviceJSON() {
// return "{\"token\":\"abcdefg12345\",\"risk\":0.000154,\"created_at\":\"2018-06-15T16:36:22.916Z\",\"last_seen_at\":\"2018-07-19T23:09:29.681Z\",\"approved_at\":null,\"escalated_at\":null,\"mitigated_at\":null,\"context\":{\"ip\":\"1.1.1.1\",\"location\":{\"country_code\":\"US\",\"country\":\"United States\",\"region\":\"New Jersey\",\"region_code\":\"NJ\",\"city\":\"Lyndhurst\",\"lat\":40.7923,\"lon\":-74.1001},\"user_agent\":{\"raw\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51\",\"browser\":\"Opera\",\"version\":\"54.0.2952\",\"os\":\"Mac OS X 10.13.6\",\"mobile\":false,\"platform\":\"Mac OS X\",\"device\":\"Unknown\",\"family\":\"Opera\"},\"type\":\"desktop\"}}";
// }
// }
| import io.castle.client.internal.json.CastleGsonModel;
import io.castle.client.utils.DeviceUtils;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List; | package io.castle.client.model;
public class CastleUserDeviceContextTest {
private CastleGsonModel model = new CastleGsonModel();
@Test
public void jsonSerialized() {
// Given
CastleUserDeviceContext deviceContext = new CastleUserDeviceContext();
// When
String payloadJson = model.getGson().toJson(deviceContext);
// Then
Assertions.assertThat(payloadJson).isEqualTo("{}");
}
@Test
public void fullBuilderJson() {
// Given
CastleUserDeviceContext deviceContext = new CastleUserDeviceContext(); | // Path: src/main/java/io/castle/client/internal/json/CastleGsonModel.java
// public class CastleGsonModel {
//
// private final Gson gson;
// private final JsonParser jsonParser;
//
// public CastleGsonModel() {
// GsonBuilder builder = createGsonBuilder();
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersSerializer());
// builder.registerTypeAdapter(String.class, new StringJsonSerializer());
// builder.registerTypeAdapter(CastleMessage.class, new CastleMessageSerializer());
// builder.registerTypeAdapter(CastleHeaders.class, new CastleHeadersDeserializer());
// builder.registerTypeAdapter(AuthenticateAction.class, new AuthenticateActionDeserializer());
// builder.registerTypeAdapter(RiskPolicyType.class, new RiskPolicyTypeDeserializer());
// this.gson = builder.create();
//
// this.jsonParser = new JsonParser();
// }
//
// public Gson getGson() {
// return gson;
// }
//
// public JsonParser getJsonParser() {
// return jsonParser;
// }
//
// public static GsonBuilder createGsonBuilder() {
// return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// }
// }
//
// Path: src/test/java/io/castle/client/utils/DeviceUtils.java
// public class DeviceUtils {
//
// public static final String DEVICE_TOKEN = "abcdefg12345";
// public static final double DEVICE_RISK = 0.000154;
// public static final String DEVICE_CREATED_AT = "2018-06-15T16:36:22.916Z";
// public static final String DEVICE_LAST_SEEN_AT = "2018-07-19T23:09:29.681Z";
// public static final String DEVICE_APPROVED_AT = null;
// public static final String DEVICE_ESCALATED_AT = null;
// public static final String DEVICE_MITIGATED_AT = null;
//
// public static final String CONTEXT_TYPE = "desktop";
// public static final String CONTEXT_IP = "1.1.1.1";
//
// public static final String USER_AGENT_FAMILY = "Opera";
// public static final String USER_AGENT_DEVICE = "Unknown";
// public static final String USER_AGENT_PLATFORM = "Mac OS X";
// public static final String USER_AGENT_OS = "Mac OS X 10.13.6";
// public static final String USER_AGENT_VERSION = "54.0.2952";
// public static final String USER_AGENT_BROWSER = "Opera";
// public static final String USER_AGENT_RAW = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51";
// public static final boolean USER_AGENT_MOBILE = false;
//
// public static CastleUserDevice createExpectedDevice() {
// CastleUserDevice device = new CastleUserDevice();
// device.setToken(DEVICE_TOKEN);
// device.setRisk(DEVICE_RISK);
// device.setCreatedAt(DEVICE_CREATED_AT);
// device.setLastSeenAt(DEVICE_LAST_SEEN_AT);
// device.setApprovedAt(null);
// device.setEscalatedAt(null);
// device.setMitigatedAt(null);
//
// CastleUserDeviceContext deviceContext = new CastleUserDeviceContext();
// deviceContext.setIp(CONTEXT_IP);
// deviceContext.setType(CONTEXT_TYPE);
//
// DeviceUserAgent userAgent = new DeviceUserAgent();
// userAgent.setFamily(USER_AGENT_FAMILY);
// userAgent.setDevice(USER_AGENT_DEVICE);
// userAgent.setPlatform(USER_AGENT_PLATFORM);
// userAgent.setOs(USER_AGENT_OS);
// userAgent.setVersion(USER_AGENT_VERSION);
// userAgent.setBrowser(USER_AGENT_BROWSER);
// userAgent.setRaw(USER_AGENT_RAW);
// userAgent.setMobile(USER_AGENT_MOBILE);
//
// deviceContext.setUserAgent(userAgent);
//
// device.setContext(deviceContext);
//
// return device;
// }
//
// public static CastleUserDevices createExpectedDevices() {
// CastleUserDevices devices = new CastleUserDevices();
// devices.setDevices(Arrays.asList(createExpectedDevice()));
// return devices;
// }
//
// public static String getDefaultDeviceJSON() {
// return "{\"token\":\"abcdefg12345\",\"risk\":0.000154,\"created_at\":\"2018-06-15T16:36:22.916Z\",\"last_seen_at\":\"2018-07-19T23:09:29.681Z\",\"approved_at\":null,\"escalated_at\":null,\"mitigated_at\":null,\"context\":{\"ip\":\"1.1.1.1\",\"location\":{\"country_code\":\"US\",\"country\":\"United States\",\"region\":\"New Jersey\",\"region_code\":\"NJ\",\"city\":\"Lyndhurst\",\"lat\":40.7923,\"lon\":-74.1001},\"user_agent\":{\"raw\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36 OPR/54.0.2952.51\",\"browser\":\"Opera\",\"version\":\"54.0.2952\",\"os\":\"Mac OS X 10.13.6\",\"mobile\":false,\"platform\":\"Mac OS X\",\"device\":\"Unknown\",\"family\":\"Opera\"},\"type\":\"desktop\"}}";
// }
// }
// Path: src/test/java/io/castle/client/model/CastleUserDeviceContextTest.java
import io.castle.client.internal.json.CastleGsonModel;
import io.castle.client.utils.DeviceUtils;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
package io.castle.client.model;
public class CastleUserDeviceContextTest {
private CastleGsonModel model = new CastleGsonModel();
@Test
public void jsonSerialized() {
// Given
CastleUserDeviceContext deviceContext = new CastleUserDeviceContext();
// When
String payloadJson = model.getGson().toJson(deviceContext);
// Then
Assertions.assertThat(payloadJson).isEqualTo("{}");
}
@Test
public void fullBuilderJson() {
// Given
CastleUserDeviceContext deviceContext = new CastleUserDeviceContext(); | deviceContext.setIp(DeviceUtils.CONTEXT_IP); |
castle/castle-java | src/main/java/io/castle/client/internal/json/CastleHeadersSerializer.java | // Path: src/main/java/io/castle/client/model/CastleHeader.java
// public class CastleHeader {
// private String key;
// private String value;
//
// public CastleHeader() {
// }
//
// public CastleHeader(String key, String value) {
// this.key = key;
// this.value = value;
// }
//
// public String getKey() {
// return key;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// CastleHeader that = (CastleHeader) o;
// return Objects.equals(key, that.key) &&
// Objects.equals(value, that.value);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(key, value);
// }
//
// @Override
// public String toString() {
// return "CastleHeader{" +
// "key='" + key + '\'' +
// ", value='" + value + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleHeaders.java
// public class CastleHeaders {
//
// private List<CastleHeader> headers;
//
// public List<CastleHeader> getHeaders() {
// return headers;
// }
//
// public static Builder builder() {
// return new Builder(new CastleHeaders());
// }
//
// public void setHeaders(List<CastleHeader> headers) {
// this.headers = headers;
// }
//
// public CastleHeaders(List<CastleHeader> headers) { this.headers = headers; }
//
// public CastleHeaders() {}
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// CastleHeaders that = (CastleHeaders) o;
// return Objects.equals(headers, that.headers);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(headers);
// }
//
// @Override
// public String toString() {
// return "CastleHeaders{" +
// "headers=" + headers +
// '}';
// }
//
// public static class Builder {
// private CastleHeaders headers;
// private ArrayList<CastleHeader> headerList;
//
// public Builder(CastleHeaders headers) {
// this.headers = headers;
// this.headerList = new ArrayList<>();
// }
//
// public CastleHeaders build() {
// headers.setHeaders(headerList);
// return headers;
// }
//
// public Builder add(String key, String value) {
// this.headerList.add(new CastleHeader(key, value));
// return this;
// }
// }
// }
| import com.google.gson.*;
import io.castle.client.model.CastleHeader;
import io.castle.client.model.CastleHeaders;
import java.lang.reflect.Type;
import java.util.Iterator; | package io.castle.client.internal.json;
public class CastleHeadersSerializer implements JsonSerializer<CastleHeaders> {
@Override
public JsonElement serialize(CastleHeaders headers, Type typeOfSrc, JsonSerializationContext context) {
JsonObject root = new JsonObject(); | // Path: src/main/java/io/castle/client/model/CastleHeader.java
// public class CastleHeader {
// private String key;
// private String value;
//
// public CastleHeader() {
// }
//
// public CastleHeader(String key, String value) {
// this.key = key;
// this.value = value;
// }
//
// public String getKey() {
// return key;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// CastleHeader that = (CastleHeader) o;
// return Objects.equals(key, that.key) &&
// Objects.equals(value, that.value);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(key, value);
// }
//
// @Override
// public String toString() {
// return "CastleHeader{" +
// "key='" + key + '\'' +
// ", value='" + value + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/io/castle/client/model/CastleHeaders.java
// public class CastleHeaders {
//
// private List<CastleHeader> headers;
//
// public List<CastleHeader> getHeaders() {
// return headers;
// }
//
// public static Builder builder() {
// return new Builder(new CastleHeaders());
// }
//
// public void setHeaders(List<CastleHeader> headers) {
// this.headers = headers;
// }
//
// public CastleHeaders(List<CastleHeader> headers) { this.headers = headers; }
//
// public CastleHeaders() {}
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// CastleHeaders that = (CastleHeaders) o;
// return Objects.equals(headers, that.headers);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(headers);
// }
//
// @Override
// public String toString() {
// return "CastleHeaders{" +
// "headers=" + headers +
// '}';
// }
//
// public static class Builder {
// private CastleHeaders headers;
// private ArrayList<CastleHeader> headerList;
//
// public Builder(CastleHeaders headers) {
// this.headers = headers;
// this.headerList = new ArrayList<>();
// }
//
// public CastleHeaders build() {
// headers.setHeaders(headerList);
// return headers;
// }
//
// public Builder add(String key, String value) {
// this.headerList.add(new CastleHeader(key, value));
// return this;
// }
// }
// }
// Path: src/main/java/io/castle/client/internal/json/CastleHeadersSerializer.java
import com.google.gson.*;
import io.castle.client.model.CastleHeader;
import io.castle.client.model.CastleHeaders;
import java.lang.reflect.Type;
import java.util.Iterator;
package io.castle.client.internal.json;
public class CastleHeadersSerializer implements JsonSerializer<CastleHeaders> {
@Override
public JsonElement serialize(CastleHeaders headers, Type typeOfSrc, JsonSerializationContext context) {
JsonObject root = new JsonObject(); | for (Iterator<CastleHeader> iterator = headers.getHeaders().iterator(); iterator.hasNext(); ) { |
nkarasch/ChessGDX | core/src/nkarasch/chessgdx/util/SoundManager.java | // Path: core/src/nkarasch/chessgdx/GameCore.java
// public class GameCore implements ApplicationListener {
//
// public static final String TITLE = "ChessGDX";
//
// private Camera mCameraController;
// private ChessLogicController mLogicController;
// private BoardController mBoardController;
// private PerspectiveRenderer mPerspectiveRenderer;
// private OverlayRenderer mOverlayRenderer;
//
// private static Runnable rebootHook;
//
// /**
// * @param rebootHook
// * game restart hook
// */
// public GameCore(final Runnable rebootHook) {
// GameCore.rebootHook = rebootHook;
// }
//
// @Override
// public void create() {
// GraphicsSettings.setGraphics();
// mCameraController = new Camera();
// mOverlayRenderer = new OverlayRenderer(this);
// mLogicController = new ChessLogicController(mOverlayRenderer);
// mBoardController = new BoardController(mCameraController, mLogicController, mOverlayRenderer);
// mPerspectiveRenderer = new PerspectiveRenderer(mCameraController, mBoardController, mLogicController.getPlacement());
//
// Gdx.input.setInputProcessor(new InputMultiplexer(mOverlayRenderer, mBoardController, mCameraController.getOrbitController()));
// }
//
// @Override
// public void render() {
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
// mCameraController.update();
// mPerspectiveRenderer.render();
// mOverlayRenderer.render();
// }
//
// @Override
// public void resize(int width, int height) {
// // requiring restart on resize instead, this would be tedious to set up
// }
//
// @Override
// public void pause() {
// // not supporting mobile
// }
//
// @Override
// public void resume() {
// // not supporting mobile
// }
//
// @Override
// public void dispose() {
// AssetHandler.getInstance().dispose();
// mLogicController.dispose();
// mOverlayRenderer.dispose();
// }
//
// /**
// * Restarts game client
// */
// public static void restart() {
// Gdx.app.postRunnable(GameCore.rebootHook);
// }
//
// /**
// * Restores board back to the new game state
// *
// * @param isWhite
// * player color
// */
// public void newGame(boolean isWhite) {
// mBoardController.setPlayerColor(isWhite);
// mBoardController.resetList();
// mLogicController.resetPosition();
// mOverlayRenderer.getCheckmateDialog().setState(false, false);
// mOverlayRenderer.getMoveHistory().resetHistory();
// }
// }
| import nkarasch.chessgdx.GameCore;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound; | package nkarasch.chessgdx.util;
public class SoundManager {
private final Music mAmbience;
private final Sound mClicked;
private final Sound mReleased;
private final Sound mMove;
private float mEffectsVolume;
// evil anti-pattern strikes again...
private static SoundManager soundManager;
/**
* @return SoundManager instance, used for playing all audio and managing
* volumes.
*/
public static SoundManager getInstance() {
if (soundManager == null) {
soundManager = new SoundManager();
}
return soundManager;
}
private SoundManager() {
| // Path: core/src/nkarasch/chessgdx/GameCore.java
// public class GameCore implements ApplicationListener {
//
// public static final String TITLE = "ChessGDX";
//
// private Camera mCameraController;
// private ChessLogicController mLogicController;
// private BoardController mBoardController;
// private PerspectiveRenderer mPerspectiveRenderer;
// private OverlayRenderer mOverlayRenderer;
//
// private static Runnable rebootHook;
//
// /**
// * @param rebootHook
// * game restart hook
// */
// public GameCore(final Runnable rebootHook) {
// GameCore.rebootHook = rebootHook;
// }
//
// @Override
// public void create() {
// GraphicsSettings.setGraphics();
// mCameraController = new Camera();
// mOverlayRenderer = new OverlayRenderer(this);
// mLogicController = new ChessLogicController(mOverlayRenderer);
// mBoardController = new BoardController(mCameraController, mLogicController, mOverlayRenderer);
// mPerspectiveRenderer = new PerspectiveRenderer(mCameraController, mBoardController, mLogicController.getPlacement());
//
// Gdx.input.setInputProcessor(new InputMultiplexer(mOverlayRenderer, mBoardController, mCameraController.getOrbitController()));
// }
//
// @Override
// public void render() {
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
// mCameraController.update();
// mPerspectiveRenderer.render();
// mOverlayRenderer.render();
// }
//
// @Override
// public void resize(int width, int height) {
// // requiring restart on resize instead, this would be tedious to set up
// }
//
// @Override
// public void pause() {
// // not supporting mobile
// }
//
// @Override
// public void resume() {
// // not supporting mobile
// }
//
// @Override
// public void dispose() {
// AssetHandler.getInstance().dispose();
// mLogicController.dispose();
// mOverlayRenderer.dispose();
// }
//
// /**
// * Restarts game client
// */
// public static void restart() {
// Gdx.app.postRunnable(GameCore.rebootHook);
// }
//
// /**
// * Restores board back to the new game state
// *
// * @param isWhite
// * player color
// */
// public void newGame(boolean isWhite) {
// mBoardController.setPlayerColor(isWhite);
// mBoardController.resetList();
// mLogicController.resetPosition();
// mOverlayRenderer.getCheckmateDialog().setState(false, false);
// mOverlayRenderer.getMoveHistory().resetHistory();
// }
// }
// Path: core/src/nkarasch/chessgdx/util/SoundManager.java
import nkarasch.chessgdx.GameCore;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
package nkarasch.chessgdx.util;
public class SoundManager {
private final Music mAmbience;
private final Sound mClicked;
private final Sound mReleased;
private final Sound mMove;
private float mEffectsVolume;
// evil anti-pattern strikes again...
private static SoundManager soundManager;
/**
* @return SoundManager instance, used for playing all audio and managing
* volumes.
*/
public static SoundManager getInstance() {
if (soundManager == null) {
soundManager = new SoundManager();
}
return soundManager;
}
private SoundManager() {
| Preferences pref = Gdx.app.getPreferences(GameCore.TITLE); |
nkarasch/ChessGDX | core/src/nkarasch/chessgdx/logiccontroller/backend/ChessLogicController.java | // Path: core/src/nkarasch/chessgdx/GameCore.java
// public class GameCore implements ApplicationListener {
//
// public static final String TITLE = "ChessGDX";
//
// private Camera mCameraController;
// private ChessLogicController mLogicController;
// private BoardController mBoardController;
// private PerspectiveRenderer mPerspectiveRenderer;
// private OverlayRenderer mOverlayRenderer;
//
// private static Runnable rebootHook;
//
// /**
// * @param rebootHook
// * game restart hook
// */
// public GameCore(final Runnable rebootHook) {
// GameCore.rebootHook = rebootHook;
// }
//
// @Override
// public void create() {
// GraphicsSettings.setGraphics();
// mCameraController = new Camera();
// mOverlayRenderer = new OverlayRenderer(this);
// mLogicController = new ChessLogicController(mOverlayRenderer);
// mBoardController = new BoardController(mCameraController, mLogicController, mOverlayRenderer);
// mPerspectiveRenderer = new PerspectiveRenderer(mCameraController, mBoardController, mLogicController.getPlacement());
//
// Gdx.input.setInputProcessor(new InputMultiplexer(mOverlayRenderer, mBoardController, mCameraController.getOrbitController()));
// }
//
// @Override
// public void render() {
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
// mCameraController.update();
// mPerspectiveRenderer.render();
// mOverlayRenderer.render();
// }
//
// @Override
// public void resize(int width, int height) {
// // requiring restart on resize instead, this would be tedious to set up
// }
//
// @Override
// public void pause() {
// // not supporting mobile
// }
//
// @Override
// public void resume() {
// // not supporting mobile
// }
//
// @Override
// public void dispose() {
// AssetHandler.getInstance().dispose();
// mLogicController.dispose();
// mOverlayRenderer.dispose();
// }
//
// /**
// * Restarts game client
// */
// public static void restart() {
// Gdx.app.postRunnable(GameCore.rebootHook);
// }
//
// /**
// * Restores board back to the new game state
// *
// * @param isWhite
// * player color
// */
// public void newGame(boolean isWhite) {
// mBoardController.setPlayerColor(isWhite);
// mBoardController.resetList();
// mLogicController.resetPosition();
// mOverlayRenderer.getCheckmateDialog().setState(false, false);
// mOverlayRenderer.getMoveHistory().resetHistory();
// }
// }
//
// Path: core/src/nkarasch/chessgdx/view/renderers/OverlayRenderer.java
// public class OverlayRenderer extends Stage {
//
// private final Skin mSkin;
// private final PromotionTable mPromotionDialog;
// private final CheckMateTable mCheckmateDialog;
// private final EngineThinkingImage mEngineThinking;
// private final SlidingMenuGroup mSlidingMenu;
//
// /**
// * Foundation of the Scene2D based GUI.
// *
// * @param core
// * root of game, is passed in so GUI elements can trigger
// * {@link GameCore#restart()} and
// * {@link GameCore#newGame(boolean)}
// */
// public OverlayRenderer(GameCore core) {
//
// mSkin = new MenuSkin();
// ExitConfirmTable exitConfirm = new ExitConfirmTable(mSkin);
// SettingsMenuGroup settings = new SettingsMenuGroup(mSkin);
// mSlidingMenu = new SlidingMenuGroup(mSkin, exitConfirm, settings, core);
// mEngineThinking = new EngineThinkingImage(mSkin);
// mPromotionDialog = new PromotionTable(mSkin);
// mCheckmateDialog = new CheckMateTable(mSkin);
//
// addActor(mPromotionDialog);
// addActor(mCheckmateDialog);
// addActor(settings);
// addActor(mSlidingMenu);
// addActor(mEngineThinking);
// addActor(exitConfirm);
// }
//
// public void render() {
// act(Gdx.graphics.getDeltaTime());
// draw();
// }
//
// public void dispose() {
// mSkin.dispose();
// super.dispose();
// }
//
// /**
// * @return UI element displaying the move history for both black and white
// */
// public MoveHistoryTable getMoveHistory() {
// return mSlidingMenu.getMoveHistory();
// }
//
// /**
// * @return UI element for letting the user which piece they want to promote
// * their pawns to
// */
// public PromotionTable getPromotionDialog() {
// return mPromotionDialog;
// }
//
// /**
// *
// * @return UI element informing the user when the board is in a check or
// * checkmate state
// */
// public CheckMateTable getCheckmateDialog() {
// return mCheckmateDialog;
// }
//
// /**
// * @return Icon in the bottom left of the screen that rotates when the
// * engine is in the process of finding a move
// */
// public EngineThinkingImage getEngineThinkingImage() {
// return mEngineThinking;
// }
// }
| import nkarasch.chessgdx.GameCore;
import nkarasch.chessgdx.view.renderers.OverlayRenderer;
import chesspresso.Chess;
import chesspresso.move.IllegalMoveException;
import chesspresso.move.Move;
import chesspresso.position.Position;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ObjectMap; | package nkarasch.chessgdx.logiccontroller.backend;
public class ChessLogicController {
private final ObjectMap<Integer, Array<Short>> mLegalMoveMap;
private final UCIEngineInterface mUCIInterface;
private Position mPosition; | // Path: core/src/nkarasch/chessgdx/GameCore.java
// public class GameCore implements ApplicationListener {
//
// public static final String TITLE = "ChessGDX";
//
// private Camera mCameraController;
// private ChessLogicController mLogicController;
// private BoardController mBoardController;
// private PerspectiveRenderer mPerspectiveRenderer;
// private OverlayRenderer mOverlayRenderer;
//
// private static Runnable rebootHook;
//
// /**
// * @param rebootHook
// * game restart hook
// */
// public GameCore(final Runnable rebootHook) {
// GameCore.rebootHook = rebootHook;
// }
//
// @Override
// public void create() {
// GraphicsSettings.setGraphics();
// mCameraController = new Camera();
// mOverlayRenderer = new OverlayRenderer(this);
// mLogicController = new ChessLogicController(mOverlayRenderer);
// mBoardController = new BoardController(mCameraController, mLogicController, mOverlayRenderer);
// mPerspectiveRenderer = new PerspectiveRenderer(mCameraController, mBoardController, mLogicController.getPlacement());
//
// Gdx.input.setInputProcessor(new InputMultiplexer(mOverlayRenderer, mBoardController, mCameraController.getOrbitController()));
// }
//
// @Override
// public void render() {
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
// mCameraController.update();
// mPerspectiveRenderer.render();
// mOverlayRenderer.render();
// }
//
// @Override
// public void resize(int width, int height) {
// // requiring restart on resize instead, this would be tedious to set up
// }
//
// @Override
// public void pause() {
// // not supporting mobile
// }
//
// @Override
// public void resume() {
// // not supporting mobile
// }
//
// @Override
// public void dispose() {
// AssetHandler.getInstance().dispose();
// mLogicController.dispose();
// mOverlayRenderer.dispose();
// }
//
// /**
// * Restarts game client
// */
// public static void restart() {
// Gdx.app.postRunnable(GameCore.rebootHook);
// }
//
// /**
// * Restores board back to the new game state
// *
// * @param isWhite
// * player color
// */
// public void newGame(boolean isWhite) {
// mBoardController.setPlayerColor(isWhite);
// mBoardController.resetList();
// mLogicController.resetPosition();
// mOverlayRenderer.getCheckmateDialog().setState(false, false);
// mOverlayRenderer.getMoveHistory().resetHistory();
// }
// }
//
// Path: core/src/nkarasch/chessgdx/view/renderers/OverlayRenderer.java
// public class OverlayRenderer extends Stage {
//
// private final Skin mSkin;
// private final PromotionTable mPromotionDialog;
// private final CheckMateTable mCheckmateDialog;
// private final EngineThinkingImage mEngineThinking;
// private final SlidingMenuGroup mSlidingMenu;
//
// /**
// * Foundation of the Scene2D based GUI.
// *
// * @param core
// * root of game, is passed in so GUI elements can trigger
// * {@link GameCore#restart()} and
// * {@link GameCore#newGame(boolean)}
// */
// public OverlayRenderer(GameCore core) {
//
// mSkin = new MenuSkin();
// ExitConfirmTable exitConfirm = new ExitConfirmTable(mSkin);
// SettingsMenuGroup settings = new SettingsMenuGroup(mSkin);
// mSlidingMenu = new SlidingMenuGroup(mSkin, exitConfirm, settings, core);
// mEngineThinking = new EngineThinkingImage(mSkin);
// mPromotionDialog = new PromotionTable(mSkin);
// mCheckmateDialog = new CheckMateTable(mSkin);
//
// addActor(mPromotionDialog);
// addActor(mCheckmateDialog);
// addActor(settings);
// addActor(mSlidingMenu);
// addActor(mEngineThinking);
// addActor(exitConfirm);
// }
//
// public void render() {
// act(Gdx.graphics.getDeltaTime());
// draw();
// }
//
// public void dispose() {
// mSkin.dispose();
// super.dispose();
// }
//
// /**
// * @return UI element displaying the move history for both black and white
// */
// public MoveHistoryTable getMoveHistory() {
// return mSlidingMenu.getMoveHistory();
// }
//
// /**
// * @return UI element for letting the user which piece they want to promote
// * their pawns to
// */
// public PromotionTable getPromotionDialog() {
// return mPromotionDialog;
// }
//
// /**
// *
// * @return UI element informing the user when the board is in a check or
// * checkmate state
// */
// public CheckMateTable getCheckmateDialog() {
// return mCheckmateDialog;
// }
//
// /**
// * @return Icon in the bottom left of the screen that rotates when the
// * engine is in the process of finding a move
// */
// public EngineThinkingImage getEngineThinkingImage() {
// return mEngineThinking;
// }
// }
// Path: core/src/nkarasch/chessgdx/logiccontroller/backend/ChessLogicController.java
import nkarasch.chessgdx.GameCore;
import nkarasch.chessgdx.view.renderers.OverlayRenderer;
import chesspresso.Chess;
import chesspresso.move.IllegalMoveException;
import chesspresso.move.Move;
import chesspresso.position.Position;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ObjectMap;
package nkarasch.chessgdx.logiccontroller.backend;
public class ChessLogicController {
private final ObjectMap<Integer, Array<Short>> mLegalMoveMap;
private final UCIEngineInterface mUCIInterface;
private Position mPosition; | private final OverlayRenderer mOverlay; |
nkarasch/ChessGDX | core/src/nkarasch/chessgdx/logiccontroller/backend/UCIEngineInterface.java | // Path: core/src/nkarasch/chessgdx/GameCore.java
// public class GameCore implements ApplicationListener {
//
// public static final String TITLE = "ChessGDX";
//
// private Camera mCameraController;
// private ChessLogicController mLogicController;
// private BoardController mBoardController;
// private PerspectiveRenderer mPerspectiveRenderer;
// private OverlayRenderer mOverlayRenderer;
//
// private static Runnable rebootHook;
//
// /**
// * @param rebootHook
// * game restart hook
// */
// public GameCore(final Runnable rebootHook) {
// GameCore.rebootHook = rebootHook;
// }
//
// @Override
// public void create() {
// GraphicsSettings.setGraphics();
// mCameraController = new Camera();
// mOverlayRenderer = new OverlayRenderer(this);
// mLogicController = new ChessLogicController(mOverlayRenderer);
// mBoardController = new BoardController(mCameraController, mLogicController, mOverlayRenderer);
// mPerspectiveRenderer = new PerspectiveRenderer(mCameraController, mBoardController, mLogicController.getPlacement());
//
// Gdx.input.setInputProcessor(new InputMultiplexer(mOverlayRenderer, mBoardController, mCameraController.getOrbitController()));
// }
//
// @Override
// public void render() {
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
// mCameraController.update();
// mPerspectiveRenderer.render();
// mOverlayRenderer.render();
// }
//
// @Override
// public void resize(int width, int height) {
// // requiring restart on resize instead, this would be tedious to set up
// }
//
// @Override
// public void pause() {
// // not supporting mobile
// }
//
// @Override
// public void resume() {
// // not supporting mobile
// }
//
// @Override
// public void dispose() {
// AssetHandler.getInstance().dispose();
// mLogicController.dispose();
// mOverlayRenderer.dispose();
// }
//
// /**
// * Restarts game client
// */
// public static void restart() {
// Gdx.app.postRunnable(GameCore.rebootHook);
// }
//
// /**
// * Restores board back to the new game state
// *
// * @param isWhite
// * player color
// */
// public void newGame(boolean isWhite) {
// mBoardController.setPlayerColor(isWhite);
// mBoardController.resetList();
// mLogicController.resetPosition();
// mOverlayRenderer.getCheckmateDialog().setState(false, false);
// mOverlayRenderer.getMoveHistory().resetHistory();
// }
// }
//
// Path: core/src/nkarasch/chessgdx/util/PreferenceStrings.java
// public class PreferenceStrings {
// public static final String ENGINE_PATH = "engine_path";
// public static final String SEARCH_VALUE = "search_value";
// public static final String DEPTH_SEARCH = "depth_search";
//
// public static final String VSYNC = "vsync";
// public static final String DISPLAY_WIDTH = "display_width";
// public static final String DISPLAY_HEIGHT = "display_height";
// public static final String FULLSCREEN = "fullscreen";
//
// public static final String MUSIC_VOLUME = "music_volume";
// public static final String EFFECTS_VOLUME = "effects_volume";
// }
| import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import nkarasch.chessgdx.GameCore;
import nkarasch.chessgdx.util.PreferenceStrings;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Preferences; | package nkarasch.chessgdx.logiccontroller.backend;
/**
* Adapted from Rahul A R's "JavaStockfish".
* https://github.com/rahular/chess-misc
* /blob/master/JavaStockfish/src/com/rahul/stockfish/Stockfish.java
*
* I've changed it to make best move searches non-blocking so the entire game
* doesn't halt while the engine is calculating. There is room for improvement.
*/
// TODO make engine process shut down properly after validateEngine is called
public class UCIEngineInterface {
private final ExecutorService mService;
private Future<String> mTask;
private Process mEngineProcess;
private final ProcessBuilder mProcessBuilder;
private BufferedReader mProcessReader;
private OutputStreamWriter mProcessWriter;
private String mFEN;
private final String mSearchType;
private final int mSearchValue;
UCIEngineInterface(String PATH) {
mProcessBuilder = new ProcessBuilder(PATH);
mService = Executors.newFixedThreadPool(1);
startEngine();
mTask = null;
| // Path: core/src/nkarasch/chessgdx/GameCore.java
// public class GameCore implements ApplicationListener {
//
// public static final String TITLE = "ChessGDX";
//
// private Camera mCameraController;
// private ChessLogicController mLogicController;
// private BoardController mBoardController;
// private PerspectiveRenderer mPerspectiveRenderer;
// private OverlayRenderer mOverlayRenderer;
//
// private static Runnable rebootHook;
//
// /**
// * @param rebootHook
// * game restart hook
// */
// public GameCore(final Runnable rebootHook) {
// GameCore.rebootHook = rebootHook;
// }
//
// @Override
// public void create() {
// GraphicsSettings.setGraphics();
// mCameraController = new Camera();
// mOverlayRenderer = new OverlayRenderer(this);
// mLogicController = new ChessLogicController(mOverlayRenderer);
// mBoardController = new BoardController(mCameraController, mLogicController, mOverlayRenderer);
// mPerspectiveRenderer = new PerspectiveRenderer(mCameraController, mBoardController, mLogicController.getPlacement());
//
// Gdx.input.setInputProcessor(new InputMultiplexer(mOverlayRenderer, mBoardController, mCameraController.getOrbitController()));
// }
//
// @Override
// public void render() {
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
// mCameraController.update();
// mPerspectiveRenderer.render();
// mOverlayRenderer.render();
// }
//
// @Override
// public void resize(int width, int height) {
// // requiring restart on resize instead, this would be tedious to set up
// }
//
// @Override
// public void pause() {
// // not supporting mobile
// }
//
// @Override
// public void resume() {
// // not supporting mobile
// }
//
// @Override
// public void dispose() {
// AssetHandler.getInstance().dispose();
// mLogicController.dispose();
// mOverlayRenderer.dispose();
// }
//
// /**
// * Restarts game client
// */
// public static void restart() {
// Gdx.app.postRunnable(GameCore.rebootHook);
// }
//
// /**
// * Restores board back to the new game state
// *
// * @param isWhite
// * player color
// */
// public void newGame(boolean isWhite) {
// mBoardController.setPlayerColor(isWhite);
// mBoardController.resetList();
// mLogicController.resetPosition();
// mOverlayRenderer.getCheckmateDialog().setState(false, false);
// mOverlayRenderer.getMoveHistory().resetHistory();
// }
// }
//
// Path: core/src/nkarasch/chessgdx/util/PreferenceStrings.java
// public class PreferenceStrings {
// public static final String ENGINE_PATH = "engine_path";
// public static final String SEARCH_VALUE = "search_value";
// public static final String DEPTH_SEARCH = "depth_search";
//
// public static final String VSYNC = "vsync";
// public static final String DISPLAY_WIDTH = "display_width";
// public static final String DISPLAY_HEIGHT = "display_height";
// public static final String FULLSCREEN = "fullscreen";
//
// public static final String MUSIC_VOLUME = "music_volume";
// public static final String EFFECTS_VOLUME = "effects_volume";
// }
// Path: core/src/nkarasch/chessgdx/logiccontroller/backend/UCIEngineInterface.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import nkarasch.chessgdx.GameCore;
import nkarasch.chessgdx.util.PreferenceStrings;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Preferences;
package nkarasch.chessgdx.logiccontroller.backend;
/**
* Adapted from Rahul A R's "JavaStockfish".
* https://github.com/rahular/chess-misc
* /blob/master/JavaStockfish/src/com/rahul/stockfish/Stockfish.java
*
* I've changed it to make best move searches non-blocking so the entire game
* doesn't halt while the engine is calculating. There is room for improvement.
*/
// TODO make engine process shut down properly after validateEngine is called
public class UCIEngineInterface {
private final ExecutorService mService;
private Future<String> mTask;
private Process mEngineProcess;
private final ProcessBuilder mProcessBuilder;
private BufferedReader mProcessReader;
private OutputStreamWriter mProcessWriter;
private String mFEN;
private final String mSearchType;
private final int mSearchValue;
UCIEngineInterface(String PATH) {
mProcessBuilder = new ProcessBuilder(PATH);
mService = Executors.newFixedThreadPool(1);
startEngine();
mTask = null;
| Preferences pref = Gdx.app.getPreferences(GameCore.TITLE); |
nkarasch/ChessGDX | core/src/nkarasch/chessgdx/logiccontroller/backend/UCIEngineInterface.java | // Path: core/src/nkarasch/chessgdx/GameCore.java
// public class GameCore implements ApplicationListener {
//
// public static final String TITLE = "ChessGDX";
//
// private Camera mCameraController;
// private ChessLogicController mLogicController;
// private BoardController mBoardController;
// private PerspectiveRenderer mPerspectiveRenderer;
// private OverlayRenderer mOverlayRenderer;
//
// private static Runnable rebootHook;
//
// /**
// * @param rebootHook
// * game restart hook
// */
// public GameCore(final Runnable rebootHook) {
// GameCore.rebootHook = rebootHook;
// }
//
// @Override
// public void create() {
// GraphicsSettings.setGraphics();
// mCameraController = new Camera();
// mOverlayRenderer = new OverlayRenderer(this);
// mLogicController = new ChessLogicController(mOverlayRenderer);
// mBoardController = new BoardController(mCameraController, mLogicController, mOverlayRenderer);
// mPerspectiveRenderer = new PerspectiveRenderer(mCameraController, mBoardController, mLogicController.getPlacement());
//
// Gdx.input.setInputProcessor(new InputMultiplexer(mOverlayRenderer, mBoardController, mCameraController.getOrbitController()));
// }
//
// @Override
// public void render() {
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
// mCameraController.update();
// mPerspectiveRenderer.render();
// mOverlayRenderer.render();
// }
//
// @Override
// public void resize(int width, int height) {
// // requiring restart on resize instead, this would be tedious to set up
// }
//
// @Override
// public void pause() {
// // not supporting mobile
// }
//
// @Override
// public void resume() {
// // not supporting mobile
// }
//
// @Override
// public void dispose() {
// AssetHandler.getInstance().dispose();
// mLogicController.dispose();
// mOverlayRenderer.dispose();
// }
//
// /**
// * Restarts game client
// */
// public static void restart() {
// Gdx.app.postRunnable(GameCore.rebootHook);
// }
//
// /**
// * Restores board back to the new game state
// *
// * @param isWhite
// * player color
// */
// public void newGame(boolean isWhite) {
// mBoardController.setPlayerColor(isWhite);
// mBoardController.resetList();
// mLogicController.resetPosition();
// mOverlayRenderer.getCheckmateDialog().setState(false, false);
// mOverlayRenderer.getMoveHistory().resetHistory();
// }
// }
//
// Path: core/src/nkarasch/chessgdx/util/PreferenceStrings.java
// public class PreferenceStrings {
// public static final String ENGINE_PATH = "engine_path";
// public static final String SEARCH_VALUE = "search_value";
// public static final String DEPTH_SEARCH = "depth_search";
//
// public static final String VSYNC = "vsync";
// public static final String DISPLAY_WIDTH = "display_width";
// public static final String DISPLAY_HEIGHT = "display_height";
// public static final String FULLSCREEN = "fullscreen";
//
// public static final String MUSIC_VOLUME = "music_volume";
// public static final String EFFECTS_VOLUME = "effects_volume";
// }
| import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import nkarasch.chessgdx.GameCore;
import nkarasch.chessgdx.util.PreferenceStrings;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Preferences; | package nkarasch.chessgdx.logiccontroller.backend;
/**
* Adapted from Rahul A R's "JavaStockfish".
* https://github.com/rahular/chess-misc
* /blob/master/JavaStockfish/src/com/rahul/stockfish/Stockfish.java
*
* I've changed it to make best move searches non-blocking so the entire game
* doesn't halt while the engine is calculating. There is room for improvement.
*/
// TODO make engine process shut down properly after validateEngine is called
public class UCIEngineInterface {
private final ExecutorService mService;
private Future<String> mTask;
private Process mEngineProcess;
private final ProcessBuilder mProcessBuilder;
private BufferedReader mProcessReader;
private OutputStreamWriter mProcessWriter;
private String mFEN;
private final String mSearchType;
private final int mSearchValue;
UCIEngineInterface(String PATH) {
mProcessBuilder = new ProcessBuilder(PATH);
mService = Executors.newFixedThreadPool(1);
startEngine();
mTask = null;
Preferences pref = Gdx.app.getPreferences(GameCore.TITLE); | // Path: core/src/nkarasch/chessgdx/GameCore.java
// public class GameCore implements ApplicationListener {
//
// public static final String TITLE = "ChessGDX";
//
// private Camera mCameraController;
// private ChessLogicController mLogicController;
// private BoardController mBoardController;
// private PerspectiveRenderer mPerspectiveRenderer;
// private OverlayRenderer mOverlayRenderer;
//
// private static Runnable rebootHook;
//
// /**
// * @param rebootHook
// * game restart hook
// */
// public GameCore(final Runnable rebootHook) {
// GameCore.rebootHook = rebootHook;
// }
//
// @Override
// public void create() {
// GraphicsSettings.setGraphics();
// mCameraController = new Camera();
// mOverlayRenderer = new OverlayRenderer(this);
// mLogicController = new ChessLogicController(mOverlayRenderer);
// mBoardController = new BoardController(mCameraController, mLogicController, mOverlayRenderer);
// mPerspectiveRenderer = new PerspectiveRenderer(mCameraController, mBoardController, mLogicController.getPlacement());
//
// Gdx.input.setInputProcessor(new InputMultiplexer(mOverlayRenderer, mBoardController, mCameraController.getOrbitController()));
// }
//
// @Override
// public void render() {
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
// mCameraController.update();
// mPerspectiveRenderer.render();
// mOverlayRenderer.render();
// }
//
// @Override
// public void resize(int width, int height) {
// // requiring restart on resize instead, this would be tedious to set up
// }
//
// @Override
// public void pause() {
// // not supporting mobile
// }
//
// @Override
// public void resume() {
// // not supporting mobile
// }
//
// @Override
// public void dispose() {
// AssetHandler.getInstance().dispose();
// mLogicController.dispose();
// mOverlayRenderer.dispose();
// }
//
// /**
// * Restarts game client
// */
// public static void restart() {
// Gdx.app.postRunnable(GameCore.rebootHook);
// }
//
// /**
// * Restores board back to the new game state
// *
// * @param isWhite
// * player color
// */
// public void newGame(boolean isWhite) {
// mBoardController.setPlayerColor(isWhite);
// mBoardController.resetList();
// mLogicController.resetPosition();
// mOverlayRenderer.getCheckmateDialog().setState(false, false);
// mOverlayRenderer.getMoveHistory().resetHistory();
// }
// }
//
// Path: core/src/nkarasch/chessgdx/util/PreferenceStrings.java
// public class PreferenceStrings {
// public static final String ENGINE_PATH = "engine_path";
// public static final String SEARCH_VALUE = "search_value";
// public static final String DEPTH_SEARCH = "depth_search";
//
// public static final String VSYNC = "vsync";
// public static final String DISPLAY_WIDTH = "display_width";
// public static final String DISPLAY_HEIGHT = "display_height";
// public static final String FULLSCREEN = "fullscreen";
//
// public static final String MUSIC_VOLUME = "music_volume";
// public static final String EFFECTS_VOLUME = "effects_volume";
// }
// Path: core/src/nkarasch/chessgdx/logiccontroller/backend/UCIEngineInterface.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import nkarasch.chessgdx.GameCore;
import nkarasch.chessgdx.util.PreferenceStrings;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Preferences;
package nkarasch.chessgdx.logiccontroller.backend;
/**
* Adapted from Rahul A R's "JavaStockfish".
* https://github.com/rahular/chess-misc
* /blob/master/JavaStockfish/src/com/rahul/stockfish/Stockfish.java
*
* I've changed it to make best move searches non-blocking so the entire game
* doesn't halt while the engine is calculating. There is room for improvement.
*/
// TODO make engine process shut down properly after validateEngine is called
public class UCIEngineInterface {
private final ExecutorService mService;
private Future<String> mTask;
private Process mEngineProcess;
private final ProcessBuilder mProcessBuilder;
private BufferedReader mProcessReader;
private OutputStreamWriter mProcessWriter;
private String mFEN;
private final String mSearchType;
private final int mSearchValue;
UCIEngineInterface(String PATH) {
mProcessBuilder = new ProcessBuilder(PATH);
mService = Executors.newFixedThreadPool(1);
startEngine();
mTask = null;
Preferences pref = Gdx.app.getPreferences(GameCore.TITLE); | if (pref.getBoolean(PreferenceStrings.DEPTH_SEARCH)) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.