lang stringclasses 1 value | license stringclasses 13 values | stderr stringlengths 0 350 | commit stringlengths 40 40 | returncode int64 0 128 | repos stringlengths 7 45.1k | new_contents stringlengths 0 1.87M | new_file stringlengths 6 292 | old_contents stringlengths 0 1.87M | message stringlengths 6 9.26k | old_file stringlengths 6 292 | subject stringlengths 0 4.45k |
|---|---|---|---|---|---|---|---|---|---|---|---|
Java | mit | 62c3032c6cb87dac376f63924e1034b3abc1baa5 | 0 | Alan736/NotCardinalPGM,Aaron1011/CardinalPGM,dentmaged/CardinalPGM,dentmaged/CardinalPGM,Alan736/NotCardinalPGM,iPGz/CardinalPGM,Pablete1234/CardinalPGM,CaptainElliott/CardinalPGM,dentmaged/Cardinal-Dev,TheMolkaPL/CardinalPGM,angelitorb99/CardinalPGM,dentmaged/Cardinal-Dev,twizmwazin/CardinalPGM,TheMolkaPL/CardinalPGM,SungMatt/CardinalPGM,Electroid/ExperimentalPGM,dentmaged/Cardinal-Plus,dentmaged/Cardinal-Plus,Electroid/ExperimentalPGM | package in.twizmwaz.cardinal.module.modules.filter;
import in.twizmwaz.cardinal.GameHandler;
import in.twizmwaz.cardinal.match.Match;
import in.twizmwaz.cardinal.module.BuilderData;
import in.twizmwaz.cardinal.module.ModuleBuilder;
import in.twizmwaz.cardinal.module.ModuleCollection;
import in.twizmwaz.cardinal.module.ModuleLoadTime;
import in.twizmwaz.cardinal.module.modules.filter.parsers.*;
import in.twizmwaz.cardinal.module.modules.filter.type.*;
import in.twizmwaz.cardinal.module.modules.filter.type.constant.*;
import in.twizmwaz.cardinal.module.modules.filter.type.logic.AllFilter;
import in.twizmwaz.cardinal.module.modules.filter.type.logic.AnyFilter;
import in.twizmwaz.cardinal.module.modules.filter.type.logic.NotFilter;
import in.twizmwaz.cardinal.module.modules.filter.type.logic.OneFilter;
import in.twizmwaz.cardinal.module.modules.filter.type.old.AllowFilter;
import in.twizmwaz.cardinal.module.modules.filter.type.old.DenyFilter;
import org.jdom2.Document;
import org.jdom2.Element;
@BuilderData(load = ModuleLoadTime.EARLIER)
public class FilterModuleBuilder implements ModuleBuilder {
@Override
public ModuleCollection load(Match match) {
match.getModules().add(new AllEventFilter("allow-all", true));
match.getModules().add(new AllEventFilter("deny-all", false));
match.getModules().add(new AllPlayerFilter("allow-players", true));
match.getModules().add(new AllPlayerFilter("deny-players", false));
match.getModules().add(new AllBlockFilter("allow-blocks", true));
match.getModules().add(new AllBlockFilter("deny-blocks", false));
match.getModules().add(new AllWorldFilter("allow-world", true));
match.getModules().add(new AllWorldFilter("deny-world", false));
match.getModules().add(new AllSpawnFilter("allow-spawns", true));
match.getModules().add(new AllSpawnFilter("deny-spawns", false));
match.getModules().add(new AllEntitiesFilter("allow-entities", true));
match.getModules().add(new AllEntitiesFilter("deny-entities", false));
match.getModules().add(new AllMobFilter("allow-mobs", true));
match.getModules().add(new AllMobFilter("deny-mobs", false));
for(Element element : match.getDocument().getRootElement().getChildren("filters")) {
for (Element filter : element.getChildren("filter")) {
match.getModules().add(getFilter(filter.getChildren().get(0)));
}
}
return new ModuleCollection<FilterModule>();
}
/**
* @param element Element to parse
* @param document Document to find filter in case the given filter is a reference
* @return The filter based upon the given element
*/
public static FilterModule getFilter(Element element, Document document) {
switch (element.getName().toLowerCase()) {
case "block":
return new BlockFilter(new BlockFilterParser(element));
case "carrying":
return new CarryingFilter(new ItemFilterParser(element));
case "cause":
return new CauseFilter(new CauseFilterParser(element));
case "class":
return new ClassFilter(new ClassFilterParser(element));
case "crouching":
return new CrouchingFilter(new FilterParser(element));
case "entity":
return new EntityFilter(new EntityFilterParser(element));
case "can-fly":
return new FlyingAbilityFilter(new FilterParser(element));
case "flying":
return new FlyingFilter(new FilterParser(element));
case "holding":
return new HoldingFilter(new ItemFilterParser(element));
case "kill-streak":
return new KillStreakFilter(new KillstreakFilterParser(element));
case "mob":
return new MobFilter(new MobFilterParser(element));
case "objective":
return new ObjectiveFilter(new ObjectiveFilterParser(element));
case "random":
return new RandomFilter(new RandomFilterParser(element));
case "spawn":
return new SpawnFilter(new SpawnFilterParser(element));
case "team":
return new TeamFilter((new TeamFilterParser(element)));
case "void":
return new VoidFilter(new GenericFilterParser(element));
case "wearing":
return new WearingFilter(new ItemFilterParser(element));
case "all":
return new AllFilter(new ChildrenFilterParser(element));
case "any":
return new AnyFilter(new ChildrenFilterParser(element));
case "not":
return new NotFilter(new ChildFilterParser(element));
case "one":
return new OneFilter(new ChildrenFilterParser(element));
case "allow":
return new AllowFilter(new GenericFilterParser(element));
case "deny":
return new DenyFilter(new GenericFilterParser(element));
case "filter":
switch (element.getAttributeValue("name").toLowerCase()) {
case "allow-all":
return new AllEventFilter("allow-all", true);
case "deny-all":
return new AllEventFilter("deny-all", false);
case "allow-players":
return new AllPlayerFilter("allow-players", true);
case "deny-players":
return new AllPlayerFilter("deny-players", false);
case "allow-blocks":
return new AllBlockFilter("allow-blocks", true);
case "deny-blocks":
return new AllBlockFilter("deny-blocks", false);
case "allow-world":
return new AllWorldFilter("allow-world", true);
case "deny-world":
return new AllWorldFilter("deny-world", false);
case "allow-spawns":
return new AllSpawnFilter("allow-spawns", true);
case "deny-spawns":
return new AllSpawnFilter("deny-spawns", false);
case "allow-entities":
return new AllEntitiesFilter("allow-entities", true);
case "deny-entities":
return new AllEntitiesFilter("deny-entities", false);
case "allow-mobs":
return new AllMobFilter("allow-mobs", true);
case "deny-mobs":
return new AllMobFilter("deny-mobs", false);
default:
if (element.getAttributeValue("name") != null) {
for (Element filterElement : document.getRootElement().getChildren("filters")) {
for (Element givenFilter : filterElement.getChildren()) {
if (givenFilter.getAttributeValue("name").equalsIgnoreCase(element.getAttributeValue("name")))
return getFilter(givenFilter.getChildren().get(0));
}
}
} else {
return getFilter(element.getChildren().get(0));
}
}
default:
return null;
}
}
/**
* This method will default the document to the document of the current match (possibly buggy)
*
* @param element Element to parse
* @return The filter based upon the given element
*/
public static FilterModule getFilter(Element element) {
return getFilter(element, GameHandler.getGameHandler().getMatch().getDocument());
}
/**
* Gets a loaded filter by the given name
* @param string
* @return
*/
public static FilterModule getFilter(String string) {
for (FilterModule filterModule : GameHandler.getGameHandler().getMatch().getModules().getModules(FilterModule.class)) {
if (string.equalsIgnoreCase(filterModule.getName())) return filterModule;
}
return null;
}
}
| src/main/java/in/twizmwaz/cardinal/module/modules/filter/FilterModuleBuilder.java | package in.twizmwaz.cardinal.module.modules.filter;
import in.twizmwaz.cardinal.GameHandler;
import in.twizmwaz.cardinal.match.Match;
import in.twizmwaz.cardinal.module.BuilderData;
import in.twizmwaz.cardinal.module.ModuleBuilder;
import in.twizmwaz.cardinal.module.ModuleCollection;
import in.twizmwaz.cardinal.module.ModuleLoadTime;
import in.twizmwaz.cardinal.module.modules.filter.parsers.*;
import in.twizmwaz.cardinal.module.modules.filter.type.*;
import in.twizmwaz.cardinal.module.modules.filter.type.constant.*;
import in.twizmwaz.cardinal.module.modules.filter.type.logic.AllFilter;
import in.twizmwaz.cardinal.module.modules.filter.type.logic.AnyFilter;
import in.twizmwaz.cardinal.module.modules.filter.type.logic.NotFilter;
import in.twizmwaz.cardinal.module.modules.filter.type.logic.OneFilter;
import in.twizmwaz.cardinal.module.modules.filter.type.old.AllowFilter;
import in.twizmwaz.cardinal.module.modules.filter.type.old.DenyFilter;
import org.jdom2.Document;
import org.jdom2.Element;
@BuilderData(load = ModuleLoadTime.EARLIER)
public class FilterModuleBuilder implements ModuleBuilder {
@Override
public ModuleCollection load(Match match) {
match.getModules().add(new AllEventFilter("allow-all", true));
match.getModules().add(new AllEventFilter("deny-all", false));
match.getModules().add(new AllPlayerFilter("allow-players", true));
match.getModules().add(new AllPlayerFilter("deny-players", false));
match.getModules().add(new AllBlockFilter("allow-blocks", true));
match.getModules().add(new AllBlockFilter("deny-blocks", false));
match.getModules().add(new AllWorldFilter("allow-world", true));
match.getModules().add(new AllWorldFilter("deny-world", false));
match.getModules().add(new AllSpawnFilter("allow-spawns", true));
match.getModules().add(new AllSpawnFilter("deny-spawns", false));
match.getModules().add(new AllEntitiesFilter("allow-entities", true));
match.getModules().add(new AllEntitiesFilter("deny-entities", false));
match.getModules().add(new AllMobFilter("allow-mobs", true));
match.getModules().add(new AllMobFilter("deny-mobs", false));
for(Element element : match.getDocument().getRootElement().getChildren("filters")) {
for (Element filter : element.getChildren("filter")) {
match.getModules().add(getFilter(filter.getChildren().get(0)));
}
}
return new ModuleCollection<FilterModule>();
}
/**
* @param element Element to parse
* @param document Document to find filter in case the given filter is a reference
* @return The filter based upon the given element
*/
public static FilterModule getFilter(Element element, Document document) {
switch (element.getName().toLowerCase()) {
case "block":
return new BlockFilter(new BlockFilterParser(element));
case "carrying":
return new CarryingFilter(new ItemFilterParser(element));
case "cause":
return new CauseFilter(new CauseFilterParser(element));
case "class":
return new ClassFilter(new ClassFilterParser(element));
case "crouching":
return new CrouchingFilter(new FilterParser(element));
case "entity":
return new EntityFilter(new EntityFilterParser(element));
case "can-fly":
return new FlyingAbilityFilter(new FilterParser(element));
case "flying":
return new FlyingFilter(new FilterParser(element));
case "holding":
return new HoldingFilter(new ItemFilterParser(element));
case "kill-streak":
return new KillStreakFilter(new KillstreakFilterParser(element));
case "mob":
return new MobFilter(new MobFilterParser(element));
case "objective":
return new ObjectiveFilter(new ObjectiveFilterParser(element));
case "random":
return new RandomFilter(new RandomFilterParser(element));
case "spawn":
return new SpawnFilter(new SpawnFilterParser(element));
case "team":
return new TeamFilter((new TeamFilterParser(element)));
case "void":
return new VoidFilter(new GenericFilterParser(element));
case "wearing":
return new WearingFilter(new ItemFilterParser(element));
case "all":
return new AllFilter(new ChildrenFilterParser(element));
case "any":
return new AnyFilter(new ChildrenFilterParser(element));
case "not":
return new NotFilter(new ChildFilterParser(element));
case "one":
return new OneFilter(new ChildrenFilterParser(element));
case "allow":
return new AllowFilter(new GenericFilterParser(element));
case "deny":
return new DenyFilter(new GenericFilterParser(element));
case "filter":
switch (element.getAttributeValue("name").toLowerCase()) {
case "allow-all":
return new AllEventFilter("allow-all", true);
case "deny-all":
return new AllEventFilter("deny-all", false);
case "allow-players":
return new AllPlayerFilter("allow-players", true);
case "deny-players":
return new AllPlayerFilter("deny-players", false);
case "allow-blocks":
return new AllBlockFilter("allow-blocks", true);
case "deny-blocks":
return new AllBlockFilter("deny-blocks", false);
case "allow-world":
return new AllWorldFilter("allow-world", true);
case "deny-world":
return new AllWorldFilter("deny-world", false);
case "allow-spawns":
return new AllSpawnFilter("allow-spawns", true);
case "deny-spawns":
return new AllSpawnFilter("deny-spawns", false);
case "allow-entities":
return new AllEntitiesFilter("allow-entities", true);
case "deny-entities":
return new AllEntitiesFilter("deny-entities", false);
case "allow-mobs":
return new AllMobFilter("allow-mobs", true);
case "deny-mobs":
return new AllMobFilter("deny-mobs", false);
default:
if (element.getAttributeValue("name") != null) {
for (Element filterElement : document.getRootElement().getChildren("filters")) {
for (Element givenFilter : filterElement.getChildren()) {
if (givenFilter.getAttributeValue("name").equalsIgnoreCase(element.getAttributeValue("name")))
return getFilter(givenFilter);
}
}
} else {
return getFilter(element.getChildren().get(0));
}
}
default:
return null;
}
}
/**
* This method will default the document to the document of the current match (possibly buggy)
*
* @param element Element to parse
* @return The filter based upon the given element
*/
public static FilterModule getFilter(Element element) {
return getFilter(element, GameHandler.getGameHandler().getMatch().getDocument());
}
/**
* Gets a loaded filter by the given name
* @param string
* @return
*/
public static FilterModule getFilter(String string) {
for (FilterModule filterModule : GameHandler.getGameHandler().getMatch().getModules().getModules(FilterModule.class)) {
if (string.equalsIgnoreCase(filterModule.getName())) return filterModule;
}
return null;
}
}
| Fix recrusively loading filters
| src/main/java/in/twizmwaz/cardinal/module/modules/filter/FilterModuleBuilder.java | Fix recrusively loading filters | |
Java | mit | c66c0ae466c38f355254e865d8a164ce84337029 | 0 | aureliano/da-mihi-logs,aureliano/da-mihi-logs | package com.github.aureliano.evtbridge.app.helper;
import org.reflections.Reflections;
import com.github.aureliano.evtbridge.common.exception.EventBridgeException;
import com.github.aureliano.evtbridge.common.helper.StringHelper;
import com.github.aureliano.evtbridge.core.SchemaTypes;
import com.github.aureliano.evtbridge.core.config.IConfiguration;
import com.github.aureliano.evtbridge.core.config.InputConfigTypes;
import com.github.aureliano.evtbridge.core.config.OutputConfigTypes;
import com.github.aureliano.evtbridge.core.doc.DocumentationSourceTypes;
import com.github.aureliano.evtbridge.core.doc.ISchemaBuilder;
import com.github.aureliano.evtbridge.core.doc.JsonSchemaBuilder;
import com.github.aureliano.evtbridge.core.doc.YamlSchemaBuilder;
import com.github.aureliano.evtbridge.core.schedule.SchedulerTypes;
import com.github.aureliano.evtbridge.input.external_command.ExternalCommandInputConfig;
import com.github.aureliano.evtbridge.input.file.FileInputConfig;
import com.github.aureliano.evtbridge.input.file_tailer.FileTailerInputConfig;
import com.github.aureliano.evtbridge.input.jdbc.JdbcInputConfig;
import com.github.aureliano.evtbridge.input.standard.StandardInputConfig;
import com.github.aureliano.evtbridge.input.url.UrlInputConfig;
import com.github.aureliano.evtbridge.output.elasticsearch.ElasticSearchOutputConfig;
import com.github.aureliano.evtbridge.output.file.FileOutputConfig;
import com.github.aureliano.evtbridge.output.jdbc.JdbcOutputConfig;
import com.github.aureliano.evtbridge.output.standard.StandardOutputConfig;
public final class ConfigurationSchemaHelper {
private ConfigurationSchemaHelper() {}
public static String fetchSchema(String type, String name, String format) {
final SchemaTypes schemaType = SchemaTypes.valueOf(type.toUpperCase());
final DocumentationSourceTypes sourceType = DocumentationSourceTypes.valueOf(format.toUpperCase());
if (StringHelper.isEmpty(name)) {
return ConfigurationSchemaHelper.getSchemaBuilder(sourceType).build(schemaType);
} else {
initializeResouces();
switch (schemaType) {
case SCHEDULER:
return ConfigurationSchemaHelper.getSchemaBuilder(sourceType)
.build(SchedulerTypes.valueOf(name.toUpperCase()));
case INPUT:
return buildInputSchema(sourceType, name);
case OUTPUT:
return buildOutputSchema(sourceType, name);
default:
throw new EventBridgeException("Unsupported schema type: [" + type + "]");
}
}
}
private static String buildInputSchema(DocumentationSourceTypes sourceType, String name) {
InputConfigTypes inputType = InputConfigTypes.valueOf(name.toUpperCase());
return ConfigurationSchemaHelper.getSchemaBuilder(sourceType).build(inputType);
}
private static String buildOutputSchema(DocumentationSourceTypes sourceType, String name) {
OutputConfigTypes outputType = OutputConfigTypes.valueOf(name.toUpperCase());
return ConfigurationSchemaHelper.getSchemaBuilder(sourceType).build(outputType);
}
private static void initializeResouces() {
Reflections reflections = new Reflections("com.github.aureliano.evtbridge");
Class<?>[] classes = reflections.getSubTypesOf(IConfiguration.class).toArray(new Class<?>[0]);
try {
for (Class<?> clazz : classes) {
Class.forName(clazz.getName());
}
} catch (ClassNotFoundException ex) {
throw new EventBridgeException(ex);
}
}
private static ISchemaBuilder<String> getSchemaBuilder(DocumentationSourceTypes sourceType) {
if (DocumentationSourceTypes.JSON.equals(sourceType)) {
return new JsonSchemaBuilder();
} else if (DocumentationSourceTypes.YAML.equals(sourceType)) {
return new YamlSchemaBuilder();
} else {
throw new EventBridgeException("Unsupported source type '" + sourceType + "'.");
}
}
} | evt-bridge-app/src/main/java/com/github/aureliano/evtbridge/app/helper/ConfigurationSchemaHelper.java | package com.github.aureliano.evtbridge.app.helper;
import com.github.aureliano.evtbridge.common.exception.EventBridgeException;
import com.github.aureliano.evtbridge.common.helper.StringHelper;
import com.github.aureliano.evtbridge.core.SchemaTypes;
import com.github.aureliano.evtbridge.core.config.InputConfigTypes;
import com.github.aureliano.evtbridge.core.config.OutputConfigTypes;
import com.github.aureliano.evtbridge.core.doc.DocumentationSourceTypes;
import com.github.aureliano.evtbridge.core.doc.ISchemaBuilder;
import com.github.aureliano.evtbridge.core.doc.JsonSchemaBuilder;
import com.github.aureliano.evtbridge.core.doc.YamlSchemaBuilder;
import com.github.aureliano.evtbridge.core.schedule.SchedulerTypes;
import com.github.aureliano.evtbridge.input.external_command.ExternalCommandInputConfig;
import com.github.aureliano.evtbridge.input.file.FileInputConfig;
import com.github.aureliano.evtbridge.input.file_tailer.FileTailerInputConfig;
import com.github.aureliano.evtbridge.input.jdbc.JdbcInputConfig;
import com.github.aureliano.evtbridge.input.standard.StandardInputConfig;
import com.github.aureliano.evtbridge.input.url.UrlInputConfig;
import com.github.aureliano.evtbridge.output.elasticsearch.ElasticSearchOutputConfig;
import com.github.aureliano.evtbridge.output.file.FileOutputConfig;
import com.github.aureliano.evtbridge.output.jdbc.JdbcOutputConfig;
import com.github.aureliano.evtbridge.output.standard.StandardOutputConfig;
public final class ConfigurationSchemaHelper {
private ConfigurationSchemaHelper() {}
public static String fetchSchema(String type, String name, String format) {
final SchemaTypes schemaType = SchemaTypes.valueOf(type.toUpperCase());
final DocumentationSourceTypes sourceType = DocumentationSourceTypes.valueOf(format.toUpperCase());
if (StringHelper.isEmpty(name)) {
return ConfigurationSchemaHelper.getSchemaBuilder(sourceType).build(schemaType);
} else {
switch (schemaType) {
case SCHEDULER:
return ConfigurationSchemaHelper.getSchemaBuilder(sourceType)
.build(SchedulerTypes.valueOf(name.toUpperCase()));
case INPUT:
return buildInputSchema(sourceType, name);
case OUTPUT:
return buildOutputSchema(sourceType, name);
default:
throw new EventBridgeException("Unsupported schema type: [" + type + "]");
}
}
}
private static String buildInputSchema(DocumentationSourceTypes sourceType, String name) {
InputConfigTypes inputType = InputConfigTypes.valueOf(name.toUpperCase());
initializeInputConfig(inputType);
return ConfigurationSchemaHelper.getSchemaBuilder(sourceType).build(inputType);
}
private static String buildOutputSchema(DocumentationSourceTypes sourceType, String name) {
OutputConfigTypes outputType = OutputConfigTypes.valueOf(name.toUpperCase());
initializeOutputConfig(outputType);
return ConfigurationSchemaHelper.getSchemaBuilder(sourceType).build(outputType);
}
private static void initializeInputConfig(InputConfigTypes inputType) {
switch (inputType) {
case FILE_INPUT:
initializeClass(FileInputConfig.class);
break;
case STANDARD_INPUT:
initializeClass(StandardInputConfig.class);
break;
case FILE_TAILER:
initializeClass(FileTailerInputConfig.class);
break;
case EXTERNAL_COMMAND:
initializeClass(ExternalCommandInputConfig.class);
break;
case JDBC_INPUT:
initializeClass(JdbcInputConfig.class);
break;
case URL:
initializeClass(UrlInputConfig.class);
break;
default:
break;
}
}
private static void initializeOutputConfig(OutputConfigTypes outputType) {
switch (outputType) {
case FILE_OUTPUT:
initializeClass(FileOutputConfig.class);
break;
case STANDARD_OUTPUT:
initializeClass(StandardOutputConfig.class);
break;
case ELASTIC_SEARCH:
initializeClass(ElasticSearchOutputConfig.class);
break;
case JDBC_OUTPUT:
initializeClass(JdbcOutputConfig.class);
break;
default:
break;
}
}
private static void initializeClass(Class<?> clazz) {
try {
Class.forName(clazz.getName());
} catch (ClassNotFoundException ex) {
throw new EventBridgeException(ex);
}
}
private static ISchemaBuilder<String> getSchemaBuilder(DocumentationSourceTypes sourceType) {
if (DocumentationSourceTypes.JSON.equals(sourceType)) {
return new JsonSchemaBuilder();
} else if (DocumentationSourceTypes.YAML.equals(sourceType)) {
return new YamlSchemaBuilder();
} else {
throw new EventBridgeException("Unsupported source type '" + sourceType + "'.");
}
}
} | Initialize resources.
| evt-bridge-app/src/main/java/com/github/aureliano/evtbridge/app/helper/ConfigurationSchemaHelper.java | Initialize resources. | |
Java | mit | fcfc766993dffec4e9415870eb764fe1134c2701 | 0 | hakandilek/play2-crud,hakandilek/play2-crud,hakandilek/play2-crud,hakandilek/play2-crud | package play.utils.crud;
import java.lang.reflect.Method;
import org.springframework.util.ReflectionUtils;
import play.Logger;
import play.Logger.ALogger;
import play.twirl.api.Html;
import play.twirl.api.Content;
import play.mvc.Controller;
import play.mvc.Result;
public class TemplateController extends Controller {
protected final ALogger log = Logger.of(getClass());
private ClassLoader classLoader;
protected String templatePackageName = "views.html."; //derived classes can change this by reassigning it in a constructor. MUST end in "."
public TemplateController(ClassLoader classLoader) {
this.classLoader = classLoader;
}
public TemplateController() {
}
protected Result ok(String template, Parameters params) {
return ok(render(template, params));
}
protected Result badRequest(String template, Parameters params) {
return badRequest(render(template, params));
}
protected Content render(String template, Parameters params) {
Content content;
try {
content = call(templatePackageName + template, "render", params);
} catch (ClassNotFoundException | MethodNotFoundException e) {
if (log.isDebugEnabled())
log.debug("template not found : '" + template + "'");
return templateNotFound(template, params);
}
return content;
}
protected Content templateNotFound(String template, Parameters params) {
StringBuilder sb = new StringBuilder("Template ");
sb.append(template).append("(");
Class<?>[] types = params.types();
for (int i = 0; i < types.length; i++) {
Class<?> type = types[i];
if (i != 0)
sb.append(", ");
sb.append(type.getSimpleName());
}
sb.append(") is not found");
return Html.apply(sb.toString());
}
protected <T> Parameters with() {
return new Parameters();
}
protected <T> Parameters with(Class<?> paramType, T paramValue) {
return new Parameters(paramType, paramValue);
}
@SuppressWarnings("unchecked")
protected <R> R call(String className, String methodName, Parameters params)
throws ClassNotFoundException, MethodNotFoundException {
if (log.isDebugEnabled())
log.debug("call <-");
if (log.isDebugEnabled())
log.debug("className : " + className);
if (log.isDebugEnabled())
log.debug("methodName : " + methodName);
if (log.isDebugEnabled())
log.debug("params : " + params);
ClassLoader cl = classLoader();
Object result = null;
Class<?> clazz = cl.loadClass(className);
if (log.isDebugEnabled())
log.debug("clazz : " + clazz);
Class<?>[] paramTypes = params.types();
Object[] paramValues = params.values();
Method method = ReflectionUtils.findMethod(clazz, methodName,
paramTypes);
if (log.isDebugEnabled())
log.debug("method : " + method);
if (method == null) {
throw new MethodNotFoundException(className, methodName, paramTypes);
}
result = ReflectionUtils.invokeMethod(method, null, paramValues);
return (R) result;
}
private ClassLoader classLoader() {
//create class loader if one does not exist
if (classLoader == null) {
classLoader = getClass().getClassLoader();
}
return classLoader;
}
public class MethodNotFoundException extends Exception {
private static final long serialVersionUID = 1L;
private String className;
private String methodName;
private Class<?>[] paramTypes;
public MethodNotFoundException(String className, String methodName,
Class<?>[] paramTypes) {
this.className = className;
this.methodName = methodName;
this.paramTypes = paramTypes;
}
public String toString() {
StringBuffer sb = new StringBuffer(className);
sb.append(".").append(methodName).append("(");
for (int i = 0; i < paramTypes.length; i++) {
Class<?> t = paramTypes[i];
sb.append(t.getSimpleName());
if (i < paramTypes.length - 1)
sb.append(", ");
}
sb.append(")");
return sb.toString();
}
}
}
| project-code/app/play/utils/crud/TemplateController.java | package play.utils.crud;
import java.lang.reflect.Method;
import org.springframework.util.ReflectionUtils;
import play.Logger;
import play.Logger.ALogger;
import play.twirl.api.Html;
import play.twirl.api.Content;
import play.mvc.Controller;
import play.mvc.Result;
public class TemplateController extends Controller {
protected final ALogger log = Logger.of(getClass());
private ClassLoader classLoader;
protected String templatePackageName = "views.html."; //derived classes can change this. MUST end in "."
public TemplateController(ClassLoader classLoader) {
this.classLoader = classLoader;
}
public TemplateController() {
}
protected Result ok(String template, Parameters params) {
return ok(render(template, params));
}
protected Result badRequest(String template, Parameters params) {
return badRequest(render(template, params));
}
protected Content render(String template, Parameters params) {
Content content;
try {
content = call(templatePackageName + template, "render", params);
} catch (ClassNotFoundException | MethodNotFoundException e) {
if (log.isDebugEnabled())
log.debug("template not found : '" + template + "'");
return templateNotFound(template, params);
}
return content;
}
protected Content templateNotFound(String template, Parameters params) {
StringBuilder sb = new StringBuilder("Template ");
sb.append(template).append("(");
Class<?>[] types = params.types();
for (int i = 0; i < types.length; i++) {
Class<?> type = types[i];
if (i != 0)
sb.append(", ");
sb.append(type.getSimpleName());
}
sb.append(") is not found");
return Html.apply(sb.toString());
}
protected <T> Parameters with() {
return new Parameters();
}
protected <T> Parameters with(Class<?> paramType, T paramValue) {
return new Parameters(paramType, paramValue);
}
@SuppressWarnings("unchecked")
protected <R> R call(String className, String methodName, Parameters params)
throws ClassNotFoundException, MethodNotFoundException {
if (log.isDebugEnabled())
log.debug("call <-");
if (log.isDebugEnabled())
log.debug("className : " + className);
if (log.isDebugEnabled())
log.debug("methodName : " + methodName);
if (log.isDebugEnabled())
log.debug("params : " + params);
ClassLoader cl = classLoader();
Object result = null;
Class<?> clazz = cl.loadClass(className);
if (log.isDebugEnabled())
log.debug("clazz : " + clazz);
Class<?>[] paramTypes = params.types();
Object[] paramValues = params.values();
Method method = ReflectionUtils.findMethod(clazz, methodName,
paramTypes);
if (log.isDebugEnabled())
log.debug("method : " + method);
if (method == null) {
throw new MethodNotFoundException(className, methodName, paramTypes);
}
result = ReflectionUtils.invokeMethod(method, null, paramValues);
return (R) result;
}
private ClassLoader classLoader() {
//create class loader if one does not exist
if (classLoader == null) {
classLoader = getClass().getClassLoader();
}
return classLoader;
}
public class MethodNotFoundException extends Exception {
private static final long serialVersionUID = 1L;
private String className;
private String methodName;
private Class<?>[] paramTypes;
public MethodNotFoundException(String className, String methodName,
Class<?>[] paramTypes) {
this.className = className;
this.methodName = methodName;
this.paramTypes = paramTypes;
}
public String toString() {
StringBuffer sb = new StringBuffer(className);
sb.append(".").append(methodName).append("(");
for (int i = 0; i < paramTypes.length; i++) {
Class<?> t = paramTypes[i];
sb.append(t.getSimpleName());
if (i < paramTypes.length - 1)
sb.append(", ");
}
sb.append(")");
return sb.toString();
}
}
}
| Update TemplateController.java
Clarify how the user can change templatePackageName in a derived class. It's worth considering making this field a private bean property with corresponding getters and setters to avoid confusion. | project-code/app/play/utils/crud/TemplateController.java | Update TemplateController.java | |
Java | mit | ab9cd125e11c208f2b4d16fef8fb462ca7aaa4ab | 0 | jericks/geoserver-shell,jericks/geoserver-shell | package org.geoserver.shell;
import it.geosolutions.geoserver.rest.GeoServerRESTPublisher;
import it.geosolutions.geoserver.rest.GeoServerRESTReader;
import it.geosolutions.geoserver.rest.HTTPUtils;
import it.geosolutions.geoserver.rest.decoder.RESTNamespace;
import it.geosolutions.geoserver.rest.decoder.RESTWorkspaceList;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import it.geosolutions.geoserver.rest.encoder.GSWorkspaceEncoder;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.shell.core.CommandMarker;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
import org.springframework.shell.support.util.OsUtils;
import org.springframework.stereotype.Component;
import java.io.StringReader;
import java.net.URI;
import java.util.List;
@Component
public class WorkspaceCommands implements CommandMarker {
@Autowired
private Geoserver geoserver;
@CliCommand(value = "workspace list", help = "List workspaces.")
public String list() throws Exception {
GeoServerRESTReader reader = new GeoServerRESTReader(geoserver.getUrl(), geoserver.getUser(), geoserver.getPassword());
List<String> names = reader.getWorkspaceNames();
StringBuilder builder = new StringBuilder();
for(String name : names) {
builder.append(name + OsUtils.LINE_SEPARATOR);
}
return builder.toString();
}
@CliCommand(value = "workspace create", help = "Create a workspace.")
public boolean create(
@CliOption(key = "name", mandatory = true, help = "The name") String name
) throws Exception {
GeoServerRESTPublisher publisher = new GeoServerRESTPublisher(geoserver.getUrl(), geoserver.getUser(), geoserver.getPassword());
return publisher.createWorkspace(name);
}
@CliCommand(value = "workspace get", help = "Get a workspace.")
public String get(
@CliOption(key = "name", mandatory = true, help = "The name") String name) throws Exception {
String url = geoserver.getUrl() + "/rest/workspaces/" + name + ".xml";
String xml = HTTPUtils.get(url, geoserver.getUser(), geoserver.getPassword());
Element workspaceElement = JDOMBuilder.buildElement(xml);
String nm = workspaceElement.getChildText("name");
return nm;
}
/*@CliCommand(value = "workspace modify", help = "Modify a workspace.")
public boolean modify(
@CliOption(key = {"", "name"}, mandatory = true, help = "The name") String name,
@CliOption(key = "newName", mandatory = true, help = "The new name") String newName
) throws Exception {
String url = geoserver.getUrl() + "/rest/workspaces/" + name + ".xml";
String xml = "<workspace><name>" + newName + "</name></workspace>";
String response = HTTPUtils.put(url,xml, GeoServerRESTPublisher.Format.XML.getContentType(), geoserver.getUser(), geoserver.getPassword());
return response != null;
}*/
@CliCommand(value = "workspace delete", help = "Delete a workspace.")
public boolean delete(
@CliOption(key = "name", mandatory = true, help = "The name") String name,
@CliOption(key = "recurse", mandatory = false, unspecifiedDefaultValue = "false", help = "Whether to delete recursively") boolean recurse) {
GeoServerRESTPublisher publisher = new GeoServerRESTPublisher(geoserver.getUrl(), geoserver.getUser(), geoserver.getPassword());
return publisher.removeWorkspace(name, recurse);
}
@CliCommand(value = "workspace default get", help = "Get the default workspace.")
public String getDefault() throws Exception {
String result = HTTPUtils.get(geoserver.getUrl() + "/rest/workspaces/default.xml", geoserver.getUser(), geoserver.getPassword());
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new StringReader(result));
Element elem = document.getRootElement();
RESTWorkspaceList.RESTShortWorkspace w = new RESTWorkspaceList.RESTShortWorkspace(elem);
return w.getName();
}
@CliCommand(value = "workspace default set", help = "Set the default workspace.")
public boolean setDefault(
@CliOption(key = "name", mandatory = true, help = "The name") String name) throws Exception {
GSWorkspaceEncoder encoder = new GSWorkspaceEncoder(name);
String content = encoder.toString();
String result = HTTPUtils.putXml(geoserver.getUrl() + "/rest/workspaces/default.xml", content, geoserver.getUser(), geoserver.getPassword());
return result != null;
}
}
| src/main/java/org/geoserver/shell/WorkspaceCommands.java | package org.geoserver.shell;
import it.geosolutions.geoserver.rest.GeoServerRESTPublisher;
import it.geosolutions.geoserver.rest.GeoServerRESTReader;
import it.geosolutions.geoserver.rest.HTTPUtils;
import it.geosolutions.geoserver.rest.decoder.RESTNamespace;
import it.geosolutions.geoserver.rest.decoder.RESTWorkspaceList;
import it.geosolutions.geoserver.rest.encoder.GSWorkspaceEncoder;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.shell.core.CommandMarker;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
import org.springframework.shell.support.util.OsUtils;
import org.springframework.stereotype.Component;
import java.io.StringReader;
import java.net.URI;
import java.util.List;
@Component
public class WorkspaceCommands implements CommandMarker {
@Autowired
private Geoserver geoserver;
@CliCommand(value = "workspace list", help = "List workspaces.")
public String list() throws Exception {
GeoServerRESTReader reader = new GeoServerRESTReader(geoserver.getUrl(), geoserver.getUser(), geoserver.getPassword());
List<String> names = reader.getWorkspaceNames();
StringBuilder builder = new StringBuilder();
for(String name : names) {
builder.append(name + OsUtils.LINE_SEPARATOR);
}
return builder.toString();
}
@CliCommand(value = "workspace create", help = "Create a workspace.")
public void create(
@CliOption(key = {"", "name"}, mandatory = true, help = "The name") String name,
@CliOption(key = {"uri"}, mandatory = true, help = "The uri") String uri) throws Exception {
GeoServerRESTPublisher publisher = new GeoServerRESTPublisher(geoserver.getUrl(), geoserver.getUser(), geoserver.getPassword());
publisher.createWorkspace(name, URI.create(uri));
}
@CliCommand(value = "workspace get", help = "Get a workspace.")
public String get(
@CliOption(key = {"", "name"}, mandatory = true, help = "The name") String name) throws Exception {
GeoServerRESTReader reader = new GeoServerRESTReader(geoserver.getUrl(), geoserver.getUser(), geoserver.getPassword());
RESTNamespace nm = reader.getNamespace(name);
return nm.getPrefix() + " " + nm.getURI();
}
@CliCommand(value = "workspace edit", help = "Edt a workspace.")
public boolean update(
@CliOption(key = {"", "name"}, mandatory = true, help = "The name") String name,
@CliOption(key = {"uri"}, mandatory = true, help = "The uri") String uri) throws Exception {
GeoServerRESTPublisher publisher = new GeoServerRESTPublisher(geoserver.getUrl(), geoserver.getUser(), geoserver.getPassword());
return publisher.updateNamespace(name, URI.create(uri));
}
@CliCommand(value = "workspace delete", help = "Delete a workspace.")
public boolean delete(
@CliOption(key = {"", "name"}, mandatory = true, help = "The name") String name,
@CliOption(key = {"recurse"}, mandatory = false, unspecifiedDefaultValue = "false", help = "Whether to delete recursively") boolean recurse) {
GeoServerRESTPublisher publisher = new GeoServerRESTPublisher(geoserver.getUrl(), geoserver.getUser(), geoserver.getPassword());
return publisher.removeWorkspace(name, recurse);
}
@CliCommand(value = "workspace getdefault", help = "Get the default workspace.")
public String getDefault() throws Exception {
String result = HTTPUtils.get(geoserver.getUrl() + "/rest/workspaces/default.xml", geoserver.getUser(), geoserver.getPassword());
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new StringReader(result));
Element elem = document.getRootElement();
RESTWorkspaceList.RESTShortWorkspace w = new RESTWorkspaceList.RESTShortWorkspace(elem);
return w.getName();
}
@CliCommand(value = "workspace setdefault", help = "Set the default workspace.")
public void setDefault(
@CliOption(key = {"", "name"}, mandatory = true, help = "The name") String name) throws Exception {
GSWorkspaceEncoder encoder = new GSWorkspaceEncoder(name);
String content = encoder.toString();
String result = HTTPUtils.putXml(geoserver.getUrl() + "/rest/workspaces/default.xml", content, geoserver.getUser(), geoserver.getPassword());
}
}
| Add workspace commands. | src/main/java/org/geoserver/shell/WorkspaceCommands.java | Add workspace commands. | |
Java | mit | 0b9d300f4a0c04e3679a6c7644571b6a8d08d5a0 | 0 | tjqadri101/oogasalad,dchouzer/OOGASalad | src/game_authoring_environment/TransferActionListener.java | package game_authoring_environment;
/*
* TransferActionListener.java is used by the 1.4
* DragPictureDemo.java example.
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
/*
* A class that tracks the focused component. This is necessary
* to delegate the menu cut/copy/paste commands to the right
* component. An instance of this class is listening and
* when the user fires one of these commands, it calls the
* appropriate action on the currently focused component.
*/
public class TransferActionListener implements ActionListener,
PropertyChangeListener {
private JComponent focusOwner = null;
public TransferActionListener() {
KeyboardFocusManager manager = KeyboardFocusManager.
getCurrentKeyboardFocusManager();
manager.addPropertyChangeListener("permanentFocusOwner", this);
}
public void propertyChange(PropertyChangeEvent e) {
Object o = e.getNewValue();
if (o instanceof JComponent) {
focusOwner = (JComponent)o;
} else {
focusOwner = null;
}
}
public void actionPerformed(ActionEvent e) {
if (focusOwner == null)
return;
String action = (String)e.getActionCommand();
Action a = focusOwner.getActionMap().get(action);
if (a != null) {
a.actionPerformed(new ActionEvent(focusOwner,
ActionEvent.ACTION_PERFORMED,
null));
}
}
}
| Deleted extraneous classes
| src/game_authoring_environment/TransferActionListener.java | Deleted extraneous classes | ||
Java | mit | fcc89d25c1553db0a26e42e0f528857ba5d4b26b | 0 | SpongePowered/SpongeGradle,SpongePowered/SpongeGradle | /*
* This file is part of spongegradle-plugin-development, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.gradle.plugin;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.gradle.testkit.runner.BuildResult;
import org.gradle.testkit.runner.TaskOutcome;
import org.gradle.testkit.runner.UnexpectedBuildFailure;
import org.gradle.testkit.runner.UnexpectedBuildSuccess;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import org.junit.jupiter.api.function.ThrowingConsumer;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.jar.JarFile;
import java.util.stream.Stream;
/**
* Simple functional tests for the Sponge plugin development plugin.
*
* <p>To capture errors from builds, it can be helpful to register exception
* breakpoints on {@link UnexpectedBuildFailure} and {@link UnexpectedBuildSuccess}.
* This allows viewing build reports before the temporary directories are cleared.</p>
*/
class SpongePluginPluginFunctionalTest {
void testSimpleBuild(final TestContext ctx) throws IOException {
ctx.copyInput("build.gradle.kts");
ctx.copyInput("settings.gradle.kts");
final BuildResult result = ctx.build("writePluginMetadata");
Assertions.assertTrue(result.getOutput().contains("SpongePowered Plugin"));
assertEquals(TaskOutcome.SUCCESS, result.task(":writePluginMetadata").getOutcome());
// Then make sure we actually generated a plugins file
ctx.assertOutputEquals("plugins.json", "build/generated/sponge/plugin/META-INF/plugins.json");
}
void testBuildFailsWhenMissingProperties(final TestContext ctx) throws IOException {
ctx.copyInput("build.gradle.kts");
ctx.copyInput("settings.gradle.kts");
final BuildResult result = ctx.runner("writePluginMetadata")
.buildAndFail();
assertEquals(TaskOutcome.FAILED, result.task(":writePluginMetadata").getOutcome());
assertTrue(
result.getOutput().contains("No value has been specified for property") // Gradle 6.x
|| result.getOutput().contains("doesn't have a configured value") // Gradle 7.x
);
assertTrue(result.getOutput().contains(".loader"));
assertTrue(result.getOutput().contains(".mainClass"));
}
void testPropertiesInferredFromProjectConfiguration(final TestContext ctx) throws IOException {
ctx.copyInput("build.gradle.kts");
ctx.copyInput("settings.gradle.kts");
final BuildResult result = ctx.build("writePluginMetadata");
assertEquals(TaskOutcome.SUCCESS, result.task(":writePluginMetadata").getOutcome());
final JsonObject plugins = new Gson().fromJson(ctx.readOutput("build/generated/sponge/plugin/META-INF/plugins.json"), JsonObject.class);
final JsonObject plugin = plugins.getAsJsonArray("plugins").get(0).getAsJsonObject();
// Compare properties drawn from build
assertEquals("1234", plugin.getAsJsonPrimitive("version").getAsString());
assertEquals(
"An example of properties coming from build configuration",
plugin.getAsJsonPrimitive("description").getAsString()
);
}
void testComplexBuild(final TestContext ctx) throws IOException {
ctx.copyInput("build.gradle.kts");
ctx.copyInput("settings.gradle.kts");
ctx.copyInput("Example.java", "src/main/java/org/spongepowered/example/Example.java");
final BuildResult result = ctx.build("build");
assertEquals(TaskOutcome.SUCCESS, result.task(":writePluginMetadata").getOutcome());
// Test that plugin metadata was included in the jar
final Path jar = ctx.outputDirectory().resolve("build/libs/complexbuild-1.0-SNAPSHOT.jar");
try (final JarFile jf = new JarFile(jar.toFile())) {
assertNotNull(jf.getEntry("META-INF/plugins.json"));
}
}
// the test framework itself (still fairly basic)
@TestFactory
Stream<DynamicTest> functionalTests(@TempDir final Path runDirectory) {
if (System.getenv("CI") != null && ManagementFactory.getOperatingSystemMXBean().getName().toLowerCase(Locale.ROOT).contains("windows")) {
// these tests fail on CI on windows for some reason related to cleaning up the temporary directory at the end of the run
return Stream.of();
}
// Common arguments for Gradle
final List<String> commonArgs = Arrays.asList("--warning-mode", "fail", "--stacktrace");
// Test variants
final String[][] variants = {
{"6.8.3", ""},
{"7.0", ""},
{"6.8.3", "--configuration-cache"},
{"7.0", "--configuration-cache"},
};
// The actual tests to execute
return Stream.of(
new Pair("simplebuild", this::testSimpleBuild),
new Pair("missingproperties", this::testBuildFailsWhenMissingProperties),
new Pair("propertiesinferred", this::testPropertiesInferredFromProjectConfiguration),
new Pair("complexbuild", this::testComplexBuild)
).flatMap(test -> Arrays.stream(variants)
.map(variant -> {
final List<String> extraArgs = SpongePluginPluginFunctionalTest.processArgs(commonArgs, variant[1]);
final Path tempDirectory;
try {
tempDirectory = Files.createTempDirectory(runDirectory, test.name + System.nanoTime());
} catch (final IOException e) {
throw new RuntimeException(e);
}
final TestContext context = new TestContext(
this.getClass(),
test.name,
tempDirectory,
variant[0],
extraArgs
);
return DynamicTest.dynamicTest(test.name + " (gradle " + variant[0] + ", args=" + extraArgs + ")", () -> test.method.accept(context));
}));
}
private static List<String> processArgs(final List<String> common, final String extra) {
final List<String> ret = new ArrayList<>(common);
if (!extra.isEmpty()) {
Collections.addAll(ret, extra.split(" ", -1));
}
return ret;
}
static class Pair {
final String name;
final ThrowingConsumer<TestContext> method;
public Pair(final String name, final ThrowingConsumer<TestContext> method) {
this.name = name;
this.method = method;
}
}
}
| plugin-development/src/functionalTest/java/org/spongepowered/gradle/plugin/SpongePluginPluginFunctionalTest.java | /*
* This file is part of spongegradle-plugin-development, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.gradle.plugin;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.gradle.testkit.runner.BuildResult;
import org.gradle.testkit.runner.TaskOutcome;
import org.gradle.testkit.runner.UnexpectedBuildFailure;
import org.gradle.testkit.runner.UnexpectedBuildSuccess;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import org.junit.jupiter.api.function.ThrowingConsumer;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.jar.JarFile;
import java.util.stream.Stream;
/**
* Simple functional tests for the Sponge plugin development plugin.
*
* <p>To capture errors from builds, it can be helpful to register exception
* breakpoints on {@link UnexpectedBuildFailure} and {@link UnexpectedBuildSuccess}.
* This allows viewing build reports before the temporary directories are cleared.</p>
*/
class SpongePluginPluginFunctionalTest {
void testSimpleBuild(final TestContext ctx) throws IOException {
ctx.copyInput("build.gradle.kts");
ctx.copyInput("settings.gradle.kts");
final BuildResult result = ctx.build("writePluginMetadata");
Assertions.assertTrue(result.getOutput().contains("SpongePowered Plugin"));
assertEquals(TaskOutcome.SUCCESS, result.task(":writePluginMetadata").getOutcome());
// Then make sure we actually generated a plugins file
ctx.assertOutputEquals("plugins.json", "build/generated/sponge/plugin/META-INF/plugins.json");
}
void testBuildFailsWhenMissingProperties(final TestContext ctx) throws IOException {
ctx.copyInput("build.gradle.kts");
ctx.copyInput("settings.gradle.kts");
final BuildResult result = ctx.runner("writePluginMetadata")
.buildAndFail();
assertEquals(TaskOutcome.FAILED, result.task(":writePluginMetadata").getOutcome());
assertTrue(
result.getOutput().contains("No value has been specified for property") // Gradle 6.x
|| result.getOutput().contains("doesn't have a configured value") // Gradle 7.x
);
assertTrue(result.getOutput().contains(".loader"));
assertTrue(result.getOutput().contains(".mainClass"));
}
void testPropertiesInferredFromProjectConfiguration(final TestContext ctx) throws IOException {
ctx.copyInput("build.gradle.kts");
ctx.copyInput("settings.gradle.kts");
final BuildResult result = ctx.build("writePluginMetadata");
assertEquals(TaskOutcome.SUCCESS, result.task(":writePluginMetadata").getOutcome());
final JsonObject plugins = new Gson().fromJson(ctx.readOutput("build/generated/sponge/plugin/META-INF/plugins.json"), JsonObject.class);
final JsonObject plugin = plugins.getAsJsonArray("plugins").get(0).getAsJsonObject();
// Compare properties drawn from build
assertEquals("1234", plugin.getAsJsonPrimitive("version").getAsString());
assertEquals(
"An example of properties coming from build configuration",
plugin.getAsJsonPrimitive("description").getAsString()
);
}
void testComplexBuild(final TestContext ctx) throws IOException {
ctx.copyInput("build.gradle.kts");
ctx.copyInput("settings.gradle.kts");
ctx.copyInput("Example.java", "src/main/java/org/spongepowered/example/Example.java");
final BuildResult result = ctx.build("build");
assertEquals(TaskOutcome.SUCCESS, result.task(":writePluginMetadata").getOutcome());
// Test that plugin metadata was included in the jar
final Path jar = ctx.outputDirectory().resolve("build/libs/complexbuild-1.0-SNAPSHOT.jar");
try (final JarFile jf = new JarFile(jar.toFile())) {
assertNotNull(jf.getEntry("META-INF/plugins.json"));
}
}
// the test framework itself (still fairly basic)
@TestFactory
Stream<DynamicTest> functionalTests(@TempDir final Path runDirectory) {
// Common arguments for Gradle
final List<String> commonArgs = Arrays.asList("--warning-mode", "fail", "--stacktrace");
// Test variants
final String[][] variants = {
{"6.8.3", ""},
{"7.0", ""},
{"6.8.3", "--configuration-cache"},
{"7.0", "--configuration-cache"},
};
// The actual tests to execute
return Stream.of(
new Pair("simplebuild", this::testSimpleBuild),
new Pair("missingproperties", this::testBuildFailsWhenMissingProperties),
new Pair("propertiesinferred", this::testPropertiesInferredFromProjectConfiguration),
new Pair("complexbuild", this::testComplexBuild)
).flatMap(test -> Arrays.stream(variants)
.map(variant -> {
final List<String> extraArgs = SpongePluginPluginFunctionalTest.processArgs(commonArgs, variant[1]);
final Path tempDirectory;
try {
tempDirectory = Files.createTempDirectory(runDirectory, test.name + System.nanoTime());
} catch (final IOException e) {
throw new RuntimeException(e);
}
final TestContext context = new TestContext(
this.getClass(),
test.name,
tempDirectory,
variant[0],
extraArgs
);
return DynamicTest.dynamicTest(test.name + " (gradle " + variant[0] + ", args=" + extraArgs + ")", () -> {
try {
test.method.accept(context);
} finally {
// force-delete... thanks windows
for (int i = 0; i < 3; i++) {
try {
Files.walkFileTree(tempDirectory, new FileVisitor<Path>() {
@Override public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) { return FileVisitResult.CONTINUE; }
@Override public FileVisitResult visitFileFailed(final Path file, final IOException exc) { return FileVisitResult.CONTINUE; }
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
break; // if successful
} catch (final IOException ex) { // then try again
Thread.sleep(500 * (i + 1)); // hope the locks go bye
}
}
}
});
}));
}
private static List<String> processArgs(final List<String> common, final String extra) {
final List<String> ret = new ArrayList<>(common);
if (!extra.isEmpty()) {
Collections.addAll(ret, extra.split(" ", -1));
}
return ret;
}
static class Pair {
final String name;
final ThrowingConsumer<TestContext> method;
public Pair(final String name, final ThrowingConsumer<TestContext> method) {
this.name = name;
this.method = method;
}
}
}
| plugin-development: i give up
| plugin-development/src/functionalTest/java/org/spongepowered/gradle/plugin/SpongePluginPluginFunctionalTest.java | plugin-development: i give up | |
Java | agpl-3.0 | 7605e65309f4dd02c3bd98176e5b6df7e06af820 | 0 | geomajas/geomajas-project-server,geomajas/geomajas-project-server,geomajas/geomajas-project-client-gwt,geomajas/geomajas-project-client-gwt,geomajas/geomajas-project-client-gwt2,geomajas/geomajas-project-client-gwt2,geomajas/geomajas-project-server,geomajas/geomajas-project-client-gwt | /*
* This file is part of Geomajas, a component framework for building
* rich Internet applications (RIA) with sophisticated capabilities for the
* display, analysis and management of geographic information.
* It is a building block that allows developers to add maps
* and other geographic data capabilities to their web applications.
*
* Copyright 2008-2010 Geosparc, http://www.geosparc.com, Belgium
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.geomajas.gwt.client.map;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.geomajas.geometry.Coordinate;
import org.geomajas.global.Api;
import org.geomajas.gwt.client.map.event.MapViewChangedEvent;
import org.geomajas.gwt.client.map.event.MapViewChangedHandler;
import org.geomajas.gwt.client.spatial.Bbox;
import org.geomajas.gwt.client.spatial.Matrix;
import org.geomajas.gwt.client.spatial.WorldViewTransformer;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.event.shared.HandlerRegistration;
/**
* <p>
* This class represents the viewing controller behind a <code>MapWidget</code>. It knows the map's width, height, but
* it also controls what is visible on the map through a <code>Camera</code> object. This camera hangs over the map at a
* certain height (represented by the scale), and together with the width and height, this MapView can determine the
* boundaries of the visible area on the map.
* </p>
* <p>
* But it's more then that. This MapView can also calculate necessary transformation matrices to go from world to view
* space an back. It can also snap the scale-levels to fixed resolutions (in case these are actually defined).
* </p>
*
* @author Pieter De Graef
* @since 1.6.0
*/
@Api
public class MapView {
/** Zoom options. */
public enum ZoomOption {
/** Zoom exactly to the new scale. */
EXACT,
/**
* Zoom to a scale level that is different from the current (lower or higher according to the new scale, only
* if allowed of course).
*/
LEVEL_CHANGE,
/** Zoom to a scale level that is as close as possible to the new scale. */
LEVEL_CLOSEST,
/** Zoom to a scale level that makes the bounds fit inside our view. */
LEVEL_FIT
}
/** The map's width in pixels. */
private int width;
/** The map's height in pixels. */
private int height;
/** The current scale : how many pixels are there in 1 map unit ? */
private double currentScale = 1.0;
/**
* The center of the map. The viewing frustum is determined by this camera object in combination with the map's
* width and height.
*/
private Camera camera;
/** The center of the map. */
private Coordinate panOrigin = new Coordinate(0, 0);
/** A maximum scale level, that this MapView is not allowed to cross. */
private double maximumScale = 10;
/** The maximum bounding box available to this MapView. Never go outside it! */
private Bbox maxBounds;
/**
* A series of scale levels to which zooming in and out should snap. This is optional! If you which to use these
* fixed zooming steps, all you have to do, is define them.
*/
private List<Double> resolutions = new ArrayList<Double>();
/** The current index in the resolutions array. That is, if the resolutions are actually used. */
private int resolutionIndex = -1;
private double previousScale;
private Coordinate previousPanOrigin = new Coordinate(0, 0);
private HandlerManager handlerManager;
private WorldViewTransformer worldViewTransformer;
private boolean panDragging;
// -------------------------------------------------------------------------
// Constructors:
// -------------------------------------------------------------------------
/** Default constructor that initializes all it's fields. */
public MapView() {
camera = new Camera();
handlerManager = new HandlerManager(this);
}
/**
* Adds this handler to the view.
*
* @param handler
* the handler
* @return {@link com.google.gwt.event.shared.HandlerRegistration} used to remove the handler
*/
public final HandlerRegistration addMapViewChangedHandler(final MapViewChangedHandler handler) {
return handlerManager.addHandler(MapViewChangedEvent.getType(), handler);
}
// -------------------------------------------------------------------------
// Retrieval of transformation matrices:
// -------------------------------------------------------------------------
/** Return the world-to-view space transformation matrix. */
public Matrix getWorldToViewTransformation() {
if (currentScale > 0) {
double dX = -(camera.getX() * currentScale) + width / 2;
double dY = camera.getY() * currentScale + height / 2;
return new Matrix(currentScale, 0, 0, -this.currentScale, dX, dY);
}
return new Matrix(1, 0, 0, 1, 0, 0);
}
/** Return the world-to-view space translation matrix. */
public Matrix getWorldToViewTranslation() {
if (currentScale > 0) {
double dX = -(camera.getX() * currentScale) + width / 2;
double dY = camera.getY() * currentScale + height / 2;
return new Matrix(1, 0, 0, 1, dX, dY);
}
return new Matrix(1, 0, 0, 1, 0, 0);
}
/** Return the world-to-pan space translation matrix. */
public Matrix getWorldToPanTransformation() {
if (currentScale > 0) {
double dX = -(panOrigin.getX() * currentScale);
double dY = panOrigin.getY() * currentScale;
return new Matrix(currentScale, 0, 0, -this.currentScale, dX, dY);
}
return new Matrix(1, 0, 0, 1, 0, 0);
}
/** Return the translation of coordinates relative to the pan origin to view coordinates. */
public Matrix getPanToViewTranslation() {
if (currentScale > 0) {
double dX = -((camera.getX() - panOrigin.getX()) * currentScale) + width / 2;
double dY = (camera.getY() - panOrigin.getY()) * currentScale + height / 2;
return new Matrix(1, 0, 0, 1, dX, dY);
}
return new Matrix(1, 0, 0, 1, 0, 0);
}
/** Return the translation of scaled world coordinates to coordinates relative to the pan origin. */
public Matrix getWorldToPanTranslation() {
if (currentScale > 0) {
double dX = -(panOrigin.getX() * currentScale);
double dY = panOrigin.getY() * currentScale;
return new Matrix(1, 0, 0, 1, dX, dY);
}
return new Matrix(1, 0, 0, 1, 0, 0);
}
/** Return the world-to-view space translation matrix. */
public Matrix getWorldToViewScaling() {
if (currentScale > 0) {
return new Matrix(currentScale, 0, 0, -currentScale, 0, 0);
}
return new Matrix(1, 0, 0, 1, 0, 0);
}
// -------------------------------------------------------------------------
// Functions that manipulate or retrieve what is visible on the map:
// -------------------------------------------------------------------------
/**
* Re-centers the map to a new position.
*
* @param coordinate
* the new center position
*/
public void setCenterPosition(Coordinate coordinate) {
pushPanData();
doSetPosition(coordinate);
fireEvent(false, null);
}
/**
* Apply a new scale level on the map. In case the are fixed resolutions defined on this MapView, it will
* automatically snap to the nearest resolution. In case the maximum extents are exceeded, it will pan to avoid
* this.
*
* @param newScale
* The preferred new scale.
* @param option
* zoom option, {@link org.geomajas.gwt.client.map.MapView.ZoomOption}
*/
public void setCurrentScale(final double newScale, final ZoomOption option) {
pushPanData();
// calculate theoretical new bounds
Coordinate center = camera.getPosition();
Bbox newBbox = new Bbox(0, 0, getWidth() / newScale, getHeight() / newScale);
newBbox.setCenterPoint(center);
// and apply...
doApplyBounds(newBbox, option);
}
/**
* <p>
* Change the view on the map by applying a bounding box (world coordinates!). Since the width/height ratio of the
* bounding box may differ from that of the map, the fit is "as good as possible".
* </p>
* <p>
* Also this function will almost certainly change the scale on the map, so if there have been resolutions defined,
* it will snap to them.
* </p>
*
* @param bounds
* A bounding box in world coordinates that determines the view from now on.
* @param option
* zoom option, {@link org.geomajas.gwt.client.map.MapView.ZoomOption}
*/
public void applyBounds(final Bbox bounds, final ZoomOption option) {
pushPanData();
doApplyBounds(bounds, option);
}
/**
* Set the size of the map in pixels.
*
* @param newWidth
* The map's width.
* @param newHeight
* The map's height.
*/
public void setSize(int newWidth, int newHeight) {
pushPanData();
Bbox oldbbox = getBounds();
this.width = newWidth;
this.height = newHeight;
// reapply the old bounds
doApplyBounds(oldbbox, ZoomOption.LEVEL_FIT);
}
/**
* Move the view on the map. This happens by translating the camera in turn.
*
* @param x
* Translation factor along the X-axis in world space.
* @param y
* Translation factor along the Y-axis in world space.
*/
public void translate(double x, double y) {
pushPanData();
Coordinate c = camera.getPosition();
doSetPosition(new Coordinate(c.getX() + x, c.getY() + y));
fireEvent(false, null);
}
/**
* Adjust the current scale on the map by a new factor.
*
* @param delta
* Adjust the scale by factor "delta".
*/
public void scale(double delta, ZoomOption option) {
setCurrentScale(currentScale * delta, option);
}
//-------------------------------------------------------------------------
// Getters:
//-------------------------------------------------------------------------
/** Return the current scale. */
public double getCurrentScale() {
return currentScale;
}
/**
* Given the information in this MapView object, what is the currently visible area?
*
* @return Notice that at this moment an Axis Aligned Bounding Box is returned! This means that rotating is not yet
* possible.
*/
public Bbox getBounds() {
double w = getViewSpaceWidth();
double h = getViewSpaceHeight();
double x = camera.getX() - w / 2;
double y = camera.getY() - h / 2;
return new Bbox(x, y, w, h);
}
/**
* Set the list of predefined map resolutions (resolution = inverse of scale).
*
* @param resolutions
* the list of predefined resolutions (expressed in map unit/pixel)
*/
public void setResolutions(List<Double> resolutions) {
this.resolutions.clear();
this.resolutions.addAll(resolutions);
Collections.sort(this.resolutions, Collections.reverseOrder());
}
/** Get the list of predefined map resolutions (resolution = inverse of scale). */
public List<Double> getResolutions() {
return resolutions;
}
/**
* are we panning ?
*
* @return true if panning
*/
public boolean isSameScaleLevel() {
return Math.abs(currentScale - previousScale) < 1.0E-10
&& previousPanOrigin.equalsDelta(this.panOrigin, 1.0E-10);
}
/** Return the internal camera that is used to represent the map's point of view. */
public Camera getCamera() {
return camera;
}
/** Return the transformer that is used to transform coordinate and geometries between world and screen space. */
public WorldViewTransformer getWorldViewTransformer() {
if (null == worldViewTransformer) {
worldViewTransformer = new WorldViewTransformer(this);
}
return worldViewTransformer;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public Coordinate getPanOrigin() {
return panOrigin;
}
public void setMaximumScale(double maximumScale) {
if (maximumScale > 0) {
this.maximumScale = maximumScale;
}
}
public Bbox getMaxBounds() {
return maxBounds;
}
public void setMaxBounds(Bbox maxBounds) {
this.maxBounds = maxBounds;
}
public boolean isPanDragging() {
return panDragging;
}
public void setPanDragging(boolean panDragging) {
this.panDragging = panDragging;
}
public String toString() {
return "VIEW: scale=" + this.currentScale + ", " + this.camera.toString();
}
// -------------------------------------------------------------------------
// Private functions:
// -------------------------------------------------------------------------
private boolean doSetScale(double scale, ZoomOption option) {
boolean res = Math.abs(currentScale - scale) > .0000001;
currentScale = scale;
return res;
}
private void doSetPosition(Coordinate coordinate) {
Coordinate center = calcCenterFromPoint(coordinate);
camera.setPosition(center);
}
private void doApplyBounds(Bbox bounds, ZoomOption option) {
if (bounds != null) {
boolean scaleChanged = false;
if (!bounds.isEmpty()) {
// find best scale
double scale = getBestScale(bounds);
// snap and limit
scale = snapToResolution(scale, option);
// set scale
scaleChanged = doSetScale(scale, option);
}
doSetPosition(bounds.getCenterPoint());
if (bounds.isEmpty()) {
fireEvent(false, null);
} else {
// set pan origin equal to camera
panOrigin.setX(camera.getX());
panOrigin.setY(camera.getY());
fireEvent(scaleChanged, option);
}
}
}
private double getMinimumScale() {
if (maxBounds != null) {
double wRatio = width / maxBounds.getWidth();
double hRatio = height / maxBounds.getHeight();
// return the maximum to fit outside
return wRatio > hRatio ? wRatio : hRatio;
} else {
return Double.MIN_VALUE;
}
}
private double getBestScale(Bbox bounds) {
double wRatio;
double boundsWidth = bounds.getWidth();
if (boundsWidth <= 0) {
wRatio = getMinimumScale();
} else {
wRatio = width / boundsWidth;
}
double hRatio;
double boundsHeight = bounds.getHeight();
if (boundsHeight <= 0) {
hRatio = getMinimumScale();
} else {
hRatio = height / boundsHeight;
}
// return the minimum to fit inside
return wRatio < hRatio ? wRatio : hRatio;
}
private double limitScale(double scale) {
double minimumScale = getMinimumScale();
if (scale < minimumScale) {
return minimumScale;
} else if (scale > maximumScale) {
return maximumScale;
} else {
return scale;
}
}
private IndexRange getResolutionRange() {
IndexRange range = new IndexRange();
double max = 1.0 / getMinimumScale();
double min = 1.0 / maximumScale;
for (int i = 0; i < resolutions.size(); i++) {
Double resolution = resolutions.get(i);
if (resolution >= min && resolution <= max) {
range.setMin(i);
range.setMax(i);
}
}
return range;
}
private double getViewSpaceWidth() {
return width / currentScale;
}
private double getViewSpaceHeight() {
return height / currentScale;
}
private void pushPanData() {
previousScale = currentScale;
previousPanOrigin = (Coordinate) panOrigin.clone();
}
/** Fire an event. */
private void fireEvent(boolean resized, ZoomOption option) {
handlerManager.fireEvent(new MapViewChangedEvent(getBounds(), getCurrentScale(), isSameScaleLevel(),
panDragging, resized, option));
}
/**
* Finds an optimal scale by snapping to resolutions.
*
* @param scale scale which needs to be snapped
* @param option snapping option
* @return snapped scale
*/
private double snapToResolution(double scale, ZoomOption option) {
// clip upper bounds
double allowedScale = limitScale(scale);
if (resolutions != null) {
IndexRange indexes = getResolutionRange();
if (option == ZoomOption.EXACT || !indexes.isValid()) {
// should not or cannot snap to resolutions
return allowedScale;
} else {
// find the new index
int newResolutionIndex = 0;
double screenResolution = 1.0 / allowedScale;
if (screenResolution >= resolutions.get(indexes.getMin())) {
newResolutionIndex = indexes.getMin();
} else if (screenResolution <= resolutions.get(indexes.getMax())) {
newResolutionIndex = indexes.getMax();
} else {
for (int i = indexes.getMin(); i < indexes.getMax(); i++) {
double upper = resolutions.get(i);
double lower = resolutions.get(i + 1);
if (screenResolution <= upper && screenResolution >= lower) {
if (option == ZoomOption.LEVEL_FIT) {
newResolutionIndex = i;
break;
} else {
if ((upper / screenResolution) > (screenResolution / lower)) {
newResolutionIndex = i + 1;
break;
} else {
newResolutionIndex = i;
break;
}
}
}
}
}
// check if we need to change level
if (newResolutionIndex == resolutionIndex && option == ZoomOption.LEVEL_CHANGE) {
if (scale > currentScale && newResolutionIndex < indexes.getMax()) {
newResolutionIndex++;
} else if (scale < currentScale && newResolutionIndex > indexes.getMin()) {
newResolutionIndex--;
}
}
resolutionIndex = newResolutionIndex;
return 1.0 / resolutions.get(resolutionIndex);
}
} else {
return scale;
}
}
/**
* Adjusts the center point of the map, to an allowed center point. This method tries to make sure the whole map
* extent is inside the maximum allowed bounds.
*
* @param worldCenter
* @return
*/
private Coordinate calcCenterFromPoint(final Coordinate worldCenter) {
double xCenter = worldCenter.getX();
double yCenter = worldCenter.getY();
if (maxBounds != null) {
double w = getViewSpaceWidth() / 2;
double h = getViewSpaceHeight() / 2;
Coordinate minCoordinate = maxBounds.getOrigin();
Coordinate maxCoordinate = maxBounds.getEndPoint();
if ((w * 2) > maxBounds.getWidth()) {
xCenter = maxBounds.getCenterPoint().getX();
} else {
if ((xCenter - w) < minCoordinate.getX()) {
xCenter = minCoordinate.getX() + w;
}
if ((xCenter + w) > maxCoordinate.getX()) {
xCenter = maxCoordinate.getX() - w;
}
}
if ((h * 2) > maxBounds.getHeight()) {
yCenter = maxBounds.getCenterPoint().getY();
} else {
if ((yCenter - h) < minCoordinate.getY()) {
yCenter = minCoordinate.getY() + h;
}
if ((yCenter + h) > maxCoordinate.getY()) {
yCenter = maxCoordinate.getY() - h;
}
}
}
return new Coordinate(xCenter, yCenter);
}
/**
* A range of indexes.
*/
private class IndexRange {
private Integer min;
private Integer max;
public int getMax() {
return max;
}
public void setMax(int max) {
if (this.max == null || max > this.max) {
this.max = max;
}
}
public int getMin() {
return min;
}
public void setMin(int min) {
if (this.min == null || min < this.min) {
this.min = min;
}
}
public boolean isValid() {
return min != null && max != null && min <= max;
}
}
}
| face/geomajas-face-gwt/geomajas-gwt-client/src/main/java/org/geomajas/gwt/client/map/MapView.java | /*
* This file is part of Geomajas, a component framework for building
* rich Internet applications (RIA) with sophisticated capabilities for the
* display, analysis and management of geographic information.
* It is a building block that allows developers to add maps
* and other geographic data capabilities to their web applications.
*
* Copyright 2008-2010 Geosparc, http://www.geosparc.com, Belgium
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.geomajas.gwt.client.map;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.geomajas.geometry.Coordinate;
import org.geomajas.global.Api;
import org.geomajas.gwt.client.map.event.MapViewChangedEvent;
import org.geomajas.gwt.client.map.event.MapViewChangedHandler;
import org.geomajas.gwt.client.spatial.Bbox;
import org.geomajas.gwt.client.spatial.Matrix;
import org.geomajas.gwt.client.spatial.WorldViewTransformer;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.event.shared.HandlerRegistration;
/**
* <p>
* This class represents the viewing controller behind a <code>MapWidget</code>. It knows the map's width, height, but
* it also controls what is visible on the map through a <code>Camera</code> object. This camera hangs over the map at a
* certain height (represented by the scale), and together with the width and height, this MapView can determine the
* boundaries of the visible area on the map.
* </p>
* <p>
* But it's more then that. This MapView can also calculate necessary transformation matrices to go from world to view
* space an back. It can also snap the scale-levels to fixed resolutions (in case these are actually defined).
* </p>
*
* @author Pieter De Graef
* @since 1.6.0
*/
@Api
public class MapView {
/** Zoom options. */
public enum ZoomOption {
/** Zoom exactly to the new scale. */
EXACT,
/**
* Zoom to a scale level that is different from the current (lower or higher according to the new scale, only
* if allowed of course).
*/
LEVEL_CHANGE,
/** Zoom to a scale level that is as close as possible to the new scale. */
LEVEL_CLOSEST,
/** Zoom to a scale level that makes the bounds fit inside our view. */
LEVEL_FIT
}
/** The map's width in pixels. */
private int width;
/** The map's height in pixels. */
private int height;
/** The current scale : how many pixels are there in 1 map unit ? */
private double currentScale = 1.0;
/**
* The center of the map. The viewing frustum is determined by this camera object in combination with the map's
* width and height.
*/
private Camera camera;
/** The center of the map. */
private Coordinate panOrigin = new Coordinate(0, 0);
/** A maximum scale level, that this MapView is not allowed to cross. */
private double maximumScale = 10;
/** The maximum bounding box available to this MapView. Never go outside it! */
private Bbox maxBounds;
/**
* A series of scale levels to which zooming in and out should snap. This is optional! If you which to use these
* fixed zooming steps, all you have to do, is define them.
*/
private List<Double> resolutions = new ArrayList<Double>();
/** The current index in the resolutions array. That is, if the resolutions are actually used. */
private int resolutionIndex = -1;
private double previousScale;
private Coordinate previousPanOrigin = new Coordinate(0, 0);
private HandlerManager handlerManager;
private WorldViewTransformer worldViewTransformer;
private boolean panDragging;
// -------------------------------------------------------------------------
// Constructors:
// -------------------------------------------------------------------------
/** Default constructor that initializes all it's fields. */
public MapView() {
camera = new Camera();
handlerManager = new HandlerManager(this);
}
/**
* Adds this handler to the view.
*
* @param handler
* the handler
* @return {@link com.google.gwt.event.shared.HandlerRegistration} used to remove the handler
*/
public final HandlerRegistration addMapViewChangedHandler(final MapViewChangedHandler handler) {
return handlerManager.addHandler(MapViewChangedEvent.getType(), handler);
}
// -------------------------------------------------------------------------
// Retrieval of transformation matrices:
// -------------------------------------------------------------------------
/** Return the world-to-view space transformation matrix. */
public Matrix getWorldToViewTransformation() {
if (currentScale > 0) {
double dX = -(camera.getX() * currentScale) + width / 2;
double dY = camera.getY() * currentScale + height / 2;
return new Matrix(currentScale, 0, 0, -this.currentScale, dX, dY);
}
return new Matrix(1, 0, 0, 1, 0, 0);
}
/** Return the world-to-view space translation matrix. */
public Matrix getWorldToViewTranslation() {
if (currentScale > 0) {
double dX = -(camera.getX() * currentScale) + width / 2;
double dY = camera.getY() * currentScale + height / 2;
return new Matrix(1, 0, 0, 1, dX, dY);
}
return new Matrix(1, 0, 0, 1, 0, 0);
}
/** Return the world-to-pan space translation matrix. */
public Matrix getWorldToPanTransformation() {
if (currentScale > 0) {
double dX = -(panOrigin.getX() * currentScale);
double dY = panOrigin.getY() * currentScale;
return new Matrix(currentScale, 0, 0, -this.currentScale, dX, dY);
}
return new Matrix(1, 0, 0, 1, 0, 0);
}
/** Return the translation of coordinates relative to the pan origin to view coordinates. */
public Matrix getPanToViewTranslation() {
if (currentScale > 0) {
double dX = -((camera.getX() - panOrigin.getX()) * currentScale) + width / 2;
double dY = (camera.getY() - panOrigin.getY()) * currentScale + height / 2;
return new Matrix(1, 0, 0, 1, dX, dY);
}
return new Matrix(1, 0, 0, 1, 0, 0);
}
/** Return the translation of scaled world coordinates to coordinates relative to the pan origin. */
public Matrix getWorldToPanTranslation() {
if (currentScale > 0) {
double dX = -(panOrigin.getX() * currentScale);
double dY = panOrigin.getY() * currentScale;
return new Matrix(1, 0, 0, 1, dX, dY);
}
return new Matrix(1, 0, 0, 1, 0, 0);
}
/** Return the world-to-view space translation matrix. */
public Matrix getWorldToViewScaling() {
if (currentScale > 0) {
return new Matrix(currentScale, 0, 0, -currentScale, 0, 0);
}
return new Matrix(1, 0, 0, 1, 0, 0);
}
// -------------------------------------------------------------------------
// Functions that manipulate or retrieve what is visible on the map:
// -------------------------------------------------------------------------
/**
* Re-centers the map to a new position.
*
* @param coordinate
* the new center position
*/
public void setCenterPosition(Coordinate coordinate) {
pushPanData();
doSetPosition(coordinate);
fireEvent(false, null);
}
/**
* Apply a new scale level on the map. In case the are fixed resolutions defined on this MapView, it will
* automatically snap to the nearest resolution. In case the maximum extents are exceeded, it will pan to avoid
* this.
*
* @param newScale
* The preferred new scale.
* @param option
* zoom option, {@link org.geomajas.gwt.client.map.MapView.ZoomOption}
*/
public void setCurrentScale(final double newScale, final ZoomOption option) {
pushPanData();
// calculate theoretical new bounds
Coordinate center = camera.getPosition();
Bbox newBbox = new Bbox(0, 0, getWidth() / newScale, getHeight() / newScale);
newBbox.setCenterPoint(center);
// and apply...
doApplyBounds(newBbox, option);
// set pan origin equal to camera
panOrigin.setX(camera.getX());
panOrigin.setY(camera.getY());
fireEvent(false, option);
}
/**
* <p>
* Change the view on the map by applying a bounding box (world coordinates!). Since the width/height ratio of the
* bounding box may differ from that of the map, the fit is "as good as possible".
* </p>
* <p>
* Also this function will almost certainly change the scale on the map, so if there have been resolutions defined,
* it will snap to them.
* </p>
*
* @param bounds
* A bounding box in world coordinates that determines the view from now on.
* @param option
* zoom option, {@link org.geomajas.gwt.client.map.MapView.ZoomOption}
*/
public void applyBounds(final Bbox bounds, final ZoomOption option) {
pushPanData();
doApplyBounds(bounds, option);
// set pan origin equal to camera
panOrigin.setX(camera.getX());
panOrigin.setY(camera.getY());
fireEvent(true, option);
}
/**
* Set the size of the map in pixels.
*
* @param newWidth
* The map's width.
* @param newHeight
* The map's height.
*/
public void setSize(int newWidth, int newHeight) {
pushPanData();
Bbox oldbbox = getBounds();
this.width = newWidth;
this.height = newHeight;
// reapply the old bounds
doApplyBounds(oldbbox, ZoomOption.LEVEL_FIT);
// set pan origin equal to camera
panOrigin.setX(camera.getX());
panOrigin.setY(camera.getY());
fireEvent(true, ZoomOption.LEVEL_FIT);
}
/**
* Move the view on the map. This happens by translating the camera in turn.
*
* @param x
* Translation factor along the X-axis in world space.
* @param y
* Translation factor along the Y-axis in world space.
*/
public void translate(double x, double y) {
pushPanData();
Coordinate c = camera.getPosition();
doSetPosition(new Coordinate(c.getX() + x, c.getY() + y));
fireEvent(false, null);
}
/**
* Adjust the current scale on the map by a new factor.
*
* @param delta
* Adjust the scale by factor "delta".
*/
public void scale(double delta, ZoomOption option) {
setCurrentScale(currentScale * delta, option);
}
//-------------------------------------------------------------------------
// Getters:
//-------------------------------------------------------------------------
/** Return the current scale. */
public double getCurrentScale() {
return currentScale;
}
/**
* Given the information in this MapView object, what is the currently visible area?
*
* @return Notice that at this moment an Axis Aligned Bounding Box is returned! This means that rotating is not yet
* possible.
*/
public Bbox getBounds() {
double w = getViewSpaceWidth();
double h = getViewSpaceHeight();
double x = camera.getX() - w / 2;
double y = camera.getY() - h / 2;
return new Bbox(x, y, w, h);
}
/**
* Set the list of predefined map resolutions (resolution = inverse of scale).
*
* @param resolutions
* the list of predefined resolutions (expressed in map unit/pixel)
*/
public void setResolutions(List<Double> resolutions) {
this.resolutions.clear();
this.resolutions.addAll(resolutions);
Collections.sort(this.resolutions, Collections.reverseOrder());
}
/** Get the list of predefined map resolutions (resolution = inverse of scale). */
public List<Double> getResolutions() {
return resolutions;
}
/**
* are we panning ?
*
* @return true if panning
*/
public boolean isSameScaleLevel() {
return Math.abs(currentScale - previousScale) < 1.0E-10
&& previousPanOrigin.equalsDelta(this.panOrigin, 1.0E-10);
}
/** Return the internal camera that is used to represent the map's point of view. */
public Camera getCamera() {
return camera;
}
/** Return the transformer that is used to transform coordinate and geometries between world and screen space. */
public WorldViewTransformer getWorldViewTransformer() {
if (null == worldViewTransformer) {
worldViewTransformer = new WorldViewTransformer(this);
}
return worldViewTransformer;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public Coordinate getPanOrigin() {
return panOrigin;
}
public void setMaximumScale(double maximumScale) {
if (maximumScale > 0) {
this.maximumScale = maximumScale;
}
}
public Bbox getMaxBounds() {
return maxBounds;
}
public void setMaxBounds(Bbox maxBounds) {
this.maxBounds = maxBounds;
}
public boolean isPanDragging() {
return panDragging;
}
public void setPanDragging(boolean panDragging) {
this.panDragging = panDragging;
}
public String toString() {
return "VIEW: scale=" + this.currentScale + ", " + this.camera.toString();
}
// -------------------------------------------------------------------------
// Private functions:
// -------------------------------------------------------------------------
private void doSetScale(double scale, ZoomOption option) {
currentScale = scale;
}
private void doSetPosition(Coordinate coordinate) {
Coordinate center = calcCenterFromPoint(coordinate);
camera.setPosition(center);
}
private void doApplyBounds(Bbox bounds, ZoomOption option) {
if (bounds != null) {
if (!bounds.isEmpty()) {
// find best scale
double scale = getBestScale(bounds);
// snap and limit
scale = snapToResolution(scale, option);
// set scale
doSetScale(scale, option);
}
doSetPosition(bounds.getCenterPoint());
}
}
private double getMinimumScale() {
if (maxBounds != null) {
double wRatio = width / maxBounds.getWidth();
double hRatio = height / maxBounds.getHeight();
// return the maximum to fit outside
return wRatio > hRatio ? wRatio : hRatio;
} else {
return Double.MIN_VALUE;
}
}
private double getBestScale(Bbox bounds) {
double wRatio;
double boundsWidth = bounds.getWidth();
if (boundsWidth <= 0) {
wRatio = getMinimumScale();
} else {
wRatio = width / boundsWidth;
}
double hRatio;
double boundsHeight = bounds.getHeight();
if (boundsHeight <= 0) {
hRatio = getMinimumScale();
} else {
hRatio = height / boundsHeight;
}
// return the minimum to fit inside
return wRatio < hRatio ? wRatio : hRatio;
}
private double limitScale(double scale) {
double minimumScale = getMinimumScale();
if (scale < minimumScale) {
return minimumScale;
} else if (scale > maximumScale) {
return maximumScale;
} else {
return scale;
}
}
private IndexRange getResolutionRange() {
IndexRange range = new IndexRange();
double max = 1.0 / getMinimumScale();
double min = 1.0 / maximumScale;
for (int i = 0; i < resolutions.size(); i++) {
Double resolution = resolutions.get(i);
if (resolution >= min && resolution <= max) {
range.setMin(i);
range.setMax(i);
}
}
return range;
}
private double getViewSpaceWidth() {
return width / currentScale;
}
private double getViewSpaceHeight() {
return height / currentScale;
}
private void pushPanData() {
previousScale = currentScale;
previousPanOrigin = (Coordinate) panOrigin.clone();
}
/** Fire an event. */
private void fireEvent(boolean resized, ZoomOption option) {
handlerManager.fireEvent(new MapViewChangedEvent(getBounds(), getCurrentScale(), isSameScaleLevel(),
panDragging, resized, option));
}
/**
* Finds an optimal scale by snapping to resolutions.
*
* @param scale scale which needs to be snapped
* @param option snapping option
* @return snapped scale
*/
private double snapToResolution(double scale, ZoomOption option) {
// clip upper bounds
double allowedScale = limitScale(scale);
if (resolutions != null) {
IndexRange indexes = getResolutionRange();
if (option == ZoomOption.EXACT || !indexes.isValid()) {
// should not or cannot snap to resolutions
return allowedScale;
} else {
// find the new index
int newResolutionIndex = 0;
double screenResolution = 1.0 / allowedScale;
if (screenResolution >= resolutions.get(indexes.getMin())) {
newResolutionIndex = indexes.getMin();
} else if (screenResolution <= resolutions.get(indexes.getMax())) {
newResolutionIndex = indexes.getMax();
} else {
for (int i = indexes.getMin(); i < indexes.getMax(); i++) {
double upper = resolutions.get(i);
double lower = resolutions.get(i + 1);
if (screenResolution <= upper && screenResolution >= lower) {
if (option == ZoomOption.LEVEL_FIT) {
newResolutionIndex = i;
break;
} else {
if ((upper / screenResolution) > (screenResolution / lower)) {
newResolutionIndex = i + 1;
break;
} else {
newResolutionIndex = i;
break;
}
}
}
}
}
// check if we need to change level
if (newResolutionIndex == resolutionIndex && option == ZoomOption.LEVEL_CHANGE) {
if (scale > currentScale && newResolutionIndex < indexes.getMax()) {
newResolutionIndex++;
} else if (scale < currentScale && newResolutionIndex > indexes.getMin()) {
newResolutionIndex--;
}
}
resolutionIndex = newResolutionIndex;
return 1.0 / resolutions.get(resolutionIndex);
}
} else {
return scale;
}
}
/**
* Adjusts the center point of the map, to an allowed center point. This method tries to make sure the whole map
* extent is inside the maximum allowed bounds.
*
* @param worldCenter
* @return
*/
private Coordinate calcCenterFromPoint(final Coordinate worldCenter) {
double xCenter = worldCenter.getX();
double yCenter = worldCenter.getY();
if (maxBounds != null) {
double w = getViewSpaceWidth() / 2;
double h = getViewSpaceHeight() / 2;
Coordinate minCoordinate = maxBounds.getOrigin();
Coordinate maxCoordinate = maxBounds.getEndPoint();
if ((w * 2) > maxBounds.getWidth()) {
xCenter = maxBounds.getCenterPoint().getX();
} else {
if ((xCenter - w) < minCoordinate.getX()) {
xCenter = minCoordinate.getX() + w;
}
if ((xCenter + w) > maxCoordinate.getX()) {
xCenter = maxCoordinate.getX() - w;
}
}
if ((h * 2) > maxBounds.getHeight()) {
yCenter = maxBounds.getCenterPoint().getY();
} else {
if ((yCenter - h) < minCoordinate.getY()) {
yCenter = minCoordinate.getY() + h;
}
if ((yCenter + h) > maxCoordinate.getY()) {
yCenter = maxCoordinate.getY() - h;
}
}
}
return new Coordinate(xCenter, yCenter);
}
/**
* A range of indexes.
*/
private class IndexRange {
private Integer min;
private Integer max;
public int getMax() {
return max;
}
public void setMax(int max) {
if (this.max == null || max > this.max) {
this.max = max;
}
}
public int getMin() {
return min;
}
public void setMin(int min) {
if (this.min == null || min < this.min) {
this.min = min;
}
}
public boolean isValid() {
return min != null && max != null && min <= max;
}
}
}
| GWT-47 another attempt to fix
| face/geomajas-face-gwt/geomajas-gwt-client/src/main/java/org/geomajas/gwt/client/map/MapView.java | GWT-47 another attempt to fix | |
Java | agpl-3.0 | b260151692545ed771ec2a17e372c82275dfabd2 | 0 | KinshipSoftware/KinOathKinshipArchiver,PeterWithers/temp-to-delete1,PeterWithers/temp-to-delete1,KinshipSoftware/KinOathKinshipArchiver | package nl.mpi.kinnate.svg;
import nl.mpi.kinnate.kindata.GraphSorter;
import nl.mpi.kinnate.kindata.EntityData;
import nl.mpi.kinnate.ui.GraphPanelContextMenu;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.JPanel;
import javax.xml.parsers.DocumentBuilderFactory;
import nl.mpi.arbil.data.ArbilComponentBuilder;
import nl.mpi.arbil.ui.ArbilTableModel;
import nl.mpi.arbil.ui.GuiHelper;
import nl.mpi.kinnate.KinTermSavePanel;
import nl.mpi.kinnate.entityindexer.IndexerParameters;
import nl.mpi.kinnate.SavePanel;
import nl.mpi.kinnate.kindata.DataTypes;
import nl.mpi.kinnate.kindata.EntityRelation;
import nl.mpi.kinnate.kintypestrings.KinTermGroup;
import nl.mpi.kinnate.ui.KinTypeEgoSelectionTestPanel;
import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
import org.apache.batik.dom.svg.SVGDOMImplementation;
import org.apache.batik.swing.JSVGCanvas;
import org.apache.batik.swing.JSVGScrollPane;
import org.apache.batik.swing.svg.LinkActivationEvent;
import org.apache.batik.swing.svg.LinkActivationListener;
import org.apache.batik.util.XMLResourceDescriptor;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.events.EventTarget;
import org.w3c.dom.svg.SVGDocument;
import org.w3c.dom.svg.SVGLocatable;
import org.w3c.dom.svg.SVGRect;
/**
* Document : GraphPanel
* Created on : Aug 16, 2010, 5:31:33 PM
* Author : Peter Withers
*/
public class GraphPanel extends JPanel implements SavePanel {
private JSVGScrollPane jSVGScrollPane;
protected JSVGCanvas svgCanvas;
protected SVGDocument doc;
protected ArbilTableModel arbilTableModel;
private boolean requiresSave = false;
private File svgFile = null;
protected GraphPanelSize graphPanelSize;
protected ArrayList<String> selectedGroupId;
protected String svgNameSpace = SVGDOMImplementation.SVG_NAMESPACE_URI;
public DataStoreSvg dataStoreSvg;
protected EntitySvg entitySvg;
// private URI[] egoPathsTemp = null;
public SvgUpdateHandler svgUpdateHandler;
private int currentZoom = 0;
private int currentWidth = 0;
private int currentHeight = 0;
private AffineTransform zoomAffineTransform = null;
public GraphPanel(KinTermSavePanel egoSelectionPanel) {
dataStoreSvg = new DataStoreSvg();
entitySvg = new EntitySvg();
dataStoreSvg.setDefaults();
svgUpdateHandler = new SvgUpdateHandler(this, egoSelectionPanel);
selectedGroupId = new ArrayList<String>();
graphPanelSize = new GraphPanelSize();
this.setLayout(new BorderLayout());
svgCanvas = new JSVGCanvas();
// svgCanvas.setMySize(new Dimension(600, 400));
svgCanvas.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC);
// drawNodes();
svgCanvas.setEnableImageZoomInteractor(false);
svgCanvas.setEnablePanInteractor(false);
svgCanvas.setEnableRotateInteractor(false);
svgCanvas.setEnableZoomInteractor(false);
svgCanvas.addMouseWheelListener(new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent e) {
currentZoom = currentZoom + e.getUnitsToScroll();
if (currentZoom > 8) {
currentZoom = 8;
}
if (currentZoom < -6) {
currentZoom = -6;
}
double scale = 1 - e.getUnitsToScroll() / 10.0;
double tx = -e.getX() * (scale - 1);
double ty = -e.getY() * (scale - 1);
AffineTransform at = new AffineTransform();
at.translate(tx, ty);
at.scale(scale, scale);
at.concatenate(svgCanvas.getRenderingTransform());
svgCanvas.setRenderingTransform(at);
// zoomDrawing();
}
});
// svgCanvas.setEnableResetTransformInteractor(true);
// svgCanvas.setDoubleBufferedRendering(true); // todo: look into reducing the noticable aliasing on the canvas
MouseListenerSvg mouseListenerSvg = new MouseListenerSvg(this);
svgCanvas.addMouseListener(mouseListenerSvg);
svgCanvas.addMouseMotionListener(mouseListenerSvg);
jSVGScrollPane = new JSVGScrollPane(svgCanvas);
// svgCanvas.setBackground(Color.LIGHT_GRAY);
this.add(BorderLayout.CENTER, jSVGScrollPane);
if (egoSelectionPanel instanceof KinTypeEgoSelectionTestPanel) {
svgCanvas.setComponentPopupMenu(new GraphPanelContextMenu((KinTypeEgoSelectionTestPanel) egoSelectionPanel, this, graphPanelSize));
} else {
svgCanvas.setComponentPopupMenu(new GraphPanelContextMenu(null, this, graphPanelSize));
}
}
private void zoomDrawing() {
AffineTransform scaleTransform = new AffineTransform();
scaleTransform.scale(1 - currentZoom / 10.0, 1 - currentZoom / 10.0);
System.out.println("currentZoom: " + currentZoom);
// svgCanvas.setRenderingTransform(scaleTransform);
Rectangle canvasBounds = this.getBounds();
SVGRect bbox = ((SVGLocatable) doc.getRootElement()).getBBox();
if (bbox != null) {
System.out.println("previousZoomedWith: " + bbox.getWidth());
}
// SVGElement rootElement = doc.getRootElement();
// if (currentWidth < canvasBounds.width) {
float drawingCenter = (currentWidth / 2);
// float drawingCenter = (bbox.getX() + (bbox.getWidth() / 2));
float canvasCenter = (canvasBounds.width / 2);
zoomAffineTransform = new AffineTransform();
zoomAffineTransform.translate((canvasCenter - drawingCenter), 1);
zoomAffineTransform.concatenate(scaleTransform);
svgCanvas.setRenderingTransform(zoomAffineTransform);
}
public void setArbilTableModel(ArbilTableModel arbilTableModelLocal) {
arbilTableModel = arbilTableModelLocal;
}
public void readSvg(File svgFilePath) {
svgFile = svgFilePath;
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory documentFactory = new SAXSVGDocumentFactory(parser);
try {
doc = (SVGDocument) documentFactory.createDocument(svgFilePath.toURI().toString());
svgCanvas.setDocument(doc);
dataStoreSvg = DataStoreSvg.loadDataFromSvg(doc);
requiresSave = false;
entitySvg.readEntityPositions(doc.getElementById("EntityGroup"));
} catch (IOException ioe) {
GuiHelper.linorgBugCatcher.logError(ioe);
}
// set up the mouse listeners that were lost in the save/re-open process
for (String groupForMouseListener : new String[]{"EntityGroup", "LabelsGroup"}) {
Element parentElement = doc.getElementById(groupForMouseListener);
if (parentElement == null) {
Element requiredGroup = doc.createElementNS(svgNameSpace, "g");
requiredGroup.setAttribute("id", groupForMouseListener);
Element svgRoot = doc.getDocumentElement();
svgRoot.appendChild(requiredGroup);
} else {
Node currentNode = parentElement.getFirstChild();
while (currentNode != null) {
((EventTarget) currentNode).addEventListener("mousedown", new MouseListenerSvg(this), false);
currentNode = currentNode.getNextSibling();
}
}
}
}
public void generateDefaultSvg() {
try {
Element svgRoot;
Element relationGroupNode;
Element entityGroupNode;
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
// set up a kinnate namespace so that the ego list and kin type strings can have more permanent storage places
// in order to add the extra namespaces to the svg document we use a string and parse it
// other methods have been tried but this is the most readable and the only one that actually works
// I think this is mainly due to the way the svg dom would otherwise be constructed
// others include:
// doc.getDomConfig()
// doc.getDocumentElement().setAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "kin:version", "");
// doc.getDocumentElement().setAttribute("xmlns:" + DataStoreSvg.kinDataNameSpace, DataStoreSvg.kinDataNameSpaceLocation); // this method of declaring multiple namespaces looks to me to be wrong but it is the only method that does not get stripped out by the transformer on save
// Document doc = impl.createDocument(svgNS, "svg", null);
// SVGDocument doc = svgCanvas.getSVGDocument();
String templateXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:kin=\"http://mpi.nl/tla/kin\" "
+ "xmlns=\"http://www.w3.org/2000/svg\" contentScriptType=\"text/ecmascript\" "
+ " zoomAndPan=\"magnify\" contentStyleType=\"text/css\" "
+ "preserveAspectRatio=\"xMidYMid meet\" version=\"1.0\"/>";
// DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
// doc = (SVGDocument) impl.createDocument(svgNameSpace, "svg", null);
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory documentFactory = new SAXSVGDocumentFactory(parser);
doc = (SVGDocument) documentFactory.createDocument(svgNameSpace, new StringReader(templateXml));
entitySvg.insertSymbols(doc, svgNameSpace);
// Get the root element (the 'svg' element)
svgRoot = doc.getDocumentElement();
// add the relation symbols in a group below the relation lines
relationGroupNode = doc.createElementNS(svgNameSpace, "g");
relationGroupNode.setAttribute("id", "RelationGroup");
svgRoot.appendChild(relationGroupNode);
// add the entity symbols in a group on top of the relation lines
entityGroupNode = doc.createElementNS(svgNameSpace, "g");
entityGroupNode.setAttribute("id", "EntityGroup");
svgRoot.appendChild(entityGroupNode);
// add the labels group on top, also added on svg load if missing
Element labelsGroup = doc.createElementNS(svgNameSpace, "g");
labelsGroup.setAttribute("id", "LabelsGroup");
svgRoot.appendChild(labelsGroup);
dataStoreSvg.indexParameters.symbolFieldsFields.setAvailableValues(entitySvg.listSymbolNames(doc));
} catch (IOException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
}
}
private void saveSvg(File svgFilePath) {
svgFile = svgFilePath;
// todo: make sure the file path ends in .svg lowercase
drawNodes(); // re draw the nodes so that any data changes such as the title/description in the kin term groups get updated into the file
ArbilComponentBuilder.savePrettyFormatting(doc, svgFilePath);
requiresSave = false;
}
private void printNodeNames(Node nodeElement) {
System.out.println(nodeElement.getLocalName());
System.out.println(nodeElement.getNamespaceURI());
Node childNode = nodeElement.getFirstChild();
while (childNode != null) {
printNodeNames(childNode);
childNode = childNode.getNextSibling();
}
}
public String[] getKinTypeStrigs() {
return dataStoreSvg.kinTypeStrings;
}
public void setKinTypeStrigs(String[] kinTypeStringArray) {
// strip out any white space, blank lines and remove duplicates
// this has set has been removed because it creates a discrepancy between what the user types and what is processed
// HashSet<String> kinTypeStringSet = new HashSet<String>();
// for (String kinTypeString : kinTypeStringArray) {
// if (kinTypeString != null && kinTypeString.trim().length() > 0) {
// kinTypeStringSet.add(kinTypeString.trim());
// }
// }
// dataStoreSvg.kinTypeStrings = kinTypeStringSet.toArray(new String[]{});
dataStoreSvg.kinTypeStrings = kinTypeStringArray;
}
public IndexerParameters getIndexParameters() {
return dataStoreSvg.indexParameters;
}
public KinTermGroup[] getkinTermGroups() {
return dataStoreSvg.kinTermGroups;
}
public void addKinTermGroup() {
ArrayList<KinTermGroup> kinTermsList = new ArrayList<KinTermGroup>(Arrays.asList(dataStoreSvg.kinTermGroups));
kinTermsList.add(new KinTermGroup());
dataStoreSvg.kinTermGroups = kinTermsList.toArray(new KinTermGroup[]{});
}
// public String[] getEgoUniquiIdentifiersList() {
// return dataStoreSvg.egoIdentifierSet.toArray(new String[]{});
// }
// public String[] getEgoIdList() {
// return dataStoreSvg.egoIdentifierSet.toArray(new String[]{});
// }
// public URI[] getEgoPaths() {
// if (egoPathsTemp != null) {
// return egoPathsTemp;
// }
// ArrayList<URI> returnPaths = new ArrayList<URI>();
// for (String egoId : dataStoreSvg.egoIdentifierSet) {
// try {
// String entityPath = getPathForElementId(egoId);
//// if (entityPath != null) {
// returnPaths.add(new URI(entityPath));
//// }
// } catch (URISyntaxException ex) {
// GuiHelper.linorgBugCatcher.logError(ex);
// // todo: warn user with a dialog
// }
// }
// return returnPaths.toArray(new URI[]{});
// }
// public void setRequiredEntities(URI[] egoPathArray, String[] egoIdentifierArray) {
//// egoPathsTemp = egoPathArray; // egoPathsTemp is only required if the ego nodes are not already on the graph (otherwise the path can be obtained from the graph elements)
// dataStoreSvg.requiredEntities = new HashSet<String>(Arrays.asList(egoIdentifierArray));
// }
//
// public void addRequiredEntity(URI[] egoPathArray, String[] egoIdentifierArray) {
//// egoPathsTemp = egoPathArray; // egoPathsTemp is only required if the ego nodes are not already on the graph (otherwise the path can be obtained from the graph elements)
// dataStoreSvg.requiredEntities.addAll(Arrays.asList(egoIdentifierArray));
// }
// public void removeEgo(String[] egoIdentifierArray) {
// dataStoreSvg.egoIdentifierSet.removeAll(Arrays.asList(egoIdentifierArray));
// }
public String[] getSelectedIds() {
return selectedGroupId.toArray(new String[]{});
}
// public boolean selectionContainsEgo() {
// for (String selectedId : selectedGroupId) {
// if (dataStoreSvg.egoIdentifierSet.contains(selectedId)) {
// return true;
// }
// }
// return false;
// }
public String getPathForElementId(String elementId) {
// NamedNodeMap namedNodeMap = doc.getElementById(elementId).getAttributes();
// for (int attributeCounter = 0; attributeCounter < namedNodeMap.getLength(); attributeCounter++) {
// System.out.println(namedNodeMap.item(attributeCounter).getNodeName());
// System.out.println(namedNodeMap.item(attributeCounter).getNamespaceURI());
// System.out.println(namedNodeMap.item(attributeCounter).getNodeValue());
// }
Element entityElement = doc.getElementById(elementId);
if (entityElement == null) {
return null;
} else {
return entityElement.getAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "path");
}
}
public String getKinTypeForElementId(String elementId) {
Element entityElement = doc.getElementById(elementId);
return entityElement.getAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "kintype");
}
public void resetZoom() {
AffineTransform at = new AffineTransform();
at.scale(1, 1);
at.setToTranslation(1, 1);
svgCanvas.setRenderingTransform(at);
}
public void drawNodes() {
drawNodes(dataStoreSvg.graphData);
}
public void drawNodes(GraphSorter graphDataLocal) {
// todo: resolve threading issue and update issue so that imdi nodes that update can update the diagram
requiresSave = true;
dataStoreSvg.graphData = graphDataLocal;
int vSpacing = graphPanelSize.getVerticalSpacing(dataStoreSvg.graphData.gridHeight);
int hSpacing = graphPanelSize.getHorizontalSpacing(dataStoreSvg.graphData.gridWidth);
currentWidth = graphPanelSize.getWidth(dataStoreSvg.graphData.gridWidth, hSpacing);
currentHeight = graphPanelSize.getHeight(dataStoreSvg.graphData.gridHeight, vSpacing);
try {
Element svgRoot;
Element relationGroupNode;
Element entityGroupNode;
// if (doc == null) {
// } else {
Node relationGroupNodeOld = doc.getElementById("RelationGroup");
Node entityGroupNodeOld = doc.getElementById("EntityGroup");
// remove the old relation lines
relationGroupNode = doc.createElementNS(svgNameSpace, "g");
relationGroupNode.setAttribute("id", "RelationGroup");
relationGroupNodeOld.getParentNode().insertBefore(relationGroupNode, relationGroupNodeOld);
relationGroupNodeOld.getParentNode().removeChild(relationGroupNodeOld);
// remove the old entity symbols
entityGroupNode = doc.createElementNS(svgNameSpace, "g");
entityGroupNode.setAttribute("id", "EntityGroup");
entityGroupNodeOld.getParentNode().insertBefore(entityGroupNode, entityGroupNodeOld);
entityGroupNodeOld.getParentNode().removeChild(entityGroupNodeOld);
// remove old kin diagram data
NodeList dataNodes = doc.getElementsByTagNameNS("http://mpi.nl/tla/kin", "KinDiagramData");
for (int nodeCounter = 0; nodeCounter < dataNodes.getLength(); nodeCounter++) {
dataNodes.item(nodeCounter).getParentNode().removeChild(dataNodes.item(nodeCounter));
}
// Get the root element (the 'svg' element)
svgRoot = doc.getDocumentElement();
// }
// Set the width and height attributes on the root 'svg' element.
svgRoot.setAttribute("width", Integer.toString(currentWidth));
svgRoot.setAttribute("height", Integer.toString(currentHeight));
this.setPreferredSize(new Dimension(graphPanelSize.getHeight(dataStoreSvg.graphData.gridHeight, vSpacing), graphPanelSize.getWidth(dataStoreSvg.graphData.gridWidth, hSpacing)));// entitySvg.removeOldEntities(entityGroupNode);
// entitySvg.removeOldEntities(relationGroupNode);
// todo: find the real text size from batik
// store the selected kin type strings and other data in the dom
dataStoreSvg.storeAllData(doc);
for (EntityData currentNode : dataStoreSvg.graphData.getDataNodes()) {
if (currentNode.isVisible) {
entityGroupNode.appendChild(entitySvg.createEntitySymbol(this, currentNode, hSpacing, vSpacing));
}
}
for (EntityData currentNode : dataStoreSvg.graphData.getDataNodes()) {
if (currentNode.isVisible) {
for (EntityRelation graphLinkNode : currentNode.getVisiblyRelateNodes()) {
if ((dataStoreSvg.showKinTermLines || graphLinkNode.relationLineType != DataTypes.RelationLineType.kinTermLine)
&& (dataStoreSvg.showSanguineLines || graphLinkNode.relationLineType != DataTypes.RelationLineType.sanguineLine)) {
new RelationSvg().insertRelation(this, svgNameSpace, relationGroupNode, currentNode, graphLinkNode, hSpacing, vSpacing);
}
}
}
}
// todo: allow the user to set an entity as the provider of new dat being entered, this selected user can then be added to each field that is updated as the providence for that data. this would be best done in a cascading fashon so that there is a default informant for the entity and if required for sub nodes and fields
svgCanvas.setSVGDocument(doc);
//ArbilComponentBuilder.savePrettyFormatting(doc, new File("/Users/petwit/Documents/SharedInVirtualBox/mpi-co-svn-mpi-nl/LAT/Kinnate/trunk/src/main/resources/output.svg"));
// svgCanvas.revalidate();
// svgUpdateHandler.updateSvgSelectionHighlights(); // todo: does this rsolve the issue after an update that the selection highlight is lost but the selection is still made?
selectedGroupId.clear();
// zoomDrawing();
if (zoomAffineTransform != null) {
// re apply the last zoom
// todo: asses why this does not work
svgCanvas.setRenderingTransform(zoomAffineTransform);
}
svgCanvas.addLinkActivationListener(new LinkActivationListener() {
public void linkActivated(LinkActivationEvent lae) {
// todo: find a better way to block the built in hyper link handler that tries to load the url into the canvas
throw new UnsupportedOperationException("Not supported yet.");
}
});
} catch (DOMException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
}
}
public boolean hasSaveFileName() {
return svgFile != null;
}
public File getFileName() {
return svgFile;
}
public boolean requiresSave() {
return requiresSave;
}
public void setRequiresSave() {
requiresSave = true;
}
public void saveToFile() {
saveSvg(svgFile);
}
public void saveToFile(File saveAsFile) {
saveSvg(saveAsFile);
}
public void updateGraph() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
| src/main/java/nl/mpi/kinnate/svg/GraphPanel.java | package nl.mpi.kinnate.svg;
import nl.mpi.kinnate.kindata.GraphSorter;
import nl.mpi.kinnate.kindata.EntityData;
import nl.mpi.kinnate.ui.GraphPanelContextMenu;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.JPanel;
import javax.xml.parsers.DocumentBuilderFactory;
import nl.mpi.arbil.data.ArbilComponentBuilder;
import nl.mpi.arbil.ui.ArbilTableModel;
import nl.mpi.arbil.ui.GuiHelper;
import nl.mpi.kinnate.KinTermSavePanel;
import nl.mpi.kinnate.entityindexer.IndexerParameters;
import nl.mpi.kinnate.SavePanel;
import nl.mpi.kinnate.kindata.DataTypes;
import nl.mpi.kinnate.kindata.EntityRelation;
import nl.mpi.kinnate.kintypestrings.KinTermGroup;
import nl.mpi.kinnate.ui.KinTypeEgoSelectionTestPanel;
import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
import org.apache.batik.dom.svg.SVGDOMImplementation;
import org.apache.batik.swing.JSVGCanvas;
import org.apache.batik.swing.JSVGScrollPane;
import org.apache.batik.swing.svg.LinkActivationEvent;
import org.apache.batik.swing.svg.LinkActivationListener;
import org.apache.batik.util.XMLResourceDescriptor;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.svg.SVGDocument;
import org.w3c.dom.svg.SVGLocatable;
import org.w3c.dom.svg.SVGRect;
/**
* Document : GraphPanel
* Created on : Aug 16, 2010, 5:31:33 PM
* Author : Peter Withers
*/
public class GraphPanel extends JPanel implements SavePanel {
private JSVGScrollPane jSVGScrollPane;
protected JSVGCanvas svgCanvas;
protected SVGDocument doc;
protected ArbilTableModel arbilTableModel;
private boolean requiresSave = false;
private File svgFile = null;
protected GraphPanelSize graphPanelSize;
protected ArrayList<String> selectedGroupId;
protected String svgNameSpace = SVGDOMImplementation.SVG_NAMESPACE_URI;
public DataStoreSvg dataStoreSvg;
protected EntitySvg entitySvg;
// private URI[] egoPathsTemp = null;
public SvgUpdateHandler svgUpdateHandler;
private int currentZoom = 0;
private int currentWidth = 0;
private int currentHeight = 0;
private AffineTransform zoomAffineTransform = null;
public GraphPanel(KinTermSavePanel egoSelectionPanel) {
dataStoreSvg = new DataStoreSvg();
entitySvg = new EntitySvg();
dataStoreSvg.setDefaults();
svgUpdateHandler = new SvgUpdateHandler(this, egoSelectionPanel);
selectedGroupId = new ArrayList<String>();
graphPanelSize = new GraphPanelSize();
this.setLayout(new BorderLayout());
svgCanvas = new JSVGCanvas();
// svgCanvas.setMySize(new Dimension(600, 400));
svgCanvas.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC);
// drawNodes();
svgCanvas.setEnableImageZoomInteractor(false);
svgCanvas.setEnablePanInteractor(false);
svgCanvas.setEnableRotateInteractor(false);
svgCanvas.setEnableZoomInteractor(false);
svgCanvas.addMouseWheelListener(new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent e) {
currentZoom = currentZoom + e.getUnitsToScroll();
if (currentZoom > 8) {
currentZoom = 8;
}
if (currentZoom < -6) {
currentZoom = -6;
}
double scale = 1 - e.getUnitsToScroll() / 10.0;
double tx = -e.getX() * (scale - 1);
double ty = -e.getY() * (scale - 1);
AffineTransform at = new AffineTransform();
at.translate(tx, ty);
at.scale(scale, scale);
at.concatenate(svgCanvas.getRenderingTransform());
svgCanvas.setRenderingTransform(at);
// zoomDrawing();
}
});
// svgCanvas.setEnableResetTransformInteractor(true);
// svgCanvas.setDoubleBufferedRendering(true); // todo: look into reducing the noticable aliasing on the canvas
MouseListenerSvg mouseListenerSvg = new MouseListenerSvg(this);
svgCanvas.addMouseListener(mouseListenerSvg);
svgCanvas.addMouseMotionListener(mouseListenerSvg);
jSVGScrollPane = new JSVGScrollPane(svgCanvas);
// svgCanvas.setBackground(Color.LIGHT_GRAY);
this.add(BorderLayout.CENTER, jSVGScrollPane);
if (egoSelectionPanel instanceof KinTypeEgoSelectionTestPanel) {
svgCanvas.setComponentPopupMenu(new GraphPanelContextMenu((KinTypeEgoSelectionTestPanel) egoSelectionPanel, this, graphPanelSize));
} else {
svgCanvas.setComponentPopupMenu(new GraphPanelContextMenu(null, this, graphPanelSize));
}
}
private void zoomDrawing() {
AffineTransform scaleTransform = new AffineTransform();
scaleTransform.scale(1 - currentZoom / 10.0, 1 - currentZoom / 10.0);
System.out.println("currentZoom: " + currentZoom);
// svgCanvas.setRenderingTransform(scaleTransform);
Rectangle canvasBounds = this.getBounds();
SVGRect bbox = ((SVGLocatable) doc.getRootElement()).getBBox();
if (bbox != null) {
System.out.println("previousZoomedWith: " + bbox.getWidth());
}
// SVGElement rootElement = doc.getRootElement();
// if (currentWidth < canvasBounds.width) {
float drawingCenter = (currentWidth / 2);
// float drawingCenter = (bbox.getX() + (bbox.getWidth() / 2));
float canvasCenter = (canvasBounds.width / 2);
zoomAffineTransform = new AffineTransform();
zoomAffineTransform.translate((canvasCenter - drawingCenter), 1);
zoomAffineTransform.concatenate(scaleTransform);
svgCanvas.setRenderingTransform(zoomAffineTransform);
}
public void setArbilTableModel(ArbilTableModel arbilTableModelLocal) {
arbilTableModel = arbilTableModelLocal;
}
public void readSvg(File svgFilePath) {
svgFile = svgFilePath;
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory documentFactory = new SAXSVGDocumentFactory(parser);
try {
doc = (SVGDocument) documentFactory.createDocument(svgFilePath.toURI().toString());
svgCanvas.setDocument(doc);
dataStoreSvg = DataStoreSvg.loadDataFromSvg(doc);
requiresSave = false;
entitySvg.readEntityPositions(doc.getElementById("EntityGroup"));
} catch (IOException ioe) {
GuiHelper.linorgBugCatcher.logError(ioe);
}
// svgCanvas.setURI(svgFilePath.toURI().toString());
}
public void generateDefaultSvg() {
try {
Element svgRoot;
Element relationGroupNode;
Element entityGroupNode;
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
// set up a kinnate namespace so that the ego list and kin type strings can have more permanent storage places
// in order to add the extra namespaces to the svg document we use a string and parse it
// other methods have been tried but this is the most readable and the only one that actually works
// I think this is mainly due to the way the svg dom would otherwise be constructed
// others include:
// doc.getDomConfig()
// doc.getDocumentElement().setAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "kin:version", "");
// doc.getDocumentElement().setAttribute("xmlns:" + DataStoreSvg.kinDataNameSpace, DataStoreSvg.kinDataNameSpaceLocation); // this method of declaring multiple namespaces looks to me to be wrong but it is the only method that does not get stripped out by the transformer on save
// Document doc = impl.createDocument(svgNS, "svg", null);
// SVGDocument doc = svgCanvas.getSVGDocument();
String templateXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:kin=\"http://mpi.nl/tla/kin\" "
+ "xmlns=\"http://www.w3.org/2000/svg\" contentScriptType=\"text/ecmascript\" "
+ " zoomAndPan=\"magnify\" contentStyleType=\"text/css\" "
+ "preserveAspectRatio=\"xMidYMid meet\" version=\"1.0\"/>";
// DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
// doc = (SVGDocument) impl.createDocument(svgNameSpace, "svg", null);
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory documentFactory = new SAXSVGDocumentFactory(parser);
doc = (SVGDocument) documentFactory.createDocument(svgNameSpace, new StringReader(templateXml));
entitySvg.insertSymbols(doc, svgNameSpace);
// Get the root element (the 'svg' element)
svgRoot = doc.getDocumentElement();
// add the relation symbols in a group below the relation lines
relationGroupNode = doc.createElementNS(svgNameSpace, "g");
relationGroupNode.setAttribute("id", "RelationGroup");
svgRoot.appendChild(relationGroupNode);
// add the entity symbols in a group on top of the relation lines
entityGroupNode = doc.createElementNS(svgNameSpace, "g");
entityGroupNode.setAttribute("id", "EntityGroup");
svgRoot.appendChild(entityGroupNode);
// add the labels group on top
Element labelsGroup = doc.createElementNS(svgNameSpace, "g");
labelsGroup.setAttribute("id", "LabelsGroup");
svgRoot.appendChild(labelsGroup);
dataStoreSvg.indexParameters.symbolFieldsFields.setAvailableValues(entitySvg.listSymbolNames(doc));
} catch (IOException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
}
}
private void saveSvg(File svgFilePath) {
svgFile = svgFilePath;
// todo: make sure the file path ends in .svg lowercase
drawNodes(); // re draw the nodes so that any data changes such as the title/description in the kin term groups get updated into the file
ArbilComponentBuilder.savePrettyFormatting(doc, svgFilePath);
requiresSave = false;
}
private void printNodeNames(Node nodeElement) {
System.out.println(nodeElement.getLocalName());
System.out.println(nodeElement.getNamespaceURI());
Node childNode = nodeElement.getFirstChild();
while (childNode != null) {
printNodeNames(childNode);
childNode = childNode.getNextSibling();
}
}
public String[] getKinTypeStrigs() {
return dataStoreSvg.kinTypeStrings;
}
public void setKinTypeStrigs(String[] kinTypeStringArray) {
// strip out any white space, blank lines and remove duplicates
// this has set has been removed because it creates a discrepancy between what the user types and what is processed
// HashSet<String> kinTypeStringSet = new HashSet<String>();
// for (String kinTypeString : kinTypeStringArray) {
// if (kinTypeString != null && kinTypeString.trim().length() > 0) {
// kinTypeStringSet.add(kinTypeString.trim());
// }
// }
// dataStoreSvg.kinTypeStrings = kinTypeStringSet.toArray(new String[]{});
dataStoreSvg.kinTypeStrings = kinTypeStringArray;
}
public IndexerParameters getIndexParameters() {
return dataStoreSvg.indexParameters;
}
public KinTermGroup[] getkinTermGroups() {
return dataStoreSvg.kinTermGroups;
}
public void addKinTermGroup() {
ArrayList<KinTermGroup> kinTermsList = new ArrayList<KinTermGroup>(Arrays.asList(dataStoreSvg.kinTermGroups));
kinTermsList.add(new KinTermGroup());
dataStoreSvg.kinTermGroups = kinTermsList.toArray(new KinTermGroup[]{});
}
// public String[] getEgoUniquiIdentifiersList() {
// return dataStoreSvg.egoIdentifierSet.toArray(new String[]{});
// }
// public String[] getEgoIdList() {
// return dataStoreSvg.egoIdentifierSet.toArray(new String[]{});
// }
// public URI[] getEgoPaths() {
// if (egoPathsTemp != null) {
// return egoPathsTemp;
// }
// ArrayList<URI> returnPaths = new ArrayList<URI>();
// for (String egoId : dataStoreSvg.egoIdentifierSet) {
// try {
// String entityPath = getPathForElementId(egoId);
//// if (entityPath != null) {
// returnPaths.add(new URI(entityPath));
//// }
// } catch (URISyntaxException ex) {
// GuiHelper.linorgBugCatcher.logError(ex);
// // todo: warn user with a dialog
// }
// }
// return returnPaths.toArray(new URI[]{});
// }
// public void setRequiredEntities(URI[] egoPathArray, String[] egoIdentifierArray) {
//// egoPathsTemp = egoPathArray; // egoPathsTemp is only required if the ego nodes are not already on the graph (otherwise the path can be obtained from the graph elements)
// dataStoreSvg.requiredEntities = new HashSet<String>(Arrays.asList(egoIdentifierArray));
// }
//
// public void addRequiredEntity(URI[] egoPathArray, String[] egoIdentifierArray) {
//// egoPathsTemp = egoPathArray; // egoPathsTemp is only required if the ego nodes are not already on the graph (otherwise the path can be obtained from the graph elements)
// dataStoreSvg.requiredEntities.addAll(Arrays.asList(egoIdentifierArray));
// }
// public void removeEgo(String[] egoIdentifierArray) {
// dataStoreSvg.egoIdentifierSet.removeAll(Arrays.asList(egoIdentifierArray));
// }
public String[] getSelectedIds() {
return selectedGroupId.toArray(new String[]{});
}
// public boolean selectionContainsEgo() {
// for (String selectedId : selectedGroupId) {
// if (dataStoreSvg.egoIdentifierSet.contains(selectedId)) {
// return true;
// }
// }
// return false;
// }
public String getPathForElementId(String elementId) {
// NamedNodeMap namedNodeMap = doc.getElementById(elementId).getAttributes();
// for (int attributeCounter = 0; attributeCounter < namedNodeMap.getLength(); attributeCounter++) {
// System.out.println(namedNodeMap.item(attributeCounter).getNodeName());
// System.out.println(namedNodeMap.item(attributeCounter).getNamespaceURI());
// System.out.println(namedNodeMap.item(attributeCounter).getNodeValue());
// }
Element entityElement = doc.getElementById(elementId);
// if (entityElement == null) {
// return null;
// } else {
return entityElement.getAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "path");
// }
}
public String getKinTypeForElementId(String elementId) {
Element entityElement = doc.getElementById(elementId);
return entityElement.getAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "kintype");
}
public void resetZoom() {
AffineTransform at = new AffineTransform();
at.scale(1, 1);
at.setToTranslation(1, 1);
svgCanvas.setRenderingTransform(at);
}
public void drawNodes() {
drawNodes(dataStoreSvg.graphData);
}
public void drawNodes(GraphSorter graphDataLocal) {
requiresSave = true;
dataStoreSvg.graphData = graphDataLocal;
int vSpacing = graphPanelSize.getVerticalSpacing(dataStoreSvg.graphData.gridHeight);
int hSpacing = graphPanelSize.getHorizontalSpacing(dataStoreSvg.graphData.gridWidth);
currentWidth = graphPanelSize.getWidth(dataStoreSvg.graphData.gridWidth, hSpacing);
currentHeight = graphPanelSize.getHeight(dataStoreSvg.graphData.gridHeight, vSpacing);
try {
Element svgRoot;
Element relationGroupNode;
Element entityGroupNode;
// if (doc == null) {
// } else {
Node relationGroupNodeOld = doc.getElementById("RelationGroup");
Node entityGroupNodeOld = doc.getElementById("EntityGroup");
// remove the old relation lines
relationGroupNode = doc.createElementNS(svgNameSpace, "g");
relationGroupNode.setAttribute("id", "RelationGroup");
relationGroupNodeOld.getParentNode().insertBefore(relationGroupNode, relationGroupNodeOld);
relationGroupNodeOld.getParentNode().removeChild(relationGroupNodeOld);
// remove the old entity symbols
entityGroupNode = doc.createElementNS(svgNameSpace, "g");
entityGroupNode.setAttribute("id", "EntityGroup");
entityGroupNodeOld.getParentNode().insertBefore(entityGroupNode, entityGroupNodeOld);
entityGroupNodeOld.getParentNode().removeChild(entityGroupNodeOld);
// remove old kin diagram data
NodeList dataNodes = doc.getElementsByTagNameNS("http://mpi.nl/tla/kin", "KinDiagramData");
for (int nodeCounter = 0; nodeCounter < dataNodes.getLength(); nodeCounter++) {
dataNodes.item(nodeCounter).getParentNode().removeChild(dataNodes.item(nodeCounter));
}
// Get the root element (the 'svg' element)
svgRoot = doc.getDocumentElement();
// }
// Set the width and height attributes on the root 'svg' element.
svgRoot.setAttribute("width", Integer.toString(currentWidth));
svgRoot.setAttribute("height", Integer.toString(currentHeight));
this.setPreferredSize(new Dimension(graphPanelSize.getHeight(dataStoreSvg.graphData.gridHeight, vSpacing), graphPanelSize.getWidth(dataStoreSvg.graphData.gridWidth, hSpacing)));// entitySvg.removeOldEntities(entityGroupNode);
// entitySvg.removeOldEntities(relationGroupNode);
// todo: find the real text size from batik
// store the selected kin type strings and other data in the dom
dataStoreSvg.storeAllData(doc);
for (EntityData currentNode : dataStoreSvg.graphData.getDataNodes()) {
if (currentNode.isVisible) {
entityGroupNode.appendChild(entitySvg.createEntitySymbol(this, currentNode, hSpacing, vSpacing));
}
}
for (EntityData currentNode : dataStoreSvg.graphData.getDataNodes()) {
if (currentNode.isVisible) {
for (EntityRelation graphLinkNode : currentNode.getVisiblyRelateNodes()) {
if ((dataStoreSvg.showKinTermLines || graphLinkNode.relationLineType != DataTypes.RelationLineType.kinTermLine)
&& (dataStoreSvg.showSanguineLines || graphLinkNode.relationLineType != DataTypes.RelationLineType.sanguineLine)) {
new RelationSvg().insertRelation(this, svgNameSpace, relationGroupNode, currentNode, graphLinkNode, hSpacing, vSpacing);
}
}
}
}
// todo: allow the user to set an entity as the provider of new dat being entered, this selected user can then be added to each field that is updated as the providence for that data. this would be best done in a cascading fashon so that there is a default informant for the entity and if required for sub nodes and fields
svgCanvas.setSVGDocument(doc);
//ArbilComponentBuilder.savePrettyFormatting(doc, new File("/Users/petwit/Documents/SharedInVirtualBox/mpi-co-svn-mpi-nl/LAT/Kinnate/trunk/src/main/resources/output.svg"));
// svgCanvas.revalidate();
// svgUpdateHandler.updateSvgSelectionHighlights(); // todo: does this rsolve the issue after an update that the selection highlight is lost but the selection is still made?
selectedGroupId.clear();
// zoomDrawing();
if (zoomAffineTransform != null) {
// re apply the last zoom
// todo: asses why this does not work
svgCanvas.setRenderingTransform(zoomAffineTransform);
}
svgCanvas.addLinkActivationListener(new LinkActivationListener() {
public void linkActivated(LinkActivationEvent lae) {
// todo: find a better way to block the built in hyper link handler that tries to load the url into the canvas
throw new UnsupportedOperationException("Not supported yet.");
}
});
} catch (DOMException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
}
}
public boolean hasSaveFileName() {
return svgFile != null;
}
public File getFileName() {
return svgFile;
}
public boolean requiresSave() {
return requiresSave;
}
public void setRequiresSave() {
requiresSave = true;
}
public void saveToFile() {
saveSvg(svgFile);
}
public void saveToFile(File saveAsFile) {
saveSvg(saveAsFile);
}
public void updateGraph() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
| On load of an svg file set up the mouse listeners that were lost in the save/re-open process. Added coloured kin term labels. Resolved issue handling urls from transient nodes.
| src/main/java/nl/mpi/kinnate/svg/GraphPanel.java | On load of an svg file set up the mouse listeners that were lost in the save/re-open process. Added coloured kin term labels. Resolved issue handling urls from transient nodes. | |
Java | lgpl-2.1 | 921898ceb29e18cf664103bc658cf5276b18e3a0 | 0 | house13/CardBox,house13/CardBox,house13/CardBox,house13/CardBox,house13/CardBox | package com.hextilla.cardbox.lobby.matchmaking;
import static com.hextilla.cardbox.lobby.Log.log;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import com.hextilla.cardbox.data.CardBoxGameConfig;
import com.hextilla.cardbox.data.TableMatchConfig;
import com.hextilla.cardbox.lobby.table.TableItem;
import com.hextilla.cardbox.util.CardBoxContext;
import com.samskivert.swing.HGroupLayout;
import com.samskivert.swing.VGroupLayout;
import com.threerings.crowd.data.PlaceObject;
import com.threerings.parlor.client.SeatednessObserver;
import com.threerings.parlor.client.TableDirector;
import com.threerings.parlor.client.TableObserver;
import com.threerings.parlor.data.Table;
import com.threerings.parlor.data.TableConfig;
import com.threerings.parlor.game.data.GameAI;
public class ComputerOpponentView extends JPanel
implements TableObserver, ActionListener, SeatednessObserver
{
/**
*
*/
private static final long serialVersionUID = -5893833850770210445L;
/**
* Creates a new table list view, suitable for providing the user interface for table-style
* matchmaking in a table lobby.
*/
public ComputerOpponentView (CardBoxContext ctx, CardBoxGameConfig config)
{
// keep track of these
_config = config;
_ctx = ctx;
// create our table director
_tdtr = new TableDirector(ctx, "aiTableSet", this);
// add ourselves as a seatedness observer
_tdtr.addSeatednessObserver(this);
// set up a layout manager
/*HGroupLayout gl = new HGroupLayout(HGroupLayout.STRETCH);
gl.setOffAxisPolicy(HGroupLayout.STRETCH);
setLayout(gl);
// we have two lists of tables, one of tables being matchmade...
VGroupLayout pgl = new VGroupLayout(VGroupLayout.STRETCH);
pgl.setOffAxisPolicy(VGroupLayout.STRETCH);
pgl.setJustification(VGroupLayout.TOP);
JPanel panel = new JPanel(pgl);
panel.add(new JLabel("Computer Opponents"));
JPanel bbox = HGroupLayout.makeButtonBox(HGroupLayout.RIGHT);
bbox.add(_randomButton);
bbox.add(_aggressiveButton);
bbox.add(_defensiveButton);
panel.add(bbox, VGroupLayout.FIXED);
add(panel);*/
/*_randomButton = new JButton("Easy Opponent");
_randomButton.addActionListener(this);
_aggressiveButton = new JButton("Aggressive Opponent");
_defensiveButton = new JButton("Defensive Opponent");
setLayout(new GridLayout(2, 1));
JPanel top = new JPanel(new BorderLayout());
JPanel bottom = new JPanel();
bottom.setLayout(new BoxLayout(bottom, BoxLayout.Y_AXIS));
top.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 0));
bottom.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
top.add(new JLabel("Computer Opponents"));
bottom.add(_randomButton);
add(top);
add(bottom);*/
_randomButton = new JButton("Easy Opponent");
_randomButton.addActionListener(this);
_aggressiveButton = new JButton("Aggressive Opponent");
_defensiveButton = new JButton("Defensive Opponent");
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.weighty = 0.1;
c.gridheight = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(0, 5, 0, 5);
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 3;
add(new JLabel("Computer Opponents"), c);
c.gridx = 0;
c.gridy = 1;
c.fill = GridBagConstraints.BOTH;
c.gridwidth = 1;
c.weighty = 0.9;
add(_randomButton, c);
c.gridx = 1;
c.gridy = 1;
add(_aggressiveButton, c);
c.gridx = 2;
c.gridy = 1;
add(_defensiveButton, c);
}
// documentation inherited
public void setPlace (PlaceObject place)
{
// pass the good word on to our table director
_tdtr.setTableObject(place);
}
// documentation inherited
public void leavePlace (PlaceObject place)
{
// pass the good word on to our table director
_tdtr.clearTableObject();
}
// documentation inherited
public void tableAdded (Table table)
{
log.info("Table added [table=" + table + "].");
}
// documentation inherited
public void tableUpdated (Table table)
{
}
// documentation inherited
public void tableRemoved (int tableId)
{
}
// documentation inherited
public void actionPerformed (ActionEvent event)
{
// the create table button was clicked. use the game config as configured by the
// configurator to create a table
CardBoxGameConfig config = _config;
//Add the AI player
GameAI ai = new GameAI();
ai.skill = 0;
ai.personality = 0;
config.ais = new GameAI[1];
config.ais[0] = ai;
TableConfig tconfig = new TableConfig();
tconfig.minimumPlayerCount = ((TableMatchConfig)config.getGameDefinition().match).minSeats;
tconfig.desiredPlayerCount = ((TableMatchConfig)config.getGameDefinition().match).maxSeats;
_tdtr.createTable(tconfig, config);
}
// documentation inherited
public void seatednessDidChange (boolean isSeated)
{
// update the create table button
_randomButton.setEnabled(!isSeated);
_aggressiveButton.setEnabled(!isSeated);
_defensiveButton.setEnabled(!isSeated);
}
/**
* Fetches the table item component associated with the specified table id.
*/
protected TableItem getTableItem (int tableId)
{
return null;
}
/** A reference to the client context. */
protected CardBoxContext _ctx;
/** The configuration for the game that we're match-making. */
protected CardBoxGameConfig _config;
/** A reference to our table director. */
protected TableDirector _tdtr;
/** Our create table button. */
protected JButton _randomButton;
protected JButton _aggressiveButton;
protected JButton _defensiveButton;
/** Our number of players indicator. */
protected JLabel _pcount;
}
| projects/cardbox/src/main/java/com/hextilla/cardbox/lobby/matchmaking/ComputerOpponentView.java | package com.hextilla.cardbox.lobby.matchmaking;
import static com.hextilla.cardbox.lobby.Log.log;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import com.hextilla.cardbox.data.CardBoxGameConfig;
import com.hextilla.cardbox.data.TableMatchConfig;
import com.hextilla.cardbox.lobby.data.LobbyCodes;
import com.hextilla.cardbox.lobby.data.LobbyObject;
import com.hextilla.cardbox.lobby.table.TableItem;
import com.hextilla.cardbox.util.CardBoxContext;
import com.samskivert.swing.HGroupLayout;
import com.samskivert.swing.SimpleSlider;
import com.samskivert.swing.VGroupLayout;
import com.samskivert.swing.util.SwingUtil;
import com.threerings.crowd.client.PlaceView;
import com.threerings.crowd.data.PlaceObject;
import com.threerings.media.SafeScrollPane;
import com.threerings.parlor.client.SeatednessObserver;
import com.threerings.parlor.client.TableDirector;
import com.threerings.parlor.client.TableObserver;
import com.threerings.parlor.data.Table;
import com.threerings.parlor.data.TableConfig;
import com.threerings.parlor.data.TableLobbyObject;
import com.threerings.parlor.game.client.GameConfigurator;
import com.threerings.parlor.game.client.SwingGameConfigurator;
import com.threerings.parlor.game.data.GameAI;
import com.threerings.util.MessageBundle;
public class ComputerOpponentView extends JPanel
implements TableObserver, ActionListener, SeatednessObserver
{
/**
* Creates a new table list view, suitable for providing the user interface for table-style
* matchmaking in a table lobby.
*/
public ComputerOpponentView (CardBoxContext ctx, CardBoxGameConfig config)
{
// keep track of these
_config = config;
_ctx = ctx;
MessageBundle msgs = ctx.getMessageManager().getBundle(LobbyCodes.LOBBY_MSGS);
// create our table director
_tdtr = new TableDirector(ctx, "aiTableSet", this);
// add ourselves as a seatedness observer
_tdtr.addSeatednessObserver(this);
// set up a layout manager
HGroupLayout gl = new HGroupLayout(HGroupLayout.STRETCH);
gl.setOffAxisPolicy(HGroupLayout.STRETCH);
setLayout(gl);
// we have two lists of tables, one of tables being matchmade...
VGroupLayout pgl = new VGroupLayout(VGroupLayout.STRETCH);
pgl.setOffAxisPolicy(VGroupLayout.STRETCH);
pgl.setJustification(VGroupLayout.TOP);
JPanel panel = new JPanel(pgl);
_create = new JButton("Computer Opponent");
_create.addActionListener(this);
JPanel bbox = HGroupLayout.makeButtonBox(HGroupLayout.RIGHT);
bbox.add(_create);
panel.add(bbox, VGroupLayout.FIXED);
add(panel);
}
// documentation inherited
public void setPlace (PlaceObject place)
{
// pass the good word on to our table director
_tdtr.setTableObject(place);
}
// documentation inherited
public void leavePlace (PlaceObject place)
{
// pass the good word on to our table director
_tdtr.clearTableObject();
}
// documentation inherited
public void tableAdded (Table table)
{
log.info("Table added [table=" + table + "].");
}
// documentation inherited
public void tableUpdated (Table table)
{
}
// documentation inherited
public void tableRemoved (int tableId)
{
}
// documentation inherited
public void actionPerformed (ActionEvent event)
{
// the create table button was clicked. use the game config as configured by the
// configurator to create a table
CardBoxGameConfig config = _config;
//Add the AI player
GameAI ai = new GameAI();
ai.skill = 0;
ai.personality = 0;
config.ais = new GameAI[1];
config.ais[0] = ai;
TableConfig tconfig = new TableConfig();
tconfig.minimumPlayerCount = ((TableMatchConfig)config.getGameDefinition().match).minSeats;
tconfig.desiredPlayerCount = ((TableMatchConfig)config.getGameDefinition().match).maxSeats;
_tdtr.createTable(tconfig, config);
}
// documentation inherited
public void seatednessDidChange (boolean isSeated)
{
// update the create table button
_create.setEnabled(!isSeated);
}
/**
* Fetches the table item component associated with the specified table id.
*/
protected TableItem getTableItem (int tableId)
{
return null;
}
/** A reference to the client context. */
protected CardBoxContext _ctx;
/** The configuration for the game that we're match-making. */
protected CardBoxGameConfig _config;
/** A reference to our table director. */
protected TableDirector _tdtr;
/** Our create table button. */
protected JButton _create;
/** Our number of players indicator. */
protected JLabel _pcount;
}
| Fixed layout for computer player options
| projects/cardbox/src/main/java/com/hextilla/cardbox/lobby/matchmaking/ComputerOpponentView.java | Fixed layout for computer player options | |
Java | lgpl-2.1 | cad4626ccf7c55e565cf024e77470e6b1e4dbb3e | 0 | retoo/pystructure,retoo/pystructure,retoo/pystructure,retoo/pystructure | /*
* Copyright (C) 2008 Reto Schuettel, Robin Stocker
*
* IFS Institute for Software, HSR Rapperswil, Switzerland
*
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
package ch.hsr.ifs.pystructure.playground;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.jdom.Content;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.ProcessingInstruction;
import org.jdom.Text;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.python.pydev.parser.jython.SimpleNode;
import org.python.pydev.parser.jython.ast.exprType;
import ch.hsr.ifs.pystructure.export.structure101.Spider;
import ch.hsr.ifs.pystructure.typeinference.basetype.IType;
import ch.hsr.ifs.pystructure.typeinference.contexts.ModuleContext;
import ch.hsr.ifs.pystructure.typeinference.goals.base.IGoal;
import ch.hsr.ifs.pystructure.typeinference.goals.base.ILocatable;
import ch.hsr.ifs.pystructure.typeinference.goals.base.Location;
import ch.hsr.ifs.pystructure.typeinference.goals.references.AttributeReferencesGoal;
import ch.hsr.ifs.pystructure.typeinference.goals.references.PossibleAttributeReferencesGoal;
import ch.hsr.ifs.pystructure.typeinference.goals.references.PossibleReferencesGoal;
import ch.hsr.ifs.pystructure.typeinference.goals.types.ClassAttributeTypeGoal;
import ch.hsr.ifs.pystructure.typeinference.inferencer.PythonTypeInferencer;
import ch.hsr.ifs.pystructure.typeinference.inferencer.logger.CombinedLogger;
import ch.hsr.ifs.pystructure.typeinference.inferencer.logger.CustomLogger;
import ch.hsr.ifs.pystructure.typeinference.inferencer.logger.StatsLogger;
import ch.hsr.ifs.pystructure.typeinference.inferencer.logger.CustomLogger.Record;
import ch.hsr.ifs.pystructure.typeinference.model.definitions.Attribute;
import ch.hsr.ifs.pystructure.typeinference.model.definitions.Class;
import ch.hsr.ifs.pystructure.typeinference.model.definitions.Module;
import ch.hsr.ifs.pystructure.typeinference.model.definitions.StructureDefinition;
import ch.hsr.ifs.pystructure.typeinference.visitors.Workspace;
import ch.hsr.ifs.pystructure.utils.FileUtils;
import ch.hsr.ifs.pystructure.utils.LineIterator;
import ch.hsr.ifs.pystructure.utils.StringUtils;
public class TypeAnnotator extends HtmlOutputter {
private static final String PYTHON = "/usr/bin/python";
private static final String PYGMENTIZE = "/Users/reto/tmp/pygments/pygmentize";
private Workspace workspace;
private File outPath;
private PythonTypeInferencer inferencer;
private CustomLogger logger;
private File goalDir;
public TypeAnnotator(File path, String outPath) {
this.workspace = new Workspace(path);
this.outPath = new File(outPath);
this.logger = new CustomLogger();
goalDir = new File(outPath, "goals");
goalDir.mkdir();
this.inferencer = new PythonTypeInferencer(new CombinedLogger(new StatsLogger(false), logger));
}
public void generateReport() throws IOException {
for (Module module : workspace.getModules()) {
/* parse */
List<Result> results = parseModule(module);
writeGoalReport(results);
writeModuleReport(module, results);
}
inferencer.shutdown();
}
private void writeModuleReport(Module module, List<Result> results)
throws IOException {
/* Write page */
Document doc = createDocument(0, module.getName());
Element root = doc.getRootElement();
Element body = emptyTag("body");
root.addContent(body);
body.addContent(tag("h2", module.getNamePath().toString()));
Element details = emptyTag("p");
body.addContent(details);
printDetail(details, "File", module.getFile().toString());
Element table = emptyTag("table");
body.addContent(table);
Map<Integer, List<Result>> types = groupResultsByLine(results);
/* print out source */
int i = 1;
String styledSource = style(module.getFile());
for (String line : new LineIterator(new StringReader(styledSource))) {
Element tr = emptyTag("tr");
table.addContent(tr);
tr.addContent(td("" + i + ":"));
Element tdLine = emptyTag("td");
tr.addContent(tdLine);
tdLine.addContent(emptyTag("a", "name", "" + i));
/* UGLY */
tdLine.addContent(new ProcessingInstruction(javax.xml.transform.Result.PI_DISABLE_OUTPUT_ESCAPING, ""));
tdLine.addContent(tag("span", " " + line, "class", "code"));
tdLine.addContent(new ProcessingInstruction(javax.xml.transform.Result.PI_ENABLE_OUTPUT_ESCAPING, ""));
List<Result> lineType = types.get(i);
Element tdTypes = emptyTag("td");
tr.addContent(tdTypes);
if (lineType != null) {
Collections.sort(lineType);
boolean first = true;
for (Result result : lineType) {
if (first) {
first = false;
} else {
tdTypes.addContent(", ");
}
String goalFilename = "goals/" + result.uid + ".html";
IType type = result.type;
String label = type.toString().equals("") ? "?" : type.toString();
tdTypes.addContent(link(label, goalFilename));
}
} else {
tdTypes.addContent(" ");
}
i++;
}
String filename = moduleFilename(module);
FileOutputStream out = new FileOutputStream(new File(outPath, filename), false);
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
/* open output file */
outputter.output(doc, out);
}
private Map<Integer, List<Result>> groupResultsByLine(List<Result> results) {
/* group results by line nr */
HashMap<Integer, List<Result>> types = new HashMap<Integer, List<Result>>();
for (Result result : results) {
List<Result> l = types.get(result.node.beginLine);
if (l == null) {
l = new LinkedList<Result>();
types.put(result.node.beginLine, l);
}
l.add(result);
}
return types;
}
private List<Result> parseModule(Module module) {
List<Result> results = new ArrayList<Result>();
Spider spider = new Spider();
spider.run(module);
for (Map.Entry<StructureDefinition, List<exprType>> entry : spider.getTypables().entrySet()) {
StructureDefinition definition = entry.getKey();
List<exprType> expressions = entry.getValue();
for (exprType node : expressions) {
IType type = inferencer.evaluateType(workspace, module, node);
LinkedList<Record> log = logger.getLog();
IGoal rootGoal = logger.getCurrentRootGoal();
Result result = new Result(definition, node, type, rootGoal, log);
results.add(result);
}
}
return results;
}
private String style(File sourceFile) throws IOException {
String[] cmd = {PYTHON, PYGMENTIZE, "-f", "html", "-l", "python", sourceFile.getPath()};
Process formatter = Runtime.getRuntime().exec(cmd);
formatter.getOutputStream();
String formatted = FileUtils.read(formatter.getInputStream());
/* don't ask, don't tell */
return formatted.replaceFirst("^.*?<pre>", "")
.replaceFirst("</pre></div>$", "");
}
private void writeGoalReport(List<Result> results) throws IOException {
for (Result result : results) {
Document doc = createDocument(1, "suboals");
Element root = doc.getRootElement();
Element body = emptyTag("body");
root.addContent(body);
String filename = String.valueOf(result.uid) + ".html";
File file = new File(goalDir, filename);
IGoal rootGoal = result.rootGoal;
// header(writer, 1);
ModuleContext context = rootGoal.getContext();
Element p = emptyTag("p");
body.addContent(p);
printDetail(p, "Root Goal", rootGoal.getClass().getSimpleName());
printDetail(p, "Context", module(context.getModule()));
Element table = emptyTag("table");
body.addContent(table);
Element trHeader = emptyTag("tr");
table.addContent(trHeader);
th(trHeader, "");
th(trHeader, "Action");
th(trHeader, "Parent");
th(trHeader, "ID");
th(trHeader, "Goal");
th(trHeader, "Evaluator");
th(trHeader, "Target");
for (Record log : result.log) {
Element tr = emptyTag("tr");
table.addContent(tr);
td(tr, StringUtils.multiply(log.level, "| "), "code");
td(tr, log.msg);
td(tr, String.valueOf(log.creatorId));
td(tr, String.valueOf(log.id));
td(tr, log.goal.getClass().getSimpleName());
td(tr, log.evaluator.toString());
td(tr, goalDetails(log.goal));
}
FileOutputStream out = new FileOutputStream(file, false);
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
outputter.output(doc, out);
}
}
private Content goalDetails(IGoal goal) {
if (goal instanceof ILocatable) {
Location location = ((ILocatable) goal).getLocation();
Element span = emptyTag("span");
span.addContent(location.node.getClass().getSimpleName() + " ");
span.addContent(linkTo(location));
return span;
} else if (goal instanceof PossibleReferencesGoal) {
PossibleReferencesGoal g = (PossibleReferencesGoal) goal;
return new Text(g.getName());
} else if (goal instanceof ClassAttributeTypeGoal) {
ClassAttributeTypeGoal g = (ClassAttributeTypeGoal) goal;
return linkTo(g.getContext(), g.getClassType().getKlass(), g.getAttributeName());
} else if (goal instanceof AttributeReferencesGoal) {
AttributeReferencesGoal g = (AttributeReferencesGoal) goal;
Attribute attribute = g.getAttribute();
return linkTo(g.getContext(), attribute.getKlass(), attribute.getName());
} else if (goal instanceof PossibleAttributeReferencesGoal) {
PossibleAttributeReferencesGoal g = (PossibleAttributeReferencesGoal) goal;
return new Text(g.getName());
} else {
throw new RuntimeException("Cannot format goal, unknown goal type: " + goal);
}
}
private static String moduleFilename(Module module) {
return module.getNamePath().toString() + ".html";
}
private static Element linkTo(ModuleContext context, Class klass,
String attributeName) {
Location classLocation = new Location(context, klass.getNode());
Element span = emptyTag("span");
span.addContent("Attribute: ");
span.addContent(linkTo(klass.getName(), classLocation));
span.addContent("." + attributeName);
return span;
}
private static Element module(Module module) {
String filename = moduleFilename(module);
return link(module.getNamePath().toString(), "../" + filename);
}
static Element linkTo(String label, Location location) {
String filename = moduleFilename(location.module);
return link(label, "../" + filename + "#" + location.getLineNr());
}
protected static Element linkTo(Location location) {
String label = location.module.getNamePath().toString() + ":" + location.getLineNr();
return linkTo(label, location);
}
private static final class Result implements Comparable<Result> {
private static int currentUid = 0;
public final StructureDefinition definition;
public final SimpleNode node;
public final IType type;
public final LinkedList<Record> log;
public final int uid;
public final IGoal rootGoal;
public Result(StructureDefinition definition, SimpleNode node, IType type, IGoal rootGoal, LinkedList<Record> log) {
this.definition = definition;
this.node = node;
this.type = type;
this.rootGoal = rootGoal;
this.log = log;
this.uid = currentUid;
currentUid++;
}
public int compareTo(Result o) {
return node.beginColumn - o.node.beginColumn;
}
/* hashCode and equals have to implemented if Result objects are stored in certain
* data structures. The Object implementations can't be used as they are not consistent
* with our compareTo implementation.
*/
@Override
public boolean equals(Object obj) {
throw new RuntimeException("not impelemnted");
}
@Override
public int hashCode() {
throw new RuntimeException("not implemented");
}
@Override
public String toString() {
return this.type.toString();
}
}
public static void main(String[] args) throws Exception {
File path = new File("s101g/examples/pydoku/");
// File path = new File("tests/python/typeinference/inher/");
TypeAnnotator ta = new TypeAnnotator(path, "out");
ta.generateReport();
}
}
| src/ch/hsr/ifs/pystructure/playground/TypeAnnotator.java | /*
* Copyright (C) 2008 Reto Schuettel, Robin Stocker
*
* IFS Institute for Software, HSR Rapperswil, Switzerland
*
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
package ch.hsr.ifs.pystructure.playground;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.jdom.Content;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.ProcessingInstruction;
import org.jdom.Text;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.python.pydev.parser.jython.SimpleNode;
import org.python.pydev.parser.jython.ast.exprType;
import ch.hsr.ifs.pystructure.export.structure101.Spider;
import ch.hsr.ifs.pystructure.typeinference.basetype.IType;
import ch.hsr.ifs.pystructure.typeinference.contexts.ModuleContext;
import ch.hsr.ifs.pystructure.typeinference.goals.base.IGoal;
import ch.hsr.ifs.pystructure.typeinference.goals.base.ILocatable;
import ch.hsr.ifs.pystructure.typeinference.goals.base.Location;
import ch.hsr.ifs.pystructure.typeinference.goals.references.AttributeReferencesGoal;
import ch.hsr.ifs.pystructure.typeinference.goals.references.PossibleAttributeReferencesGoal;
import ch.hsr.ifs.pystructure.typeinference.goals.references.PossibleReferencesGoal;
import ch.hsr.ifs.pystructure.typeinference.goals.types.ClassAttributeTypeGoal;
import ch.hsr.ifs.pystructure.typeinference.inferencer.PythonTypeInferencer;
import ch.hsr.ifs.pystructure.typeinference.inferencer.logger.CombinedLogger;
import ch.hsr.ifs.pystructure.typeinference.inferencer.logger.CustomLogger;
import ch.hsr.ifs.pystructure.typeinference.inferencer.logger.StatsLogger;
import ch.hsr.ifs.pystructure.typeinference.inferencer.logger.CustomLogger.Record;
import ch.hsr.ifs.pystructure.typeinference.model.definitions.Attribute;
import ch.hsr.ifs.pystructure.typeinference.model.definitions.Class;
import ch.hsr.ifs.pystructure.typeinference.model.definitions.Module;
import ch.hsr.ifs.pystructure.typeinference.model.definitions.StructureDefinition;
import ch.hsr.ifs.pystructure.typeinference.visitors.Workspace;
import ch.hsr.ifs.pystructure.utils.FileUtils;
import ch.hsr.ifs.pystructure.utils.LineIterator;
import ch.hsr.ifs.pystructure.utils.StringUtils;
public class TypeAnnotator extends HtmlOutputter {
private static final String PYTHON = "/usr/bin/python";
private static final String PYGMENTIZE = "/Users/reto/tmp/pygments/pygmentize";
private Workspace workspace;
private File outPath;
private PythonTypeInferencer inferencer;
private CustomLogger logger;
private File goalDir;
public TypeAnnotator(File path, String outPath) {
this.workspace = new Workspace(path);
this.outPath = new File(outPath);
this.logger = new CustomLogger();
goalDir = new File(outPath, "goals");
goalDir.mkdir();
this.inferencer = new PythonTypeInferencer(new CombinedLogger(new StatsLogger(false), logger));
}
public void generateReport() throws IOException {
for (Module module : workspace.getModules()) {
/* parse */
List<Result> results = parseModule(module);
writeGoalReport(results);
writeModuleReport(module, results);
}
inferencer.shutdown();
}
private void writeModuleReport(Module module, List<Result> results)
throws IOException {
/* Write page */
Document doc = createDocument(0, module.getName());
Element root = doc.getRootElement();
Element body = emptyTag("body");
root.addContent(body);
body.addContent(tag("h2", module.getNamePath().toString()));
Element details = emptyTag("p");
body.addContent(details);
printDetail(details, "File", module.getFile().toString());
Element table = emptyTag("table");
body.addContent(table);
Map<Integer, List<Result>> types = groupResultsByLine(results);
/* print out source */
int i = 1;
String styledSource = style(module.getFile());
for (String line : new LineIterator(new StringReader(styledSource))) {
Element tr = emptyTag("tr");
table.addContent(tr);
tr.addContent(td("" + i + ":"));
Element tdLine = emptyTag("td");
tr.addContent(tdLine);
tdLine.addContent(emptyTag("a", "name", "" + i));
/* UGLY */
tdLine.addContent(new ProcessingInstruction(javax.xml.transform.Result.PI_DISABLE_OUTPUT_ESCAPING, ""));
tdLine.addContent(tag("span", " " + line, "class", "code"));
tdLine.addContent(new ProcessingInstruction(javax.xml.transform.Result.PI_ENABLE_OUTPUT_ESCAPING, ""));
List<Result> lineType = types.get(i);
Element tdTypes = emptyTag("td");
tr.addContent(tdTypes);
if (lineType != null) {
Collections.sort(lineType);
boolean first = true;
for (Result result : lineType) {
if (first) {
first = false;
} else {
tdTypes.addContent(", ");
}
String goalFilename = "goals/" + result.uid + ".html";
IType type = result.type;
String label = type.toString().equals("") ? "?" : type.toString();
tdTypes.addContent(link(label, goalFilename));
}
} else {
tdTypes.addContent(" ");
}
i++;
}
String filename = moduleFilename(module);
FileOutputStream out = new FileOutputStream(new File(outPath, filename), false);
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
/* open output file */
outputter.output(doc, out);
}
private Map<Integer, List<Result>> groupResultsByLine(List<Result> results) {
/* group results by line nr */
HashMap<Integer, List<Result>> types = new HashMap<Integer, List<Result>>();
for (Result result : results) {
List<Result> l = types.get(result.node.beginLine);
if (l == null) {
l = new LinkedList<Result>();
types.put(result.node.beginLine, l);
}
l.add(result);
}
return types;
}
private List<Result> parseModule(Module module) {
List<Result> results = new ArrayList<Result>();
Spider spider = new Spider();
spider.run(module);
for (Map.Entry<StructureDefinition, List<exprType>> entry : spider.getTypables().entrySet()) {
StructureDefinition definition = entry.getKey();
List<exprType> expressions = entry.getValue();
for (exprType node : expressions) {
IType type = inferencer.evaluateType(workspace, module, node);
LinkedList<Record> log = logger.getLog();
IGoal rootGoal = logger.getCurrentRootGoal();
Result result = new Result(definition, node, type, rootGoal, log);
results.add(result);
}
}
return results;
}
private String style(File sourceFile) throws IOException {
String[] cmd = {PYTHON, PYGMENTIZE, "-f", "html", "-l", "python", sourceFile.getPath()};
Process formatter = Runtime.getRuntime().exec(cmd);
formatter.getOutputStream();
String formatted = FileUtils.read(formatter.getInputStream());
/* don't ask, don't tell */
return formatted.replaceFirst("^.*?<pre>", "")
.replaceFirst("</pre></div>$", "");
}
private void writeGoalReport(List<Result> results) throws IOException {
for (Result result : results) {
Document doc = createDocument(1, "suboals");
Element root = doc.getRootElement();
Element body = emptyTag("body");
root.addContent(body);
String filename = String.valueOf(result.uid) + ".html";
File file = new File(goalDir, filename);
IGoal rootGoal = result.rootGoal;
// header(writer, 1);
ModuleContext context = rootGoal.getContext();
Element p = emptyTag("p");
body.addContent(p);
printDetail(p, "Root Goal", rootGoal.getClass().getSimpleName());
printDetail(p, "Context", module(context.getModule()));
Element table = emptyTag("table");
body.addContent(table);
Element trHeader = emptyTag("tr");
table.addContent(trHeader);
th(trHeader, "");
th(trHeader, "Action");
th(trHeader, "Parent");
th(trHeader, "ID");
th(trHeader, "Goal");
th(trHeader, "Evaluator");
th(trHeader, "Target");
for (Record log : result.log) {
Element tr = emptyTag("tr");
table.addContent(tr);
td(tr, StringUtils.multiply(log.level, "| "), "code");
td(tr, log.msg);
td(tr, String.valueOf(log.creatorId));
td(tr, String.valueOf(log.id));
td(tr, log.goal.getClass().getSimpleName());
td(tr, log.evaluator.toString());
td(tr, goalDetails(log.goal));
}
FileOutputStream out = new FileOutputStream(file, false);
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
outputter.output(doc, out);
}
}
private Content goalDetails(IGoal goal) {
if (goal instanceof ILocatable) {
Location location = ((ILocatable) goal).getLocation();
Element span = emptyTag("span");
span.addContent(location.node.getClass().getSimpleName() + " ");
span.addContent(linkTo(location));
return span;
} else if (goal instanceof PossibleReferencesGoal) {
PossibleReferencesGoal g = (PossibleReferencesGoal) goal;
return new Text(g.getName());
} else if (goal instanceof ClassAttributeTypeGoal) {
ClassAttributeTypeGoal g = (ClassAttributeTypeGoal) goal;
return linkTo(g.getContext(), g.getClassType().getKlass(), g.getAttributeName());
} else if (goal instanceof AttributeReferencesGoal) {
AttributeReferencesGoal g = (AttributeReferencesGoal) goal;
Attribute attribute = g.getAttribute();
return linkTo(g.getContext(), attribute.getKlass(), attribute.getName());
} else if (goal instanceof PossibleAttributeReferencesGoal) {
PossibleAttributeReferencesGoal g = (PossibleAttributeReferencesGoal) goal;
return new Text(g.getName());
} else {
throw new RuntimeException("Cannot format goal, unknown goal type: " + goal);
}
}
private static String moduleFilename(Module module) {
return module.getNamePath().toString() + ".html";
}
private static Element linkTo(ModuleContext context, Class klass,
String attributeName) {
Location classLocation = new Location(context, klass.getNode());
Element span = emptyTag("span");
span.addContent("Attribute: ");
span.addContent(linkTo(klass.getName(), classLocation));
span.addContent("." + attributeName);
return span;
}
private static Element module(Module module) {
String filename = moduleFilename(module);
return link(module.getNamePath().toString(), "../" + filename);
}
static Element linkTo(String label, Location location) {
String filename = moduleFilename(location.module);
return link(label, "../" + filename + "#" + location.getLineNr());
}
protected static Element linkTo(Location location) {
String label = location.module.getNamePath().toString() + ":" + location.getLineNr();
return linkTo(label, location);
}
private static final class Result implements Comparable<Result> {
private static int currentUid = 0;
public final StructureDefinition definition;
public final SimpleNode node;
public final IType type;
public final LinkedList<Record> log;
public final int uid;
public final IGoal rootGoal;
public Result(StructureDefinition definition, SimpleNode node, IType type, IGoal rootGoal, LinkedList<Record> log) {
this.definition = definition;
this.node = node;
this.type = type;
this.rootGoal = rootGoal;
this.log = log;
this.uid = currentUid;
currentUid++;
}
public int compareTo(Result o) {
return node.beginColumn - o.node.beginColumn;
}
/* hashCode and equals have to implemented if Result objects are stored in certain
* data structures. The Object implementations can't be used as they are not consistent
* with our compareTo implementation.
*/
@Override
public boolean equals(Object obj) {
throw new RuntimeException("not impelemnted");
}
@Override
public int hashCode() {
throw new RuntimeException("not implemented");
}
@Override
public String toString() {
return this.type.toString();
}
}
public static void main(String[] args) throws Exception {
File path = new File("s101g/examples/pydoku/");
TypeAnnotator ta = new TypeAnnotator(path, "out");
ta.generateReport();
}
}
| new source path in the type annotator
| src/ch/hsr/ifs/pystructure/playground/TypeAnnotator.java | new source path in the type annotator | |
Java | unlicense | d39aa21b9e088212e777d5d8bc76c6bd33aee937 | 0 | noritersand/laboratory,noritersand/laboratory,noritersand/laboratory | package laboratory.test.java.lang;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StringTest {
@SuppressWarnings("unused")
private static final Logger log = LoggerFactory.getLogger(StringTest.class);
@Test
public void testAutoNewInstance() {
String a = "a";
String b = "a";
Assert.assertTrue(a == b);
b = a; // new String(a)처럼 명시적으로 새 인스턴스를 할당하지 않아도.
b = "b"; // 리터럴이 바뀌면 참조하고 있는 인스턴스의 값이 변경되는게 아니라 새 인스턴스가 할당된다. (String 타입의 특징)
Assert.assertEquals("a", a); // 그래서 a는 원래의 값을 유지할 수 있다.
}
@Test
public void testBuilder() {
StringBuilder builder = new StringBuilder();
Assert.assertEquals(0, builder.length());
Assert.assertEquals("", builder.toString());
}
@Test
public void testLength() {
String a = "totcnt123\nstart";
String b = "totcnt123start";
Assert.assertEquals(10, a.indexOf("start"));
Assert.assertEquals("start", a.substring(a.indexOf("start"), a.length()));
Assert.assertEquals(9, b.indexOf("start"));
Assert.assertEquals("start", b.substring(b.indexOf("start"), b.length()));
}
@Test
public void testIntern() {
// 아래처럼 초기화될 땐 intern()을 쓰든 안쓰든 String의 주소값은 같다.
String a = "경기";
String b = "경기";
Assert.assertTrue(a == b);
// 요로케 해야됨
String c = "AAA";
String d = new String("AAA");
Assert.assertFalse(c == d);
d = d.intern();
Assert.assertTrue(c == d);
Assert.assertTrue(new String("BBB").intern() == "BBB");
Assert.assertTrue(new String("CCC").intern() == "CCC");
Assert.assertEquals(new String("CCC").intern().hashCode(), "CCC".hashCode());
}
@Test
public void testReplaceAlls() {
Assert.assertEquals("경기", "경기도".replaceAll("도", ""));
Assert.assertEquals("전라", "전라도".replaceAll("도", ""));
Assert.assertEquals("경상", "경상도".replaceAll("도", ""));
}
@Test
public void testDomainSplit() {
Assert.assertEquals(1, "localhost".split("\\.").length);
Assert.assertEquals(3, "master.benecafe.com".split("\\.").length);
Assert.assertEquals(2, "daum.net".split("\\.").length);
}
@Test
public void testSubstring() {
String str = "a234567890b234567890c234567890d234";
Assert.assertEquals(34, str.length());
Assert.assertEquals("a234567890b234567890c234567890", str.substring(0, 30));
Assert.assertEquals(30, str.substring(0, 30).length());
}
@Test
public void testLastIndexOf() {
String str = "/abcd";
Assert.assertEquals(0, str.lastIndexOf("/"));
Assert.assertEquals("abcd", str.substring(str.lastIndexOf("/") + 1));
}
@Test
public void testSplit() {
String str = "abcdefghijklmn";
Assert.assertEquals(str, str.split("\\|")[0]);
}
@Test
public void testSplit2() {
String str = "abcdefghijklmn";
Assert.assertEquals(14, str.length());
Assert.assertEquals(str.substring(1, 5), str.subSequence(1, 5));
}
@Test
public void testSplitByLength1333() {
String str = "00x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 1
str += "01x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 2
str += "02x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 3
str += "03x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 4
str += "04x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 5
str += "05x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 6
str += "06x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 7
str += "07x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 8
str += "08x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 9
str += "09x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 10
str += "10x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 11
str += "11x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 12
str += "12x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 13
str += "13x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 14
str += "14x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "15x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "16x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "17x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "18x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "19x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "20x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "21x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "22x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "23x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "24x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "25x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "26x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "27x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "28x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "29x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "30x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "31x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
// int len = str.length();
String[] strArray = splitByLength1333(str);
// for (String ele : strArray) {
// log.debug(ele);
// }
Assert.assertArrayEquals(strArray, splitByLength(str, 1333));
}
@Test
public void testAbs() {
Assert.assertEquals(0, Math.abs(1000/1333));
Assert.assertEquals(1, Math.abs(1333/1333));
Assert.assertEquals(1, Math.abs(1334/1333));
Assert.assertEquals(1, Math.abs(2665/1333));
Assert.assertEquals(2, Math.abs(2666/1333));
Assert.assertEquals(2, Math.abs(2667/1333));
}
@Test
public void testSplitByLength() {
Assert.assertArrayEquals(new String[] { "abc", "def" }, splitByLength("abcdef", 3));
Assert.assertArrayEquals(new String[] { "abc", "def", "ef" }, splitByLength("abcdefef", 3));
Assert.assertArrayEquals(new String[] { "abcd", "ef12", "34" }, splitByLength("abcdef1234", 4));
Assert.assertArrayEquals(new String[] { "abcde", "f1234", "5" }, splitByLength("abcdef12345", 5));
}
public static String[] splitByLength1333(String str) {
return splitByLength(str, 1333);
}
public static String[] splitByLength(String str, int splitLength) {
if (str == null) {
return null;
}
int strLen = str.length();
int arrayLength = Math.abs(strLen / splitLength) + (strLen % splitLength != 0 ? 1 : 0);
String[] strArray = null;
if (arrayLength == 0) {
return new String[] { str };
} else {
strArray = new String[arrayLength];
}
String temp = "";
for (int i = 0; i < arrayLength; i++) {
if (str.length() > splitLength) {
strArray[i] = str.substring(0, splitLength);
temp = str.substring(splitLength, str.length());
} else {
strArray[i] = str.substring(0, str.length());
}
str = temp;
}
return strArray;
}
}
| src/test/java/laboratory/test/java/lang/StringTest.java | package laboratory.test.java.lang;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StringTest {
@SuppressWarnings("unused")
private static final Logger log = LoggerFactory.getLogger(StringTest.class);
@Test
public void testAutoNewInstance() {
String a = "a";
String b = "a";
Assert.assertTrue(a == b);
b = a; // new String(a)처럼 명시적으로 새 인스턴스를 할당하지 않아도.
b = "b"; // 리터럴이 바뀌면 참조하고 있는 인스턴스의 값이 변경되는게 아니라 새 인스턴스가 할당된다. (String 타입의 특징)
Assert.assertEquals("a", a); // 그래서 a는 원래의 값을 유지할 수 있다.
}
@Test
public void testBuilder() {
StringBuilder builder = new StringBuilder();
Assert.assertEquals(0, builder.length());
Assert.assertEquals("", builder.toString());
}
@Test
public void testLength() {
String a = "totcnt123\nstart";
String b = "totcnt123start";
Assert.assertEquals(10, a.indexOf("start"));
Assert.assertEquals("start", a.substring(a.indexOf("start"), a.length()));
Assert.assertEquals(9, b.indexOf("start"));
Assert.assertEquals("start", b.substring(b.indexOf("start"), b.length()));
}
@Test
public void testIntern() {
// 아래처럼 초기화될 땐 intern()을 쓰든 안쓰든 String의 주소값은 같다.
String a = "경기";
String b = "경기";
Assert.assertTrue(a == b);
// 요로케 해야됨
String c = "AAA";
String d = new String("AAA");
Assert.assertFalse(c == d);
d = d.intern();
Assert.assertTrue(c == d);
Assert.assertTrue(new String("BBB").intern() == "BBB");
Assert.assertTrue(new String("CCC").intern() == "CCC");
Assert.assertEquals(new String("CCC").intern().hashCode(), "CCC".hashCode());
}
@Test
public void testReplaceAlls() {
Assert.assertEquals("경기", "경기도".replaceAll("도", ""));
Assert.assertEquals("전라", "전라도".replaceAll("도", ""));
Assert.assertEquals("경상", "경상도".replaceAll("도", ""));
}
@Test
public void testDomainSplit() {
Assert.assertEquals(1, "localhost".split("\\.").length);
Assert.assertEquals(3, "master.benecafe.com".split("\\.").length);
Assert.assertEquals(2, "daum.net".split("\\.").length);
}
@Test
public void testSubstring() {
String str = "a234567890b234567890c234567890d234";
Assert.assertEquals(34, str.length());
Assert.assertEquals("a234567890b234567890c234567890", str.substring(0, 30));
Assert.assertEquals(30, str.substring(0, 30).length());
}
@Test
public void testLastIndexOf() {
String str = "/abcd";
Assert.assertEquals(0, str.lastIndexOf("/"));
Assert.assertEquals("abcd", str.substring(str.lastIndexOf("/") + 1));
}
@Test
public void testSplit() {
String str = "abcdefghijklmn";
Assert.assertEquals(str, str.split("\\|")[0]);
}
@Test
public void testSplit2() {
String str = "abcdefghijklmn";
Assert.assertEquals(14, str.length());
Assert.assertEquals(str.substring(1, 5), str.subSequence(1, 5));
}
@Test
public void testSplitByLength1333() {
String str = "00x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 1
str += "01x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 2
str += "02x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 3
str += "03x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 4
str += "04x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 5
str += "05x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 6
str += "06x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 7
str += "07x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 8
str += "08x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 9
str += "09x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 10
str += "10x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 11
str += "11x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 12
str += "12x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 13
str += "13x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000"; // 14
str += "14x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "15x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "16x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "17x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "18x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "19x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "20x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "21x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "22x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "23x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "24x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "25x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "26x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "27x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "28x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "29x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "30x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
str += "31x1111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000";
// int len = str.length();
String[] strArray = splitByLength1333(str);
// for (String ele : strArray) {
// log.debug(ele);
// }
Assert.assertArrayEquals(strArray, splitByLength(str, 1333));
}
@Test
public void testAbs() {
Assert.assertEquals(0, Math.abs(1000/1333));
Assert.assertEquals(1, Math.abs(1333/1333));
Assert.assertEquals(1, Math.abs(1334/1333));
Assert.assertEquals(1, Math.abs(2665/1333));
Assert.assertEquals(2, Math.abs(2666/1333));
Assert.assertEquals(2, Math.abs(2667/1333));
}
@Test
public void testSplitByLength() {
Assert.assertArrayEquals(new String[] { "abc", "def" }, splitByLength("abcdef", 3));
Assert.assertArrayEquals(new String[] { "abc", "def", "ef" }, splitByLength("abcdefef", 3));
Assert.assertArrayEquals(new String[] { "abcd", "ef12", "34" }, splitByLength("abcdef1234", 4));
Assert.assertArrayEquals(new String[] { "abcde", "f1234", "5" }, splitByLength("abcdef12345", 5));
}
public static String[] splitByLength1333(String str) {
return splitByLength(str, 1333);
}
public static String[] splitByLength(String str, int splitLength) {
if (str == null) {
return null;
}
int strLen = str.length();
int arrayLength = Math.abs(strLen / splitLength) + (strLen % splitLength != 0 ? 1 : 0);
String[] strArray = null;
if (arrayLength == 0) {
return new String[] { str };
} else {
strArray = new String[arrayLength];
}
String temp = "";
for (int i = 0; i < arrayLength; i++) {
if (str.length() > splitLength) {
strArray[i] = str.substring(0, splitLength);
temp = str.substring(splitLength, str.length());
} else {
strArray[i] = str.substring(0, str.length());
}
str = temp;
}
return strArray;
}
}
| two factor auth test | src/test/java/laboratory/test/java/lang/StringTest.java | two factor auth test | |
Java | apache-2.0 | 7bba7104e74161abc1aec2a6a24fd8d255a290dd | 0 | wouterv/orientdb,intfrr/orientdb,joansmith/orientdb,giastfader/orientdb,giastfader/orientdb,allanmoso/orientdb,intfrr/orientdb,alonsod86/orientdb,intfrr/orientdb,alonsod86/orientdb,sanyaade-g2g-repos/orientdb,rprabhat/orientdb,jdillon/orientdb,rprabhat/orientdb,tempbottle/orientdb,allanmoso/orientdb,orientechnologies/orientdb,tempbottle/orientdb,mbhulin/orientdb,joansmith/orientdb,orientechnologies/orientdb,wouterv/orientdb,wyzssw/orientdb,wouterv/orientdb,orientechnologies/orientdb,intfrr/orientdb,joansmith/orientdb,mbhulin/orientdb,mmacfadden/orientdb,allanmoso/orientdb,alonsod86/orientdb,cstamas/orientdb,wyzssw/orientdb,allanmoso/orientdb,tempbottle/orientdb,joansmith/orientdb,cstamas/orientdb,mmacfadden/orientdb,mbhulin/orientdb,wyzssw/orientdb,rprabhat/orientdb,giastfader/orientdb,mmacfadden/orientdb,sanyaade-g2g-repos/orientdb,tempbottle/orientdb,wouterv/orientdb,wyzssw/orientdb,sanyaade-g2g-repos/orientdb,giastfader/orientdb,jdillon/orientdb,rprabhat/orientdb,orientechnologies/orientdb,sanyaade-g2g-repos/orientdb,cstamas/orientdb,mmacfadden/orientdb,cstamas/orientdb,mbhulin/orientdb,jdillon/orientdb,alonsod86/orientdb | /*
* Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.com)
*
* 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.orientechnologies.orient.core.index;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import com.orientechnologies.common.collection.OMultiCollectionIterator;
import com.orientechnologies.common.comparator.ODefaultComparator;
import com.orientechnologies.common.concur.resource.OSharedResourceIterator;
import com.orientechnologies.common.listener.OProgressListener;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerListRID;
import com.orientechnologies.orient.core.type.tree.OMVRBTreeRIDSet;
/**
* Abstract index implementation that supports multi-values for the same key.
*
* @author Luca Garulli
*
*/
public abstract class OIndexMultiValues extends OIndexAbstract<Set<OIdentifiable>> {
public OIndexMultiValues(final String type, OIndexEngine<Set<OIdentifiable>> indexEngine) {
super(type, indexEngine);
}
public Set<OIdentifiable> get(final Object key) {
checkForRebuild();
acquireSharedLock();
try {
final OMVRBTreeRIDSet values = (OMVRBTreeRIDSet) indexEngine.get(key);
if (values == null)
return Collections.emptySet();
return new HashSet<OIdentifiable>(values);
} finally {
releaseSharedLock();
}
}
public long count(final Object key) {
checkForRebuild();
acquireSharedLock();
try {
final OMVRBTreeRIDSet values = (OMVRBTreeRIDSet) indexEngine.get(key);
if (values == null)
return 0;
return values.size();
} finally {
releaseSharedLock();
}
}
public OIndexMultiValues put(final Object key, final OIdentifiable iSingleValue) {
checkForRebuild();
modificationLock.requestModificationLock();
try {
acquireExclusiveLock();
try {
checkForKeyType(key);
Set<OIdentifiable> values = indexEngine.get(key);
if (values == null) {
values = new OMVRBTreeRIDSet(OGlobalConfiguration.MVRBTREE_RID_BINARY_THRESHOLD.getValueAsInteger());
((OMVRBTreeRIDSet) values).setAutoConvertToRecord(false);
}
if (!iSingleValue.getIdentity().isValid())
((ORecord<?>) iSingleValue).save();
values.add(iSingleValue.getIdentity());
indexEngine.put(key, values);
return this;
} finally {
releaseExclusiveLock();
}
} finally {
modificationLock.releaseModificationLock();
}
}
public int remove(final OIdentifiable iRecord) {
checkForRebuild();
acquireExclusiveLock();
try {
return indexEngine.removeValue(iRecord, MultiValuesTransformer.INSTANCE);
} finally {
releaseExclusiveLock();
}
}
@Override
public boolean remove(final Object key, final OIdentifiable value) {
checkForRebuild();
modificationLock.requestModificationLock();
try {
acquireExclusiveLock();
try {
Set<OIdentifiable> recs = indexEngine.get(key);
if (recs == null)
return false;
if (recs.remove(value)) {
if (recs.isEmpty())
indexEngine.remove(key);
else
indexEngine.put(key, recs);
return true;
}
return false;
} finally {
releaseExclusiveLock();
}
} finally {
modificationLock.releaseModificationLock();
}
}
public OIndexMultiValues create(final String name, final OIndexDefinition indexDefinition, final String clusterIndexName,
final Set<String> clustersToIndex, boolean rebuild, final OProgressListener progressListener) {
return (OIndexMultiValues) super.create(name, indexDefinition, clusterIndexName, clustersToIndex, rebuild, progressListener,
OStreamSerializerListRID.INSTANCE);
}
public Collection<OIdentifiable> getValuesBetween(final Object rangeFrom, final boolean fromInclusive, final Object rangeTo,
final boolean toInclusive, final int maxValuesToFetch) {
checkForRebuild();
acquireSharedLock();
try {
return indexEngine.getValuesBetween(rangeFrom, fromInclusive, rangeTo, toInclusive, maxValuesToFetch,
MultiValuesTransformer.INSTANCE);
} finally {
releaseSharedLock();
}
}
public Collection<OIdentifiable> getValuesMajor(final Object fromKey, final boolean isInclusive, final int maxValuesToFetch) {
checkForRebuild();
acquireSharedLock();
try {
return indexEngine.getValuesMajor(fromKey, isInclusive, maxValuesToFetch, MultiValuesTransformer.INSTANCE);
} finally {
releaseSharedLock();
}
}
public Collection<OIdentifiable> getValuesMinor(final Object toKey, final boolean isInclusive, final int maxValuesToFetch) {
checkForRebuild();
acquireSharedLock();
try {
return indexEngine.getValuesMinor(toKey, isInclusive, maxValuesToFetch, MultiValuesTransformer.INSTANCE);
} finally {
releaseSharedLock();
}
}
public Collection<OIdentifiable> getValues(final Collection<?> iKeys, final int maxValuesToFetch) {
checkForRebuild();
final List<Object> sortedKeys = new ArrayList<Object>(iKeys);
Collections.sort(sortedKeys, ODefaultComparator.INSTANCE);
acquireSharedLock();
try {
final Set<OIdentifiable> result = new HashSet<OIdentifiable>();
for (final Object key : sortedKeys) {
final OMVRBTreeRIDSet values = (OMVRBTreeRIDSet) indexEngine.get(key);
if (values == null)
continue;
if (!values.isEmpty()) {
for (final OIdentifiable value : values) {
if (maxValuesToFetch > -1 && maxValuesToFetch == result.size())
return result;
result.add(value);
}
}
}
return result;
} finally {
releaseSharedLock();
}
}
public Collection<ODocument> getEntriesMajor(final Object fromKey, final boolean isInclusive, final int maxEntriesToFetch) {
checkForRebuild();
acquireSharedLock();
try {
return indexEngine.getEntriesMajor(fromKey, isInclusive, maxEntriesToFetch, MultiValuesTransformer.INSTANCE);
} finally {
releaseSharedLock();
}
}
public Collection<ODocument> getEntriesMinor(Object toKey, boolean isInclusive, int maxEntriesToFetch) {
checkForRebuild();
acquireSharedLock();
try {
return indexEngine.getEntriesMinor(toKey, isInclusive, maxEntriesToFetch, MultiValuesTransformer.INSTANCE);
} finally {
releaseSharedLock();
}
}
public Collection<ODocument> getEntriesBetween(Object rangeFrom, Object rangeTo, boolean inclusive, int maxEntriesToFetch) {
checkForRebuild();
final OType[] types = getDefinition().getTypes();
if (types.length == 1) {
rangeFrom = OType.convert(rangeFrom, types[0].getDefaultJavaType());
rangeTo = OType.convert(rangeTo, types[0].getDefaultJavaType());
}
acquireSharedLock();
try {
return indexEngine.getEntriesBetween(rangeFrom, rangeTo, inclusive, maxEntriesToFetch, MultiValuesTransformer.INSTANCE);
} finally {
releaseSharedLock();
}
}
public long count(Object rangeFrom, final boolean fromInclusive, Object rangeTo, final boolean toInclusive,
final int maxValuesToFetch) {
checkForRebuild();
final OType[] types = getDefinition().getTypes();
if (types.length == 1) {
rangeFrom = OType.convert(rangeFrom, types[0].getDefaultJavaType());
rangeTo = OType.convert(rangeTo, types[0].getDefaultJavaType());
}
if (rangeFrom != null && rangeTo != null && rangeFrom.getClass() != rangeTo.getClass())
throw new IllegalArgumentException("Range from-to parameters are of different types");
acquireSharedLock();
try {
return indexEngine.count(rangeFrom, fromInclusive, rangeTo, toInclusive, maxValuesToFetch, MultiValuesTransformer.INSTANCE);
} finally {
releaseSharedLock();
}
}
public Collection<ODocument> getEntries(Collection<?> iKeys, int maxEntriesToFetch) {
checkForRebuild();
final List<Object> sortedKeys = new ArrayList<Object>(iKeys);
Collections.sort(sortedKeys, ODefaultComparator.INSTANCE);
acquireSharedLock();
try {
final Set<ODocument> result = new ODocumentFieldsHashSet();
for (final Object key : sortedKeys) {
final OMVRBTreeRIDSet values = (OMVRBTreeRIDSet) indexEngine.get(key);
if (values == null)
continue;
if (!values.isEmpty()) {
for (final OIdentifiable value : values) {
if (maxEntriesToFetch > -1 && maxEntriesToFetch == result.size())
return result;
final ODocument document = new ODocument();
document.field("key", key);
document.field("rid", value.getIdentity());
document.unsetDirty();
result.add(document);
}
}
}
return result;
} finally {
releaseSharedLock();
}
}
public long getSize() {
checkForRebuild();
acquireSharedLock();
try {
return indexEngine.size(MultiValuesTransformer.INSTANCE);
} finally {
releaseSharedLock();
}
}
public long getKeySize() {
checkForRebuild();
acquireSharedLock();
try {
return indexEngine.size(null);
} finally {
releaseSharedLock();
}
}
public Iterator<OIdentifiable> valuesIterator() {
checkForRebuild();
acquireSharedLock();
try {
return new OSharedResourceIterator<OIdentifiable>(this, new OMultiCollectionIterator<OIdentifiable>(
indexEngine.valuesIterator()));
} finally {
releaseSharedLock();
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public Iterator<OIdentifiable> valuesInverseIterator() {
checkForRebuild();
acquireSharedLock();
try {
return new OSharedResourceIterator(this, new OMultiCollectionIterator<OIdentifiable>(indexEngine.inverseValuesIterator()));
} finally {
releaseSharedLock();
}
}
private static final class MultiValuesTransformer implements OIndexEngine.ValuesTransformer<Set<OIdentifiable>> {
private static final MultiValuesTransformer INSTANCE = new MultiValuesTransformer();
@Override
public Collection<OIdentifiable> transformFromValue(Set<OIdentifiable> value) {
return value;
}
@Override
public Set<OIdentifiable> transformToValue(Collection<OIdentifiable> collection) {
return (Set<OIdentifiable>) collection;
}
}
}
| core/src/main/java/com/orientechnologies/orient/core/index/OIndexMultiValues.java | /*
* Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.com)
*
* 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.orientechnologies.orient.core.index;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import com.orientechnologies.common.collection.OMultiCollectionIterator;
import com.orientechnologies.common.comparator.ODefaultComparator;
import com.orientechnologies.common.concur.resource.OSharedResourceIterator;
import com.orientechnologies.common.listener.OProgressListener;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerListRID;
import com.orientechnologies.orient.core.type.tree.OMVRBTreeRIDSet;
/**
* Abstract index implementation that supports multi-values for the same key.
*
* @author Luca Garulli
*
*/
public abstract class OIndexMultiValues extends OIndexAbstract<Set<OIdentifiable>> {
public OIndexMultiValues(final String type, OIndexEngine<Set<OIdentifiable>> indexEngine) {
super(type, indexEngine);
}
public Set<OIdentifiable> get(final Object key) {
checkForRebuild();
acquireSharedLock();
try {
final OMVRBTreeRIDSet values = (OMVRBTreeRIDSet) indexEngine.get(key);
if (values == null)
return Collections.emptySet();
return new HashSet<OIdentifiable>(values);
} finally {
releaseSharedLock();
}
}
public long count(final Object key) {
checkForRebuild();
acquireSharedLock();
try {
final OMVRBTreeRIDSet values = (OMVRBTreeRIDSet) indexEngine.get(key);
if (values == null)
return 0;
return values.size();
} finally {
releaseSharedLock();
}
}
public OIndexMultiValues put(final Object key, final OIdentifiable iSingleValue) {
checkForRebuild();
modificationLock.requestModificationLock();
try {
acquireExclusiveLock();
try {
checkForKeyType(key);
Set<OIdentifiable> values = indexEngine.get(key);
if (values == null) {
values = new OMVRBTreeRIDSet(8);
((OMVRBTreeRIDSet) values).setAutoConvertToRecord(false);
}
if (!iSingleValue.getIdentity().isValid())
((ORecord<?>) iSingleValue).save();
values.add(iSingleValue.getIdentity());
indexEngine.put(key, values);
return this;
} finally {
releaseExclusiveLock();
}
} finally {
modificationLock.releaseModificationLock();
}
}
public int remove(final OIdentifiable iRecord) {
checkForRebuild();
acquireExclusiveLock();
try {
return indexEngine.removeValue(iRecord, MultiValuesTransformer.INSTANCE);
} finally {
releaseExclusiveLock();
}
}
@Override
public boolean remove(final Object key, final OIdentifiable value) {
checkForRebuild();
modificationLock.requestModificationLock();
try {
acquireExclusiveLock();
try {
Set<OIdentifiable> recs = indexEngine.get(key);
if (recs == null)
return false;
if (recs.remove(value)) {
if (recs.isEmpty())
indexEngine.remove(key);
else
indexEngine.put(key, recs);
return true;
}
return false;
} finally {
releaseExclusiveLock();
}
} finally {
modificationLock.releaseModificationLock();
}
}
public OIndexMultiValues create(final String name, final OIndexDefinition indexDefinition, final String clusterIndexName,
final Set<String> clustersToIndex, boolean rebuild, final OProgressListener progressListener) {
return (OIndexMultiValues) super.create(name, indexDefinition, clusterIndexName, clustersToIndex, rebuild, progressListener,
OStreamSerializerListRID.INSTANCE);
}
public Collection<OIdentifiable> getValuesBetween(final Object rangeFrom, final boolean fromInclusive, final Object rangeTo,
final boolean toInclusive, final int maxValuesToFetch) {
checkForRebuild();
acquireSharedLock();
try {
return indexEngine.getValuesBetween(rangeFrom, fromInclusive, rangeTo, toInclusive, maxValuesToFetch,
MultiValuesTransformer.INSTANCE);
} finally {
releaseSharedLock();
}
}
public Collection<OIdentifiable> getValuesMajor(final Object fromKey, final boolean isInclusive, final int maxValuesToFetch) {
checkForRebuild();
acquireSharedLock();
try {
return indexEngine.getValuesMajor(fromKey, isInclusive, maxValuesToFetch, MultiValuesTransformer.INSTANCE);
} finally {
releaseSharedLock();
}
}
public Collection<OIdentifiable> getValuesMinor(final Object toKey, final boolean isInclusive, final int maxValuesToFetch) {
checkForRebuild();
acquireSharedLock();
try {
return indexEngine.getValuesMinor(toKey, isInclusive, maxValuesToFetch, MultiValuesTransformer.INSTANCE);
} finally {
releaseSharedLock();
}
}
public Collection<OIdentifiable> getValues(final Collection<?> iKeys, final int maxValuesToFetch) {
checkForRebuild();
final List<Object> sortedKeys = new ArrayList<Object>(iKeys);
Collections.sort(sortedKeys, ODefaultComparator.INSTANCE);
acquireSharedLock();
try {
final Set<OIdentifiable> result = new HashSet<OIdentifiable>();
for (final Object key : sortedKeys) {
final OMVRBTreeRIDSet values = (OMVRBTreeRIDSet) indexEngine.get(key);
if (values == null)
continue;
if (!values.isEmpty()) {
for (final OIdentifiable value : values) {
if (maxValuesToFetch > -1 && maxValuesToFetch == result.size())
return result;
result.add(value);
}
}
}
return result;
} finally {
releaseSharedLock();
}
}
public Collection<ODocument> getEntriesMajor(final Object fromKey, final boolean isInclusive, final int maxEntriesToFetch) {
checkForRebuild();
acquireSharedLock();
try {
return indexEngine.getEntriesMajor(fromKey, isInclusive, maxEntriesToFetch, MultiValuesTransformer.INSTANCE);
} finally {
releaseSharedLock();
}
}
public Collection<ODocument> getEntriesMinor(Object toKey, boolean isInclusive, int maxEntriesToFetch) {
checkForRebuild();
acquireSharedLock();
try {
return indexEngine.getEntriesMinor(toKey, isInclusive, maxEntriesToFetch, MultiValuesTransformer.INSTANCE);
} finally {
releaseSharedLock();
}
}
public Collection<ODocument> getEntriesBetween(Object rangeFrom, Object rangeTo, boolean inclusive, int maxEntriesToFetch) {
checkForRebuild();
final OType[] types = getDefinition().getTypes();
if (types.length == 1) {
rangeFrom = OType.convert(rangeFrom, types[0].getDefaultJavaType());
rangeTo = OType.convert(rangeTo, types[0].getDefaultJavaType());
}
acquireSharedLock();
try {
return indexEngine.getEntriesBetween(rangeFrom, rangeTo, inclusive, maxEntriesToFetch, MultiValuesTransformer.INSTANCE);
} finally {
releaseSharedLock();
}
}
public long count(Object rangeFrom, final boolean fromInclusive, Object rangeTo, final boolean toInclusive,
final int maxValuesToFetch) {
checkForRebuild();
final OType[] types = getDefinition().getTypes();
if (types.length == 1) {
rangeFrom = OType.convert(rangeFrom, types[0].getDefaultJavaType());
rangeTo = OType.convert(rangeTo, types[0].getDefaultJavaType());
}
if (rangeFrom != null && rangeTo != null && rangeFrom.getClass() != rangeTo.getClass())
throw new IllegalArgumentException("Range from-to parameters are of different types");
acquireSharedLock();
try {
return indexEngine.count(rangeFrom, fromInclusive, rangeTo, toInclusive, maxValuesToFetch, MultiValuesTransformer.INSTANCE);
} finally {
releaseSharedLock();
}
}
public Collection<ODocument> getEntries(Collection<?> iKeys, int maxEntriesToFetch) {
checkForRebuild();
final List<Object> sortedKeys = new ArrayList<Object>(iKeys);
Collections.sort(sortedKeys, ODefaultComparator.INSTANCE);
acquireSharedLock();
try {
final Set<ODocument> result = new ODocumentFieldsHashSet();
for (final Object key : sortedKeys) {
final OMVRBTreeRIDSet values = (OMVRBTreeRIDSet) indexEngine.get(key);
if (values == null)
continue;
if (!values.isEmpty()) {
for (final OIdentifiable value : values) {
if (maxEntriesToFetch > -1 && maxEntriesToFetch == result.size())
return result;
final ODocument document = new ODocument();
document.field("key", key);
document.field("rid", value.getIdentity());
document.unsetDirty();
result.add(document);
}
}
}
return result;
} finally {
releaseSharedLock();
}
}
public long getSize() {
checkForRebuild();
acquireSharedLock();
try {
return indexEngine.size(MultiValuesTransformer.INSTANCE);
} finally {
releaseSharedLock();
}
}
public long getKeySize() {
checkForRebuild();
acquireSharedLock();
try {
return indexEngine.size(null);
} finally {
releaseSharedLock();
}
}
public Iterator<OIdentifiable> valuesIterator() {
checkForRebuild();
acquireSharedLock();
try {
return new OSharedResourceIterator<OIdentifiable>(this, new OMultiCollectionIterator<OIdentifiable>(
indexEngine.valuesIterator()));
} finally {
releaseSharedLock();
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public Iterator<OIdentifiable> valuesInverseIterator() {
checkForRebuild();
acquireSharedLock();
try {
return new OSharedResourceIterator(this, new OMultiCollectionIterator<OIdentifiable>(indexEngine.inverseValuesIterator()));
} finally {
releaseSharedLock();
}
}
private static final class MultiValuesTransformer implements OIndexEngine.ValuesTransformer<Set<OIdentifiable>> {
private static final MultiValuesTransformer INSTANCE = new MultiValuesTransformer();
@Override
public Collection<OIdentifiable> transformFromValue(Set<OIdentifiable> value) {
return value;
}
@Override
public Set<OIdentifiable> transformToValue(Collection<OIdentifiable> collection) {
return (Set<OIdentifiable>) collection;
}
}
}
| Fixed bug on MVRB-Tree-RID-Set built with default 8 items as threshold instead of reading the configuration
| core/src/main/java/com/orientechnologies/orient/core/index/OIndexMultiValues.java | Fixed bug on MVRB-Tree-RID-Set built with default 8 items as threshold instead of reading the configuration | |
Java | apache-2.0 | e2f5eb0d0d1e4e215cb0a354e6062e2e195708f5 | 0 | apache/felix-dev,apache/felix-dev,apache/felix-dev,apache/felix-dev | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.felix.ipojo.architecture;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Properties;
import org.apache.felix.ipojo.Factory;
import org.apache.felix.ipojo.IPojoFactory;
import org.apache.felix.ipojo.metadata.Attribute;
import org.apache.felix.ipojo.metadata.Element;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.service.cm.ManagedServiceFactory;
/**
* Component Type description.
* @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
*/
public class ComponentTypeDescription {
/**
* Provided service by the component type.
*/
private String[] m_providedServiceSpecification = new String[0];
/**
* Configuration Properties accepted by the component type.
*/
private PropertyDescription[] m_properties = new PropertyDescription[0];
/*
* Used by custom handlers to keep and retrieve custom info.
*/
private Dictionary m_handlerInfoSlot = new Hashtable();
/**
* Represented factory.
*/
private final IPojoFactory m_factory;
/**
* Constructor.
* @param factory : represented factory.
*/
public ComponentTypeDescription(IPojoFactory factory) {
m_factory = factory;
}
/**
* Gets the attached factory.
* @return the factory
*/
public IPojoFactory getFactory() {
return m_factory;
}
/**
* Gets a printable form of the current component type description.
* @return printable form of the component type description
* @see java.lang.Object#toString()
*/
public String toString() {
return getDescription().toString();
}
/**
* Gets the implementation class of this component type.
* @return the component type implementation class name.
* @deprecated
*/
public String getClassName() {
return m_factory.getClassName();
}
/**
* Gets the component type version.
* @return the component type version or
* <code>null</code> if not set.
*/
public String getVersion() {
return m_factory.getVersion();
}
/**
* Gets component-type properties.
* @return the list of configuration properties accepted by the component type type.
*/
public PropertyDescription[] getProperties() {
return m_properties;
}
/**
* Adds a String property in the component type.
* @param name : property name.
* @param value : property value.
*/
public void addProperty(String name, String value) {
addProperty(name, value, false);
}
/**
* Adds a String property in the component type.
* @param name : property name.
* @param value : property value.
* @param immutable : the property is immutable.
*/
public void addProperty(String name, String value, boolean immutable) {
PropertyDescription prop = new PropertyDescription(name, String.class.getName(), value);
addProperty(prop);
}
/**
* Adds a configuration properties to the component type.
* @param pd : the property to add
*/
public void addProperty(PropertyDescription pd) { //NOPMD remove the instance name of the 'name' property.
String name = pd.getName();
// Check if the property is not already in the array
for (int i = 0; i < m_properties.length; i++) {
PropertyDescription desc = m_properties[i];
if (desc.getName().equals(name)) { return; }
}
PropertyDescription[] newProps = new PropertyDescription[m_properties.length + 1];
System.arraycopy(m_properties, 0, newProps, 0, m_properties.length);
newProps[m_properties.length] = pd;
m_properties = newProps;
}
/**
* Adds the HandlerInfo for specified handler.
* @param handlerNs Handler's namespace
* @param handlerName Handler's name
* @param info HandlerInfo associated with the given custom handler.
*/
public void setHandlerInfo(String handlerNs, String handlerName, CustomHandlerInfo info)
{
String fullHandlerName = handlerNs + ":" + handlerName;
if(info == null)
{
m_handlerInfoSlot.remove(fullHandlerName);
}
else
{
m_handlerInfoSlot.put(fullHandlerName, info);
}
}
public CustomHandlerInfo getHandlerInfo(String handlerNs, String handlerName)
{
String fullHandlerName = handlerNs + ":" + handlerName;
return (CustomHandlerInfo)m_handlerInfoSlot.get(fullHandlerName);
}
/**
* Gets the list of provided service offered by instances of this type.
* @return the list of the provided service.
*/
public String[] getprovidedServiceSpecification() {
return m_providedServiceSpecification;
}
/**
* Adds a provided service to the component type.
* @param serviceSpecification : the provided service to add (interface name)
*/
public void addProvidedServiceSpecification(String serviceSpecification) {
String[] newSs = new String[m_providedServiceSpecification.length + 1];
System.arraycopy(m_providedServiceSpecification, 0, newSs, 0, m_providedServiceSpecification.length);
newSs[m_providedServiceSpecification.length] = serviceSpecification;
m_providedServiceSpecification = newSs;
}
/**
* Returns the component-type name.
* @return the name of this component type
*/
public String getName() {
return m_factory.getName();
}
/**
* Computes the default service properties to publish :
* factory.name, service.pid, component.providedServiceSpecification, component.properties, component.description, factory.State.
* @return : the dictionary of properties to publish.
*/
public Dictionary getPropertiesToPublish() {
Properties props = new Properties();
props.put("factory.name", m_factory.getName());
props.put(Constants.SERVICE_PID, m_factory.getName()); // Service PID is required for the integration in the configuration admin.
// Add the version if set
String v = getVersion();
if (v != null) {
props.put("factory.version", v);
}
props.put("component.providedServiceSpecifications", m_providedServiceSpecification);
props.put("component.properties", m_properties);
props.put("component.description", this);
// add every immutable property
for (int i = 0; i < m_properties.length; i++) {
if (m_properties[i].isImmutable() && m_properties[i].getValue() != null) {
props.put(m_properties[i].getName(), m_properties[i].getObjectValue(m_factory.getBundleContext()));
}
}
// Add factory state
props.put("factory.state", new Integer(m_factory.getState()));
return props;
}
/**
* Gets the interfaces published by the factory.
* By default publish both {@link Factory} and {@link ManagedServiceFactory}.
* @return : the list of interface published by the factory.
*/
public String[] getFactoryInterfacesToPublish() {
return new String[] {Factory.class.getName(), ManagedServiceFactory.class.getName()};
}
/**
* Gets the component type description.
* @return : the description
*/
public Element getDescription() {
Element desc = new Element("Factory", "");
desc.addAttribute(new Attribute("name", m_factory.getName()));
desc.addAttribute(
new Attribute("bundle",
Long.toString(m_factory.getBundleContext().getBundle().getBundleId())));
String state = "valid";
if (m_factory.getState() == Factory.INVALID) {
state = "invalid";
}
desc.addAttribute(new Attribute("state", state));
// Display required & missing handlers
Element req = new Element("RequiredHandlers", "");
req.addAttribute(new Attribute("list", m_factory.getRequiredHandlers().toString()));
Element missing = new Element("MissingHandlers", "");
missing.addAttribute(new Attribute("list", m_factory.getMissingHandlers().toString()));
desc.addElement(req);
desc.addElement(missing);
for (int i = 0; i < m_providedServiceSpecification.length; i++) {
Element prov = new Element("provides", "");
prov.addAttribute(new Attribute("specification", m_providedServiceSpecification[i]));
desc.addElement(prov);
}
for (int i = 0; i < m_properties.length; i++) {
Element prop = new Element("property", "");
prop.addAttribute(new Attribute("name", m_properties[i].getName()));
prop.addAttribute(new Attribute("type", m_properties[i].getType()));
if (m_properties[i].isMandatory() && m_properties[i].getValue() == null) {
prop.addAttribute(new Attribute("value", "REQUIRED"));
} else {
prop.addAttribute(new Attribute("value", m_properties[i].getValue()));
}
desc.addElement(prop);
}
if(m_handlerInfoSlot.size() > 0)
{
Enumeration keys = m_handlerInfoSlot.keys();
while(keys.hasMoreElements())
{
String fullHandlerName = (String) keys.nextElement();
CustomHandlerInfo handlerInfo = (CustomHandlerInfo)m_handlerInfoSlot.get(fullHandlerName);
desc.addElement( handlerInfo.getDescription() );
}
}
return desc;
}
public BundleContext getBundleContext() {
return m_factory.getBundleContext();
}
}
| ipojo/runtime/core/src/main/java/org/apache/felix/ipojo/architecture/ComponentTypeDescription.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.felix.ipojo.architecture;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Properties;
import org.apache.felix.ipojo.ComponentFactory;
import org.apache.felix.ipojo.Factory;
import org.apache.felix.ipojo.IPojoFactory;
import org.apache.felix.ipojo.metadata.Attribute;
import org.apache.felix.ipojo.metadata.Element;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.service.cm.ManagedServiceFactory;
/**
* Component Type description.
* @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
*/
public class ComponentTypeDescription {
/**
* Provided service by the component type.
*/
private String[] m_providedServiceSpecification = new String[0];
/**
* Configuration Properties accepted by the component type.
*/
private PropertyDescription[] m_properties = new PropertyDescription[0];
/*
* Used by custom handlers to keep and retrieve custom info.
*/
private Dictionary m_handlerInfoSlot = new Hashtable();
/**
* Represented factory.
*/
private final IPojoFactory m_factory;
/**
* Constructor.
* @param factory : represented factory.
*/
public ComponentTypeDescription(IPojoFactory factory) {
m_factory = factory;
}
/**
* Gets the attached factory.
* @return the factory
*/
public IPojoFactory getFactory() {
return m_factory;
}
/**
* Gets a printable form of the current component type description.
* @return printable form of the component type description
* @see java.lang.Object#toString()
*/
public String toString() {
return getDescription().toString();
}
/**
* Gets the implementation class of this component type.
* @return the component type implementation class name.
* @deprecated
*/
public String getClassName() {
return m_factory.getClassName();
}
/**
* Gets the component type version.
* @return the component type version or
* <code>null</code> if not set.
*/
public String getVersion() {
return m_factory.getVersion();
}
/**
* Gets component-type properties.
* @return the list of configuration properties accepted by the component type type.
*/
public PropertyDescription[] getProperties() {
return m_properties;
}
/**
* Adds a String property in the component type.
* @param name : property name.
* @param value : property value.
*/
public void addProperty(String name, String value) {
addProperty(name, value, false);
}
/**
* Adds a String property in the component type.
* @param name : property name.
* @param value : property value.
* @param immutable : the property is immutable.
*/
public void addProperty(String name, String value, boolean immutable) {
PropertyDescription prop = new PropertyDescription(name, String.class.getName(), value);
addProperty(prop);
}
/**
* Adds a configuration properties to the component type.
* @param pd : the property to add
*/
public void addProperty(PropertyDescription pd) { //NOPMD remove the instance name of the 'name' property.
String name = pd.getName();
// Check if the property is not already in the array
for (int i = 0; i < m_properties.length; i++) {
PropertyDescription desc = m_properties[i];
if (desc.getName().equals(name)) { return; }
}
PropertyDescription[] newProps = new PropertyDescription[m_properties.length + 1];
System.arraycopy(m_properties, 0, newProps, 0, m_properties.length);
newProps[m_properties.length] = pd;
m_properties = newProps;
}
/**
* Adds the HandlerInfo for specified handler.
* @param handlerNs Handler's namespace
* @param handlerName Handler's name
* @param info HandlerInfo associated with the given custom handler.
*/
public void setHandlerInfo(String handlerNs, String handlerName, CustomHandlerInfo info)
{
String fullHandlerName = handlerNs + ":" + handlerName;
if(info == null)
{
m_handlerInfoSlot.remove(fullHandlerName);
}
else
{
m_handlerInfoSlot.put(fullHandlerName, info);
}
}
public CustomHandlerInfo getHandlerInfo(String handlerNs, String handlerName)
{
String fullHandlerName = handlerNs + ":" + handlerName;
return (CustomHandlerInfo)m_handlerInfoSlot.get(fullHandlerName);
}
/**
* Gets the list of provided service offered by instances of this type.
* @return the list of the provided service.
*/
public String[] getprovidedServiceSpecification() {
return m_providedServiceSpecification;
}
/**
* Adds a provided service to the component type.
* @param serviceSpecification : the provided service to add (interface name)
*/
public void addProvidedServiceSpecification(String serviceSpecification) {
String[] newSs = new String[m_providedServiceSpecification.length + 1];
System.arraycopy(m_providedServiceSpecification, 0, newSs, 0, m_providedServiceSpecification.length);
newSs[m_providedServiceSpecification.length] = serviceSpecification;
m_providedServiceSpecification = newSs;
}
/**
* Returns the component-type name.
* @return the name of this component type
*/
public String getName() {
return m_factory.getName();
}
/**
* Computes the default service properties to publish :
* factory.name, service.pid, component.providedServiceSpecification, component.properties, component.description, factory.State.
* @return : the dictionary of properties to publish.
*/
public Dictionary getPropertiesToPublish() {
Properties props = new Properties();
props.put("factory.name", m_factory.getName());
props.put(Constants.SERVICE_PID, m_factory.getName()); // Service PID is required for the integration in the configuration admin.
// Add the version if set
String v = getVersion();
if (v != null) {
props.put("factory.version", v);
}
props.put("component.providedServiceSpecifications", m_providedServiceSpecification);
props.put("component.properties", m_properties);
props.put("component.description", this);
// add every immutable property
for (int i = 0; i < m_properties.length; i++) {
if (m_properties[i].isImmutable() && m_properties[i].getValue() != null) {
props.put(m_properties[i].getName(), m_properties[i].getObjectValue(m_factory.getBundleContext()));
}
}
// Add factory state
props.put("factory.state", new Integer(m_factory.getState()));
return props;
}
/**
* Gets the interfaces published by the factory.
* By default publish both {@link Factory} and {@link ManagedServiceFactory}.
* @return : the list of interface published by the factory.
*/
public String[] getFactoryInterfacesToPublish() {
return new String[] {Factory.class.getName(), ManagedServiceFactory.class.getName()};
}
/**
* Gets the component type description.
* @return : the description
*/
public Element getDescription() {
Element desc = new Element("Factory", "");
desc.addAttribute(new Attribute("name", m_factory.getName()));
desc.addAttribute(
new Attribute("bundle",
Long.toString(((ComponentFactory) m_factory).getBundleContext().getBundle().getBundleId())));
String state = "valid";
if (m_factory.getState() == Factory.INVALID) {
state = "invalid";
}
desc.addAttribute(new Attribute("state", state));
// Display required & missing handlers
Element req = new Element("RequiredHandlers", "");
req.addAttribute(new Attribute("list", m_factory.getRequiredHandlers().toString()));
Element missing = new Element("MissingHandlers", "");
missing.addAttribute(new Attribute("list", m_factory.getMissingHandlers().toString()));
desc.addElement(req);
desc.addElement(missing);
for (int i = 0; i < m_providedServiceSpecification.length; i++) {
Element prov = new Element("provides", "");
prov.addAttribute(new Attribute("specification", m_providedServiceSpecification[i]));
desc.addElement(prov);
}
for (int i = 0; i < m_properties.length; i++) {
Element prop = new Element("property", "");
prop.addAttribute(new Attribute("name", m_properties[i].getName()));
prop.addAttribute(new Attribute("type", m_properties[i].getType()));
if (m_properties[i].isMandatory() && m_properties[i].getValue() == null) {
prop.addAttribute(new Attribute("value", "REQUIRED"));
} else {
prop.addAttribute(new Attribute("value", m_properties[i].getValue()));
}
desc.addElement(prop);
}
if(m_handlerInfoSlot.size() > 0)
{
Enumeration keys = m_handlerInfoSlot.keys();
while(keys.hasMoreElements())
{
String fullHandlerName = (String) keys.nextElement();
CustomHandlerInfo handlerInfo = (CustomHandlerInfo)m_handlerInfoSlot.get(fullHandlerName);
desc.addElement( handlerInfo.getDescription() );
}
}
return desc;
}
public BundleContext getBundleContext() {
return m_factory.getBundleContext();
}
}
| FELIX-3843 ClassCastException when listing service properties of a non-ComponentFactory Factory service
* Remove un-needed cast to ComponentFactory
git-svn-id: e057f57e93a604d3b43d277ae69bde5ebf332112@1430762 13f79535-47bb-0310-9956-ffa450edef68
| ipojo/runtime/core/src/main/java/org/apache/felix/ipojo/architecture/ComponentTypeDescription.java | FELIX-3843 ClassCastException when listing service properties of a non-ComponentFactory Factory service | |
Java | apache-2.0 | c5a2595a03bf1c1945a7115a05486781eec98f6a | 0 | kef/hieos,kef/hieos,kef/hieos | /*
*
* This code is subject to the HIEOS License, Version 1.0
*
* Copyright(c) 2011 Vangent, Inc. All rights reserved.
*
* 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.vangent.hieos.DocViewer.server.services.rpc.config;
import java.util.List;
import com.vangent.hieos.DocViewer.client.model.config.Config;
import com.vangent.hieos.DocViewer.client.model.config.DocumentTemplateConfig;
import com.vangent.hieos.DocViewer.client.services.rpc.ConfigRemoteService;
import com.vangent.hieos.DocViewer.server.framework.ServletUtilMixin;
import com.vangent.hieos.xutil.xconfig.XConfig;
import com.vangent.hieos.xutil.xconfig.XConfigObject;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
public class ConfigRemoteServiceImpl extends RemoteServiceServlet implements
ConfigRemoteService {
/**
*
*/
private static final long serialVersionUID = -7923244304825432784L;
@Override
public Config getConfig() {
System.out.println("********* ConfigRemoteServiceImpl ********");
// Get the mixin to allow access to xconfig.xml.
ServletUtilMixin servletUtil = new ServletUtilMixin();
servletUtil.init(this.getServletContext());
// Create the Config instance that will be sent back to the client.
Config config = new Config();
// Now get the relevant properties
// DefaultSearchMode:
String defaultSearchMode = servletUtil
.getProperty(Config.KEY_SEARCH_MODE);
System.out.println("DefaultSearchMode = " + defaultSearchMode);
if (defaultSearchMode == null) {
defaultSearchMode = Config.VAL_SEARCH_MODE_HIE;
}
// TrimDocumentTabTitles:
String trimDocumentTabTitles = servletUtil
.getProperty(Config.KEY_TRIM_DOCUMENT_TAB_TITLES);
if (trimDocumentTabTitles == null) {
trimDocumentTabTitles = "false";
}
// TrimDocumentTabTitlesLength:
String trimDocumentTabTitlesLength = servletUtil
.getProperty(Config.KEY_TRIM_DOCUMENT_TAB_TITLES_LENGTH);
if (trimDocumentTabTitlesLength == null) {
trimDocumentTabTitlesLength = "50";
}
// Title:
String title = servletUtil.getProperty(Config.KEY_TITLE);
if (title == null) {
title = "HIEOS Doc Viewer";
}
// LogoFileName:
String logoFileName = servletUtil
.getProperty(Config.KEY_LOGO_FILE_NAME);
System.out.println("LogoFileName = " + logoFileName);
if (logoFileName == null) {
logoFileName = "search_computer.png";
}
// LogoWidth/LogoHeight:
String logoWidth = servletUtil.getProperty(Config.KEY_LOGO_WIDTH);
String logoHeigth = servletUtil.getProperty(Config.KEY_LOGO_HEIGHT);
// Fill up the config:
config.put(Config.KEY_SEARCH_MODE, defaultSearchMode);
config.put(Config.KEY_TRIM_DOCUMENT_TAB_TITLES, trimDocumentTabTitles);
config.put(Config.KEY_TRIM_DOCUMENT_TAB_TITLES_LENGTH,
trimDocumentTabTitlesLength);
config.put(Config.KEY_TITLE, title);
config.put(Config.KEY_LOGO_FILE_NAME, logoFileName);
config.put(Config.KEY_LOGO_WIDTH, logoWidth);
config.put(Config.KEY_LOGO_HEIGHT, logoHeigth);
this.loadDocumentTemplateConfigs(servletUtil, config);
return config;
}
/**
*
* @param servletUtil
* @param config
*/
private void loadDocumentTemplateConfigs(ServletUtilMixin servletUtil,
Config config) {
try {
XConfig xconf = XConfig.getInstance();
XConfigObject propertiesObject = xconf.getXConfigObjectByName(
"DocViewerProperties", "DocViewerPropertiesType");
XConfigObject documentTemplateListConfig = propertiesObject
.getXConfigObjectWithName("DocumentTemplates",
"DocumentTemplateListType");
List<XConfigObject> configObjects = documentTemplateListConfig
.getXConfigObjectsWithType("DocumentTemplateType");
for (XConfigObject configObject : configObjects) {
DocumentTemplateConfig documentTemplateConfig = new DocumentTemplateConfig();
documentTemplateConfig.setDisplayName(configObject
.getProperty("DisplayName"));
documentTemplateConfig.setFileName(configObject
.getProperty("FileName"));
config.addDocumentTemplateConfig(documentTemplateConfig);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| src/DocViewer/src/com/vangent/hieos/DocViewer/server/services/rpc/config/ConfigRemoteServiceImpl.java | /*
*
* This code is subject to the HIEOS License, Version 1.0
*
* Copyright(c) 2011 Vangent, Inc. All rights reserved.
*
* 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.vangent.hieos.DocViewer.server.services.rpc.config;
import com.vangent.hieos.DocViewer.client.model.config.Config;
import com.vangent.hieos.DocViewer.client.services.rpc.ConfigRemoteService;
import com.vangent.hieos.DocViewer.server.framework.ServletUtilMixin;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
public class ConfigRemoteServiceImpl extends RemoteServiceServlet implements ConfigRemoteService {
/**
*
*/
private static final long serialVersionUID = -7923244304825432784L;
@Override
public Config getConfig() {
System.out.println("********* ConfigRemoteServiceImpl ********");
// Get the mixin to allow access to xconfig.xml.
ServletUtilMixin servletUtil = new ServletUtilMixin();
servletUtil.init(this.getServletContext());
// Create the Config instance that will be sent back to the client.
Config config = new Config();
// Now get the relevant properties
// DefaultSearchMode:
String defaultSearchMode = servletUtil.getProperty(Config.KEY_SEARCH_MODE);
System.out.println("DefaultSearchMode = " + defaultSearchMode);
if (defaultSearchMode == null)
{
defaultSearchMode = Config.VAL_SEARCH_MODE_HIE;
}
// TrimDocumentTabTitles:
String trimDocumentTabTitles = servletUtil.getProperty(Config.KEY_TRIM_DOCUMENT_TAB_TITLES);
if (trimDocumentTabTitles == null)
{
trimDocumentTabTitles = "false";
}
// TrimDocumentTabTitlesLength:
String trimDocumentTabTitlesLength = servletUtil.getProperty(Config.KEY_TRIM_DOCUMENT_TAB_TITLES_LENGTH);
if (trimDocumentTabTitlesLength == null)
{
trimDocumentTabTitlesLength = "50";
}
// Title:
String title = servletUtil.getProperty(Config.KEY_TITLE);
if (title == null)
{
title = "HIEOS Doc Viewer";
}
// LogoFileName:
String logoFileName = servletUtil.getProperty(Config.KEY_LOGO_FILE_NAME);
System.out.println("LogoFileName = " + logoFileName);
if (logoFileName == null)
{
logoFileName = "search_computer.png";
}
// LogoWidth/LogoHeight:
String logoWidth = servletUtil.getProperty(Config.KEY_LOGO_WIDTH);
String logoHeigth = servletUtil.getProperty(Config.KEY_LOGO_HEIGHT);
// Fill up the config:
config.put(Config.KEY_SEARCH_MODE, defaultSearchMode);
config.put(Config.KEY_TRIM_DOCUMENT_TAB_TITLES, trimDocumentTabTitles);
config.put(Config.KEY_TRIM_DOCUMENT_TAB_TITLES_LENGTH, trimDocumentTabTitlesLength);
config.put(Config.KEY_TITLE, title);
config.put(Config.KEY_LOGO_FILE_NAME, logoFileName);
config.put(Config.KEY_LOGO_WIDTH, logoWidth);
config.put(Config.KEY_LOGO_HEIGHT, logoHeigth);
return config;
}
}
| Added templates as configuration.
| src/DocViewer/src/com/vangent/hieos/DocViewer/server/services/rpc/config/ConfigRemoteServiceImpl.java | Added templates as configuration. | |
Java | apache-2.0 | 39392f59487515e38ebf35781f3caa0850805418 | 0 | lgoldstein/mina-sshd,apache/mina-sshd,lgoldstein/mina-sshd,lgoldstein/mina-sshd,lgoldstein/mina-sshd,apache/mina-sshd,apache/mina-sshd,apache/mina-sshd | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.sshd.common.session.helpers;
import java.io.IOException;
import org.apache.sshd.common.PropertyResolverUtils;
import org.apache.sshd.common.SshConstants;
import org.apache.sshd.common.channel.Channel;
import org.apache.sshd.common.io.IoWriteFuture;
import org.apache.sshd.common.session.ConnectionService;
import org.apache.sshd.common.session.Session;
import org.apache.sshd.common.session.UnknownChannelReferenceHandler;
import org.apache.sshd.common.util.buffer.Buffer;
import org.apache.sshd.common.util.logging.AbstractLoggingBean;
/**
* @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
*/
public class DefaultUnknownChannelReferenceHandler
extends AbstractLoggingBean
implements UnknownChannelReferenceHandler {
/**
* RFC4254 does not clearly specify how to handle {@code SSH_MSG_CHANNEL_DATA}
* and {@code SSH_MSG_CHANNEL_EXTENDED_DATA} received through an unknown channel.
* Therefore, we provide a configurable approach to it with the default set to ignore it.
*/
public static final String SEND_REPLY_FOR_CHANNEL_DATA = "send-unknown-channel-data-reply";
// Not sure if entirely compliant with RFC4254, but try to stem the flood
public static final boolean DEFAULT_SEND_REPLY_FOR_CHANNEL_DATA = false;
public static final DefaultUnknownChannelReferenceHandler INSTANCE = new DefaultUnknownChannelReferenceHandler();
public DefaultUnknownChannelReferenceHandler() {
super();
}
@Override
public Channel handleUnknownChannelCommand(
ConnectionService service, byte cmd, int channelId, Buffer buffer)
throws IOException {
Session session = service.getSession();
// Use DEBUG level to avoid log overflow due to invalid messages flood
if (log.isDebugEnabled()) {
log.debug("handleUnknownChannelCommand({}) received {} command for unknown channel: {}",
session, SshConstants.getCommandMessageName(cmd), channelId);
}
boolean wantReply = false;
switch (cmd) {
case SshConstants.SSH_MSG_CHANNEL_REQUEST: {
/*
* From RFC 4252 - section 5.4:
*
* If the request is not recognized or is not supported for the
* channel, SSH_MSG_CHANNEL_FAILURE is returned
*/
String req = buffer.getString();
wantReply = buffer.getBoolean();
// Use DEBUG level to avoid log overflow due to invalid messages flood
if (log.isDebugEnabled()) {
log.debug("handleUnknownChannelCommand({}) Received SSH_MSG_CHANNEL_REQUEST={} (wantReply={}) for unknown channel: {}",
session, req, wantReply, channelId);
}
break;
}
case SshConstants.SSH_MSG_CHANNEL_DATA:
case SshConstants.SSH_MSG_CHANNEL_EXTENDED_DATA:
wantReply = PropertyResolverUtils.getBooleanProperty(session, SEND_REPLY_FOR_CHANNEL_DATA, DEFAULT_SEND_REPLY_FOR_CHANNEL_DATA);
// Use TRACE level to avoid log overflow due to invalid messages flood
if (log.isTraceEnabled()) {
log.trace("handleUnknownChannelCommand({}) received msg channel data (opcode={}) reply={}", session, cmd, wantReply);
}
break;
default: // do nothing
}
if (wantReply) {
sendFailureResponse(service, cmd, channelId);
}
return null;
}
protected IoWriteFuture sendFailureResponse(ConnectionService service, byte cmd, int channelId) throws IOException {
Session session = service.getSession();
// Use DEBUG level to avoid log overflow due to invalid messages flood
if (log.isDebugEnabled()) {
log.debug("sendFailureResponse({}) send SSH_MSG_CHANNEL_FAILURE for {} command on unknown channel: {}",
session, SshConstants.getCommandMessageName(cmd), channelId);
}
Buffer rsp = session.createBuffer(SshConstants.SSH_MSG_CHANNEL_FAILURE, Integer.BYTES);
rsp.putInt(channelId);
return session.writePacket(rsp);
}
}
| sshd-core/src/main/java/org/apache/sshd/common/session/helpers/DefaultUnknownChannelReferenceHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.sshd.common.session.helpers;
import java.io.IOException;
import org.apache.sshd.common.SshConstants;
import org.apache.sshd.common.channel.Channel;
import org.apache.sshd.common.io.IoWriteFuture;
import org.apache.sshd.common.session.ConnectionService;
import org.apache.sshd.common.session.Session;
import org.apache.sshd.common.session.UnknownChannelReferenceHandler;
import org.apache.sshd.common.util.buffer.Buffer;
import org.apache.sshd.common.util.logging.AbstractLoggingBean;
/**
* @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
*/
public class DefaultUnknownChannelReferenceHandler
extends AbstractLoggingBean
implements UnknownChannelReferenceHandler {
public static final DefaultUnknownChannelReferenceHandler INSTANCE = new DefaultUnknownChannelReferenceHandler();
public DefaultUnknownChannelReferenceHandler() {
super();
}
@Override
public Channel handleUnknownChannelCommand(
ConnectionService service, byte cmd, int channelId, Buffer buffer)
throws IOException {
Session session = service.getSession();
// Use DEBUG level to avoid log overflow due to invalid messages flood
if (log.isDebugEnabled()) {
log.debug("handleUnknownChannelCommand({}) received {} command for unknown channel: {}",
session, SshConstants.getCommandMessageName(cmd), channelId);
}
boolean wantReply = false;
switch (cmd) {
case SshConstants.SSH_MSG_CHANNEL_REQUEST: {
/*
* From RFC 4252 - section 5.4:
*
* If the request is not recognized or is not supported for the
* channel, SSH_MSG_CHANNEL_FAILURE is returned
*/
String req = buffer.getString();
wantReply = buffer.getBoolean();
// Use DEBUG level to avoid log overflow due to invalid messages flood
if (log.isDebugEnabled()) {
log.debug("handleUnknownChannelCommand({}) Received SSH_MSG_CHANNEL_REQUEST={} (wantReply={}) for unknown channel: {}",
session, req, wantReply, channelId);
}
break;
}
case SshConstants.SSH_MSG_CHANNEL_DATA:
case SshConstants.SSH_MSG_CHANNEL_EXTENDED_DATA:
// Not sure if entirely compliant with RFC4254, but try to stem the flood
wantReply = true;
break;
default: // do nothing
}
if (wantReply) {
sendFailureResponse(service, cmd, channelId);
}
return null;
}
protected IoWriteFuture sendFailureResponse(ConnectionService service, byte cmd, int channelId) throws IOException {
Session session = service.getSession();
// Use DEBUG level to avoid log overflow due to invalid messages flood
if (log.isDebugEnabled()) {
log.debug("sendFailureResponse({}) send SSH_MSG_CHANNEL_FAILURE for {} command on unknown channel: {}",
session, SshConstants.getCommandMessageName(cmd), channelId);
}
Buffer rsp = session.createBuffer(SshConstants.SSH_MSG_CHANNEL_FAILURE, Integer.BYTES);
rsp.putInt(channelId);
return session.writePacket(rsp);
}
}
| [SSHD-800] Numerous SSH_MSG_CHANNEL_FAILURE messages sent for SSH_MSG_CHANNEL_DATA on unknown channel
| sshd-core/src/main/java/org/apache/sshd/common/session/helpers/DefaultUnknownChannelReferenceHandler.java | [SSHD-800] Numerous SSH_MSG_CHANNEL_FAILURE messages sent for SSH_MSG_CHANNEL_DATA on unknown channel | |
Java | apache-2.0 | 6f4e6bd6089aa484c8504de620193ad148b526ee | 0 | blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle | /*
* Copyright 2020 the original author or authors.
*
* 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 org.gradle.internal.watch.registry.impl;
import org.gradle.internal.file.DefaultFileHierarchySet;
import org.gradle.internal.file.FileHierarchySet;
import org.gradle.internal.file.FileMetadata;
import org.gradle.internal.snapshot.CompleteDirectorySnapshot;
import org.gradle.internal.snapshot.CompleteFileSystemLocationSnapshot;
import org.gradle.internal.snapshot.FileSystemSnapshotVisitor;
import org.gradle.internal.snapshot.SnapshotHierarchy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.CheckReturnValue;
import java.io.File;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Deque;
import java.util.function.Predicate;
public class WatchableHierarchies {
private static final Logger LOGGER = LoggerFactory.getLogger(WatchableHierarchies.class);
private final Predicate<String> watchFilter;
private final int maxHierarchiesToWatch;
private FileHierarchySet watchableHierarchies = DefaultFileHierarchySet.of();
private final Deque<File> recentlyUsedHierarchies = new ArrayDeque<>();
public WatchableHierarchies(Predicate<String> watchFilter, int maxHierarchiesToWatch) {
this.watchFilter = watchFilter;
this.maxHierarchiesToWatch = maxHierarchiesToWatch;
}
public void registerWatchableHierarchy(File watchableHierarchy, SnapshotHierarchy root) {
String watchableHierarchyAbsolutePath = watchableHierarchy.getAbsolutePath();
if (!watchFilter.test(watchableHierarchyAbsolutePath)) {
throw new IllegalStateException(String.format(
"Unable to watch directory '%s' since it is within Gradle's caches",
watchableHierarchyAbsolutePath
));
}
if (!watchableHierarchies.contains(watchableHierarchyAbsolutePath)) {
checkThatNothingExistsInNewWatchableHierarchy(watchableHierarchyAbsolutePath, root);
recentlyUsedHierarchies.addFirst(watchableHierarchy);
watchableHierarchies = watchableHierarchies.plus(watchableHierarchy);
} else {
recentlyUsedHierarchies.remove(watchableHierarchy);
recentlyUsedHierarchies.addFirst(watchableHierarchy);
}
LOGGER.info("Now considering {} as hierarchies to watch", recentlyUsedHierarchies);
}
@CheckReturnValue
public SnapshotHierarchy removeUnwatchedSnapshots(Predicate<File> isWatchedHierarchy, SnapshotHierarchy root, Invalidator invalidator) {
recentlyUsedHierarchies.removeIf(hierarchy -> !isWatchedHierarchy.test(hierarchy));
SnapshotHierarchy currentRoot = stopWatchingHierarchiesOverLimit(invalidator, root);
this.watchableHierarchies = DefaultFileHierarchySet.of(recentlyUsedHierarchies);
RemoveUnwatchedFiles removeUnwatchedFilesVisitor = new RemoveUnwatchedFiles(currentRoot, invalidator);
currentRoot.visitSnapshotRoots(snapshotRoot -> snapshotRoot.accept(removeUnwatchedFilesVisitor));
return removeUnwatchedFilesVisitor.getRootWithUnwatchedFilesRemoved();
}
private SnapshotHierarchy stopWatchingHierarchiesOverLimit(Invalidator invalidator, SnapshotHierarchy root) {
SnapshotHierarchy result = root;
int toRemove = recentlyUsedHierarchies.size() - maxHierarchiesToWatch;
if (toRemove > 0) {
LOGGER.warn("Watching too many directories in the file system (watching {}, limit {}), dropping some state from the virtual file system", recentlyUsedHierarchies.size(), maxHierarchiesToWatch);
for (int i = 0; i < toRemove; i++) {
File locationToRemove = recentlyUsedHierarchies.removeLast();
result = invalidator.invalidate(locationToRemove.getAbsolutePath(), result);
}
}
return result;
}
public Collection<File> getWatchableHierarchies() {
return recentlyUsedHierarchies;
}
private void checkThatNothingExistsInNewWatchableHierarchy(String watchableHierarchy, SnapshotHierarchy vfsRoot) {
vfsRoot.visitSnapshotRoots(watchableHierarchy, snapshotRoot -> {
if (!isInWatchableHierarchy(snapshotRoot.getAbsolutePath()) && !ignoredForWatching(snapshotRoot)) {
throw new IllegalStateException(String.format(
"Found existing snapshot at '%s' for unwatched hierarchy '%s'",
snapshotRoot.getAbsolutePath(),
watchableHierarchy
));
}
});
}
public boolean ignoredForWatching(CompleteFileSystemLocationSnapshot snapshot) {
return snapshot.getAccessType() == FileMetadata.AccessType.VIA_SYMLINK || !watchFilter.test(snapshot.getAbsolutePath());
}
public boolean isInWatchableHierarchy(String path) {
return watchableHierarchies.contains(path);
}
public boolean shouldWatch(CompleteFileSystemLocationSnapshot snapshot) {
return !ignoredForWatching(snapshot) && isInWatchableHierarchy(snapshot.getAbsolutePath());
}
private class RemoveUnwatchedFiles implements FileSystemSnapshotVisitor {
private SnapshotHierarchy root;
private final Invalidator invalidator;
public RemoveUnwatchedFiles(SnapshotHierarchy root, Invalidator invalidator) {
this.root = root;
this.invalidator = invalidator;
}
@Override
public boolean preVisitDirectory(CompleteDirectorySnapshot directorySnapshot) {
if (shouldBeRemoved(directorySnapshot)) {
invalidateUnwatchedFile(directorySnapshot);
return false;
}
return true;
}
private boolean shouldBeRemoved(CompleteFileSystemLocationSnapshot snapshot) {
return snapshot.getAccessType() == FileMetadata.AccessType.VIA_SYMLINK ||
(!isInWatchableHierarchy(snapshot.getAbsolutePath()) && watchFilter.test(snapshot.getAbsolutePath()));
}
@Override
public void visitFile(CompleteFileSystemLocationSnapshot fileSnapshot) {
if (shouldBeRemoved(fileSnapshot)) {
invalidateUnwatchedFile(fileSnapshot);
}
}
@Override
public void postVisitDirectory(CompleteDirectorySnapshot directorySnapshot) {
}
private void invalidateUnwatchedFile(CompleteFileSystemLocationSnapshot snapshot) {
root = invalidator.invalidate(snapshot.getAbsolutePath(), root);
}
public SnapshotHierarchy getRootWithUnwatchedFilesRemoved() {
return root;
}
}
public interface Invalidator {
SnapshotHierarchy invalidate(String absolutePath, SnapshotHierarchy currentRoot);
}
}
| subprojects/file-watching/src/main/java/org/gradle/internal/watch/registry/impl/WatchableHierarchies.java | /*
* Copyright 2020 the original author or authors.
*
* 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 org.gradle.internal.watch.registry.impl;
import org.gradle.internal.file.DefaultFileHierarchySet;
import org.gradle.internal.file.FileHierarchySet;
import org.gradle.internal.file.FileMetadata;
import org.gradle.internal.snapshot.CompleteDirectorySnapshot;
import org.gradle.internal.snapshot.CompleteFileSystemLocationSnapshot;
import org.gradle.internal.snapshot.FileSystemSnapshotVisitor;
import org.gradle.internal.snapshot.SnapshotHierarchy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.CheckReturnValue;
import java.io.File;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Deque;
import java.util.function.Predicate;
public class WatchableHierarchies {
private static final Logger LOGGER = LoggerFactory.getLogger(WatchableHierarchies.class);
private final Predicate<String> watchFilter;
private final int maxHierarchiesToWatch;
private FileHierarchySet watchableHierarchies = DefaultFileHierarchySet.of();
private final Deque<File> recentlyUsedHierarchies = new ArrayDeque<>();
public WatchableHierarchies(Predicate<String> watchFilter, int maxHierarchiesToWatch) {
this.watchFilter = watchFilter;
this.maxHierarchiesToWatch = maxHierarchiesToWatch;
}
public void registerWatchableHierarchy(File watchableHierarchy, SnapshotHierarchy root) {
String watchableHierarchyAbsolutePath = watchableHierarchy.getAbsolutePath();
if (!watchFilter.test(watchableHierarchyAbsolutePath)) {
throw new IllegalStateException(String.format(
"Unable to watch directory '%s' since it is within Gradle's caches",
watchableHierarchyAbsolutePath
));
}
if (!watchableHierarchies.contains(watchableHierarchyAbsolutePath)) {
checkThatNothingExistsInNewWatchableHierarchy(watchableHierarchyAbsolutePath, root);
recentlyUsedHierarchies.addFirst(watchableHierarchy);
watchableHierarchies = watchableHierarchies.plus(watchableHierarchy);
} else {
recentlyUsedHierarchies.remove(watchableHierarchy);
recentlyUsedHierarchies.addFirst(watchableHierarchy);
}
LOGGER.info("Now considering {} as hierarchies to watch", recentlyUsedHierarchies);
}
@CheckReturnValue
public SnapshotHierarchy removeUnwatchedSnapshots(Predicate<File> isWatchedHierarchy, SnapshotHierarchy root, Invalidator invalidator) {
recentlyUsedHierarchies.removeIf(hierarchy -> !isWatchedHierarchy.test(hierarchy));
SnapshotHierarchy currentRoot = stopWatchingHierarchiesOverLimit(invalidator, root);
this.watchableHierarchies = DefaultFileHierarchySet.of(recentlyUsedHierarchies);
RemoveUnwatchedFiles removeUnwatchedFilesVisitor = new RemoveUnwatchedFiles(currentRoot, invalidator);
currentRoot.visitSnapshotRoots(snapshotRoot -> snapshotRoot.accept(removeUnwatchedFilesVisitor));
return removeUnwatchedFilesVisitor.getRootWithUnwatchedFilesRemoved();
}
private SnapshotHierarchy stopWatchingHierarchiesOverLimit(Invalidator invalidator, SnapshotHierarchy root) {
SnapshotHierarchy result = root;
int toRemove = recentlyUsedHierarchies.size() - maxHierarchiesToWatch;
if (toRemove > 0) {
LOGGER.warn("Watching {} hierarchies, removing {} to limit the number of watched directories", recentlyUsedHierarchies.size(), toRemove);
for (int i = 0; i < toRemove; i++) {
File locationToRemove = recentlyUsedHierarchies.removeLast();
result = invalidator.invalidate(locationToRemove.getAbsolutePath(), result);
}
}
return result;
}
public Collection<File> getWatchableHierarchies() {
return recentlyUsedHierarchies;
}
private void checkThatNothingExistsInNewWatchableHierarchy(String watchableHierarchy, SnapshotHierarchy vfsRoot) {
vfsRoot.visitSnapshotRoots(watchableHierarchy, snapshotRoot -> {
if (!isInWatchableHierarchy(snapshotRoot.getAbsolutePath()) && !ignoredForWatching(snapshotRoot)) {
throw new IllegalStateException(String.format(
"Found existing snapshot at '%s' for unwatched hierarchy '%s'",
snapshotRoot.getAbsolutePath(),
watchableHierarchy
));
}
});
}
public boolean ignoredForWatching(CompleteFileSystemLocationSnapshot snapshot) {
return snapshot.getAccessType() == FileMetadata.AccessType.VIA_SYMLINK || !watchFilter.test(snapshot.getAbsolutePath());
}
public boolean isInWatchableHierarchy(String path) {
return watchableHierarchies.contains(path);
}
public boolean shouldWatch(CompleteFileSystemLocationSnapshot snapshot) {
return !ignoredForWatching(snapshot) && isInWatchableHierarchy(snapshot.getAbsolutePath());
}
private class RemoveUnwatchedFiles implements FileSystemSnapshotVisitor {
private SnapshotHierarchy root;
private final Invalidator invalidator;
public RemoveUnwatchedFiles(SnapshotHierarchy root, Invalidator invalidator) {
this.root = root;
this.invalidator = invalidator;
}
@Override
public boolean preVisitDirectory(CompleteDirectorySnapshot directorySnapshot) {
if (shouldBeRemoved(directorySnapshot)) {
invalidateUnwatchedFile(directorySnapshot);
return false;
}
return true;
}
private boolean shouldBeRemoved(CompleteFileSystemLocationSnapshot snapshot) {
return snapshot.getAccessType() == FileMetadata.AccessType.VIA_SYMLINK ||
(!isInWatchableHierarchy(snapshot.getAbsolutePath()) && watchFilter.test(snapshot.getAbsolutePath()));
}
@Override
public void visitFile(CompleteFileSystemLocationSnapshot fileSnapshot) {
if (shouldBeRemoved(fileSnapshot)) {
invalidateUnwatchedFile(fileSnapshot);
}
}
@Override
public void postVisitDirectory(CompleteDirectorySnapshot directorySnapshot) {
}
private void invalidateUnwatchedFile(CompleteFileSystemLocationSnapshot snapshot) {
root = invalidator.invalidate(snapshot.getAbsolutePath(), root);
}
public SnapshotHierarchy getRootWithUnwatchedFilesRemoved() {
return root;
}
}
public interface Invalidator {
SnapshotHierarchy invalidate(String absolutePath, SnapshotHierarchy currentRoot);
}
}
| Improve message when we hit the limit of directories to watch
| subprojects/file-watching/src/main/java/org/gradle/internal/watch/registry/impl/WatchableHierarchies.java | Improve message when we hit the limit of directories to watch | |
Java | apache-2.0 | 6af15e115cc4e2a9c00857053abc8911304171e6 | 0 | Alfresco/alfresco-sdk,Alfresco/alfresco-sdk,Alfresco/alfresco-sdk,loftuxab/alfresco-sdk,AFaust/alfresco-sdk,adrianopatrick/alfresco-sdk,loftuxab/alfresco-sdk,abhinavmishra14/alfresco-sdk,microstrat/alfresco-sdk,loftuxab/alfresco-sdk,microstrat/alfresco-sdk,abhinavmishra14/alfresco-sdk,Alfresco/alfresco-sdk,bhagyas/alfresco-sdk,abhinavmishra14/alfresco-sdk,bhagyas/alfresco-sdk,AFaust/alfresco-sdk,adrianopatrick/alfresco-sdk,AFaust/alfresco-sdk,abhinavmishra14/alfresco-sdk,bhagyas/alfresco-sdk,microstrat/alfresco-sdk,adrianopatrick/alfresco-sdk,AFaust/alfresco-sdk,adrianopatrick/alfresco-sdk,bhagyas/alfresco-sdk,microstrat/alfresco-sdk,loftuxab/alfresco-sdk | package org.alfresco.maven.rad;
import com.tradeshift.test.remote.RemoteServer;
public class RemoteRunnerWrapper implements Runnable {
public void run() {
try {
RemoteServer.main(new String []{});
} catch (Exception e) {
System.out.println("Could not start JUnit remoteServer because of: " + e.getMessage());
}
}
}
| modules/alfresco-rad/src/main/java/org/alfresco/maven/rad/RemoteRunnerWrapper.java | package org.alfresco.maven.rad;
import com.tradeshift.test.remote.RemoteServer;
public class RemoteRunnerWrapper implements Runnable {
public void run() {
try {
RemoteServer.main(new String []{});
} catch (Exception e) {
System.out.println("Could not start JUnit remoteServer");
}
}
}
| ugly code, made only slightly less ugly by not swallowing the exception
| modules/alfresco-rad/src/main/java/org/alfresco/maven/rad/RemoteRunnerWrapper.java | ugly code, made only slightly less ugly by not swallowing the exception | |
Java | apache-2.0 | bbaa106a1bee230f670c6affdc6a82cc642e2c21 | 0 | mpouttuclarke/cdap,mpouttuclarke/cdap,caskdata/cdap,hsaputra/cdap,anthcp/cdap,chtyim/cdap,chtyim/cdap,mpouttuclarke/cdap,caskdata/cdap,hsaputra/cdap,chtyim/cdap,caskdata/cdap,caskdata/cdap,hsaputra/cdap,hsaputra/cdap,anthcp/cdap,anthcp/cdap,chtyim/cdap,anthcp/cdap,caskdata/cdap,mpouttuclarke/cdap,anthcp/cdap,chtyim/cdap,mpouttuclarke/cdap,caskdata/cdap,chtyim/cdap,hsaputra/cdap | /*
* Copyright © 2014-2015 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package co.cask.cdap.internal.app.runtime.batch;
import co.cask.cdap.api.Resources;
import co.cask.cdap.api.data.batch.BatchReadable;
import co.cask.cdap.api.data.batch.BatchWritable;
import co.cask.cdap.api.data.batch.DatasetOutputCommitter;
import co.cask.cdap.api.data.batch.InputFormatProvider;
import co.cask.cdap.api.data.batch.OutputFormatProvider;
import co.cask.cdap.api.data.batch.Split;
import co.cask.cdap.api.data.format.FormatSpecification;
import co.cask.cdap.api.data.stream.StreamBatchReadable;
import co.cask.cdap.api.dataset.DataSetException;
import co.cask.cdap.api.dataset.Dataset;
import co.cask.cdap.api.flow.flowlet.StreamEvent;
import co.cask.cdap.api.mapreduce.MapReduce;
import co.cask.cdap.api.mapreduce.MapReduceSpecification;
import co.cask.cdap.api.stream.StreamEventDecoder;
import co.cask.cdap.api.templates.plugins.PluginInfo;
import co.cask.cdap.common.conf.CConfiguration;
import co.cask.cdap.common.conf.Constants;
import co.cask.cdap.common.io.Locations;
import co.cask.cdap.common.lang.ClassLoaders;
import co.cask.cdap.common.lang.WeakReferenceDelegatorClassLoader;
import co.cask.cdap.common.logging.LoggingContextAccessor;
import co.cask.cdap.common.utils.ApplicationBundler;
import co.cask.cdap.common.utils.DirUtils;
import co.cask.cdap.data.stream.StreamInputFormat;
import co.cask.cdap.data.stream.StreamUtils;
import co.cask.cdap.data2.registry.UsageRegistry;
import co.cask.cdap.data2.transaction.Transactions;
import co.cask.cdap.data2.transaction.stream.StreamAdmin;
import co.cask.cdap.data2.transaction.stream.StreamConfig;
import co.cask.cdap.data2.util.hbase.HBaseTableUtilFactory;
import co.cask.cdap.internal.app.runtime.batch.dataset.DataSetInputFormat;
import co.cask.cdap.internal.app.runtime.batch.dataset.DataSetOutputFormat;
import co.cask.cdap.proto.Id;
import co.cask.cdap.proto.ProgramType;
import co.cask.cdap.templates.AdapterDefinition;
import co.cask.tephra.Transaction;
import co.cask.tephra.TransactionContext;
import co.cask.tephra.TransactionExecutor;
import co.cask.tephra.TransactionFailureException;
import co.cask.tephra.TransactionSystemClient;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import com.google.common.io.ByteStreams;
import com.google.common.io.Files;
import com.google.common.reflect.TypeToken;
import com.google.common.util.concurrent.AbstractExecutionThreadService;
import com.google.inject.ProvisionException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.MRJobConfig;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.OutputFormat;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.twill.filesystem.Location;
import org.apache.twill.filesystem.LocationFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Performs the actual execution of mapreduce job.
*
* Service start -> Performs job setup, beforeSubmit and submit job
* Service run -> Poll for job completion
* Service triggerStop -> kill job
* Service stop -> Commit/abort transaction, onFinish, cleanup
*/
final class MapReduceRuntimeService extends AbstractExecutionThreadService {
private static final Logger LOG = LoggerFactory.getLogger(MapReduceRuntimeService.class);
/**
* Do not remove: we need this variable for loading MRClientSecurityInfo class required for communicating with
* AM in secure mode.
*/
@SuppressWarnings("unused")
private org.apache.hadoop.mapreduce.v2.app.MRClientSecurityInfo mrClientSecurityInfo;
// Name of configuration source if it is set programmatically. This constant is not defined in Hadoop
private static final String PROGRAMMATIC_SOURCE = "programmatically";
private final CConfiguration cConf;
private final Configuration hConf;
private final MapReduce mapReduce;
private final MapReduceSpecification specification;
private final Location programJarLocation;
private final DynamicMapReduceContext context;
private final LocationFactory locationFactory;
private final StreamAdmin streamAdmin;
private final TransactionSystemClient txClient;
private final UsageRegistry usageRegistry;
private Job job;
private Transaction transaction;
private Runnable cleanupTask;
private ClassLoader classLoader;
private volatile boolean stopRequested;
MapReduceRuntimeService(CConfiguration cConf, Configuration hConf,
MapReduce mapReduce, MapReduceSpecification specification,
DynamicMapReduceContext context,
Location programJarLocation, LocationFactory locationFactory,
StreamAdmin streamAdmin, TransactionSystemClient txClient,
UsageRegistry usageRegistry) {
this.cConf = cConf;
this.hConf = hConf;
this.mapReduce = mapReduce;
this.specification = specification;
this.programJarLocation = programJarLocation;
this.locationFactory = locationFactory;
this.streamAdmin = streamAdmin;
this.txClient = txClient;
this.context = context;
this.usageRegistry = usageRegistry;
}
@Override
protected String getServiceName() {
return "MapReduceRunner-" + specification.getName();
}
@Override
protected void startUp() throws Exception {
final Job job = Job.getInstance(new Configuration(hConf));
Configuration mapredConf = job.getConfiguration();
if (UserGroupInformation.isSecurityEnabled()) {
// If runs in secure cluster, this program runner is running in a yarn container, hence not able
// to get authenticated with the history.
mapredConf.unset("mapreduce.jobhistory.address");
mapredConf.setBoolean(Job.JOB_AM_ACCESS_DISABLED, false);
Credentials credentials = UserGroupInformation.getCurrentUser().getCredentials();
LOG.info("Running in secure mode; adding all user credentials: {}", credentials.getAllTokens());
job.getCredentials().addAll(credentials);
}
// We need to hold a strong reference to the ClassLoader until the end of the MapReduce job.
classLoader = new MapReduceClassLoader(context.getProgram().getClassLoader());
job.getConfiguration().setClassLoader(new WeakReferenceDelegatorClassLoader(classLoader));
ClassLoaders.setContextClassLoader(job.getConfiguration().getClassLoader());
context.setJob(job);
// both beforeSubmit() and setInput/OutputDataset() may call dataset methods. They must be run inside a tx
runUserCodeInTx(new TransactionExecutor.Subroutine() {
// Call the user MapReduce for initialization
@Override
public void apply() throws Exception {
beforeSubmit();
// set input/output datasets info
setInputDatasetIfNeeded(job);
setOutputDatasetIfNeeded(job);
}
}, "startUp()");
// Override user-defined job name, since we set it and depend on the name.
// https://issues.cask.co/browse/CDAP-2441
String jobName = job.getJobName();
if (!jobName.isEmpty()) {
LOG.warn("Job name {} is being overridden.", jobName);
}
job.setJobName(getJobName(context));
// After calling beforeSubmit, we know what plugins are needed for adapter, hence construct the proper
// ClassLoader from here and use it for setting up the job
Location pluginArchive = createPluginArchive(context.getAdapterSpecification(), context.getProgram().getId());
try {
if (pluginArchive != null) {
job.addCacheArchive(pluginArchive.toURI());
}
// Alter the configuration ClassLoader to a MapReduceClassLoader that supports plugin
// It is mainly for standalone mode to have the same ClassLoader as in distributed mode
// It can only be constructed here because we need to have all adapter plugins information
classLoader = new MapReduceClassLoader(context.getProgram().getClassLoader(), context.getAdapterSpecification(),
context.getPluginInstantiator());
job.getConfiguration().setClassLoader(new WeakReferenceDelegatorClassLoader(classLoader));
ClassLoaders.setContextClassLoader(job.getConfiguration().getClassLoader());
setOutputClassesIfNeeded(job);
setMapOutputClassesIfNeeded(job);
// Prefer our job jar in the classpath
// Set both old and new keys
mapredConf.setBoolean("mapreduce.user.classpath.first", true);
mapredConf.setBoolean(Job.MAPREDUCE_JOB_USER_CLASSPATH_FIRST, true);
mapredConf.setBoolean(Job.MAPREDUCE_JOB_CLASSLOADER, true);
// Make CDAP classes (which is in the job.jar created below) to have higher precedence
// It is needed to override the ApplicationClassLoader to use our implementation
String yarnAppClassPath = mapredConf.get(YarnConfiguration.YARN_APPLICATION_CLASSPATH, Joiner.on(',')
.join(YarnConfiguration.DEFAULT_YARN_APPLICATION_CLASSPATH));
mapredConf.set(YarnConfiguration.YARN_APPLICATION_CLASSPATH, "job.jar/lib/*,job.jar/classes," + yarnAppClassPath);
// set resources for the job
Resources mapperResources = context.getMapperResources();
Resources reducerResources = context.getReducerResources();
// this will determine how much memory and virtual cores the yarn container will run with
if (mapperResources != null) {
mapredConf.setInt(Job.MAP_MEMORY_MB, mapperResources.getMemoryMB());
// Also set the Xmx to be smaller than the container memory.
mapredConf.set(Job.MAP_JAVA_OPTS, "-Xmx" + (int) (mapperResources.getMemoryMB() * 0.8) + "m");
setVirtualCores(mapredConf, mapperResources.getVirtualCores(), "MAP");
}
if (reducerResources != null) {
mapredConf.setInt(Job.REDUCE_MEMORY_MB, reducerResources.getMemoryMB());
// Also set the Xmx to be smaller than the container memory.
mapredConf.set(Job.REDUCE_JAVA_OPTS, "-Xmx" + (int) (reducerResources.getMemoryMB() * 0.8) + "m");
setVirtualCores(mapredConf, reducerResources.getVirtualCores(), "REDUCE");
}
// replace user's Mapper & Reducer's with our wrappers in job config
MapperWrapper.wrap(job);
ReducerWrapper.wrap(job);
// packaging job jar which includes cdap classes with dependencies
Location jobJar = buildJobJar(context);
try {
Location programJarCopy = copyProgramJar();
try {
job.setJar(jobJar.toURI().toString());
// Localize the program jar, but not add it to class path
// The ApplicationLoader will create ProgramClassLoader from it
job.addCacheFile(programJarCopy.toURI());
MapReduceContextConfig contextConfig = new MapReduceContextConfig(job.getConfiguration());
// We start long-running tx to be used by mapreduce job tasks.
Transaction tx = txClient.startLong();
try {
// We remember tx, so that we can re-use it in mapreduce tasks
// Make a copy of the conf and rewrite the template plugin directory to be the plugin archive name
CConfiguration cConfCopy = cConf;
if (pluginArchive != null) {
cConfCopy = CConfiguration.copy(cConf);
cConfCopy.set(Constants.AppFabric.APP_TEMPLATE_DIR, pluginArchive.getName());
}
contextConfig.set(context, cConfCopy, tx, programJarCopy.toURI());
LOG.info("Submitting MapReduce Job: {}", context);
// submits job and returns immediately. Shouldn't need to set context ClassLoader.
job.submit();
this.job = job;
this.transaction = tx;
this.cleanupTask = createCleanupTask(jobJar, programJarCopy, pluginArchive);
} catch (Throwable t) {
Transactions.invalidateQuietly(txClient, tx);
throw Throwables.propagate(t);
}
} catch (Throwable t) {
Locations.deleteQuietly(programJarCopy);
throw Throwables.propagate(t);
}
} catch (Throwable t) {
Locations.deleteQuietly(jobJar);
throw Throwables.propagate(t);
}
} catch (Throwable t) {
if (pluginArchive != null) {
Locations.deleteQuietly(pluginArchive);
}
LOG.error("Exception when submitting MapReduce Job: {}", context, t);
throw Throwables.propagate(t);
}
}
@Override
protected void run() throws Exception {
MapReduceMetricsWriter metricsWriter = new MapReduceMetricsWriter(job, context);
// until job is complete report stats
while (!job.isComplete()) {
metricsWriter.reportStats();
// we report to metrics backend every second, so 1 sec is enough here. That's mapreduce job anyways (not
// short) ;)
TimeUnit.SECONDS.sleep(1);
}
LOG.info("MapReduce Job is complete, status: {}, job: {}", job.isSuccessful(), context);
// NOTE: we want to report the final stats (they may change since last report and before job completed)
metricsWriter.reportStats();
// If we don't sleep, the final stats may not get sent before shutdown.
TimeUnit.SECONDS.sleep(2L);
// If the job is not successful, throw exception so that this service will terminate with a failure state
// Shutdown will still get executed, but the service will notify failure after that.
// However, if it's the job is requested to stop (via triggerShutdown, meaning it's a user action), don't throw
if (!stopRequested) {
Preconditions.checkState(job.isSuccessful(), "MapReduce execution failure: %s", job.getStatus());
}
}
@Override
protected void shutDown() throws Exception {
boolean success = job.isSuccessful();
try {
if (success) {
LOG.info("Committing MapReduce Job transaction: {}", context);
// committing long running tx: no need to commit datasets, as they were committed in external processes
// also no need to rollback changes if commit fails, as these changes where performed by mapreduce tasks
// NOTE: can't call afterCommit on datasets in this case: the changes were made by external processes.
if (!txClient.commit(transaction)) {
LOG.warn("MapReduce Job transaction failed to commit");
throw new TransactionFailureException("Failed to commit transaction for MapReduce " + context.toString());
}
} else {
// invalids long running tx. All writes done by MR cannot be undone at this point.
txClient.invalidate(transaction.getWritePointer());
}
} finally {
// whatever happens we want to call this
try {
onFinish(success);
} finally {
context.close();
cleanupTask.run();
}
}
}
@Override
protected void triggerShutdown() {
try {
stopRequested = true;
if (job != null && !job.isComplete()) {
job.killJob();
}
} catch (IOException e) {
LOG.error("Failed to kill MapReduce job {}", context, e);
throw Throwables.propagate(e);
}
}
@Override
protected Executor executor() {
// Always execute in new daemon thread.
return new Executor() {
@Override
public void execute(@Nonnull final Runnable runnable) {
final Thread t = new Thread(new Runnable() {
@Override
public void run() {
// note: this sets logging context on the thread level
LoggingContextAccessor.setLoggingContext(context.getLoggingContext());
runnable.run();
}
});
t.setDaemon(true);
t.setName(getServiceName());
t.start();
}
};
}
/**
* Sets mapper/reducer virtual cores into job configuration if the platform supports it.
*
* @param conf The job configuration
* @param vcores Number of virtual cores to use
* @param type Either {@code MAP} or {@code REDUCE}.
*/
private void setVirtualCores(Configuration conf, int vcores, String type) {
// Try to set virtual cores if the platform supports it
try {
String fieldName = type + "_CPU_VCORES";
Field field = Job.class.getField(fieldName);
conf.setInt(field.get(null).toString(), vcores);
} catch (Exception e) {
// OK to ignore
// Some older version of hadoop-mr-client doesn't has the VCORES field as vcores was not supported in YARN.
}
}
/**
* Calls the {@link MapReduce#beforeSubmit(co.cask.cdap.api.mapreduce.MapReduceContext)} method.
*/
private void beforeSubmit() throws Exception {
ClassLoader oldClassLoader = ClassLoaders.setContextClassLoader(context.getProgram().getClassLoader());
try {
mapReduce.beforeSubmit(context);
} finally {
ClassLoaders.setContextClassLoader(oldClassLoader);
}
}
/**
* Calls the {@link MapReduce#onFinish(boolean, co.cask.cdap.api.mapreduce.MapReduceContext)} method.
*/
private void onFinish(final boolean succeeded) throws TransactionFailureException, InterruptedException {
runUserCodeInTx(new TransactionExecutor.Subroutine() {
@Override
public void apply() throws Exception {
ClassLoader oldClassLoader = ClassLoaders.setContextClassLoader(context.getProgram().getClassLoader());
try {
// TODO this should be done in the output committer, to make the M/R fail if addPartition fails
boolean success = succeeded;
Dataset outputDataset = context.getOutputDataset();
if (outputDataset != null && outputDataset instanceof DatasetOutputCommitter) {
try {
if (succeeded) {
((DatasetOutputCommitter) outputDataset).onSuccess();
} else {
((DatasetOutputCommitter) outputDataset).onFailure();
}
} catch (Throwable t) {
LOG.error(String.format("Error from %s method of output dataset %s.",
succeeded ? "onSuccess" : "onFailure", context.getOutputDatasetName()), t);
success = false;
}
}
mapReduce.onFinish(success, context);
} finally {
ClassLoaders.setContextClassLoader(oldClassLoader);
}
}
}, "onFinish()");
}
// instead of using Tephra's TransactionExecutor, we must implement the transaction lifecycle
// ourselves. This is because the user code may add new datasets through the dynamic mr context,
// which is not supported by the TransactionExecutor. Instead, we reuse the same txContext
// (which is managed by the mr context) for all transactions.
private void runUserCodeInTx(TransactionExecutor.Subroutine userCode, String methodName) {
TransactionContext txContext = context.getTransactionContext();
try {
txContext.start();
userCode.apply();
txContext.finish();
} catch (TransactionFailureException e) {
abortTransaction(e, "Failed to commit after running " + methodName + ". Aborting transaction.", txContext);
} catch (Throwable t) {
abortTransaction(t, "Exception occurred running " + methodName + ". Aborting transaction.", txContext);
}
}
private void abortTransaction(Throwable t, String message, TransactionContext context) {
try {
LOG.error(message, t);
context.abort();
Throwables.propagate(t);
} catch (TransactionFailureException e) {
LOG.error("Failed to abort transaction.", e);
Throwables.propagate(e);
}
}
@SuppressWarnings("unchecked")
private void setInputDatasetIfNeeded(Job job) throws IOException {
String inputDatasetName = context.getInputDatasetName();
// TODO: It's a hack for stream
if (inputDatasetName != null && inputDatasetName.startsWith(Constants.Stream.URL_PREFIX)) {
StreamBatchReadable stream = new StreamBatchReadable(URI.create(inputDatasetName));
configureStreamInput(job, stream);
return;
}
Dataset dataset = context.getInputDataset();
if (dataset == null) {
return;
}
LOG.debug("Using Dataset {} as input for MapReduce Job", inputDatasetName);
// We checked on validation phase that it implements BatchReadable or InputFormatProvider
if (dataset instanceof BatchReadable) {
BatchReadable inputDataset = (BatchReadable) dataset;
List<Split> inputSplits = context.getInputDataSelection();
if (inputSplits == null) {
inputSplits = inputDataset.getSplits();
}
context.setInput(inputDatasetName, inputSplits);
DataSetInputFormat.setInput(job, inputDatasetName);
return;
}
// must be input format provider
InputFormatProvider inputDataset = (InputFormatProvider) dataset;
String inputFormatClassName = inputDataset.getInputFormatClassName();
if (inputFormatClassName == null) {
throw new DataSetException("Input dataset '" + inputDatasetName + "' provided null as the input format");
}
job.getConfiguration().set(Job.INPUT_FORMAT_CLASS_ATTR, inputFormatClassName);
Map<String, String> inputConfig = inputDataset.getInputFormatConfiguration();
if (inputConfig != null) {
for (Map.Entry<String, String> entry : inputConfig.entrySet()) {
job.getConfiguration().set(entry.getKey(), entry.getValue());
}
}
}
/**
* Sets the configurations for Dataset used for output.
*/
private void setOutputDatasetIfNeeded(Job job) {
String outputDatasetName = context.getOutputDatasetName();
Dataset dataset = context.getOutputDataset();
if (dataset == null) {
return;
}
LOG.debug("Using Dataset {} as output for MapReduce Job", outputDatasetName);
// We checked on validation phase that it implements BatchWritable or OutputFormatProvider
if (dataset instanceof BatchWritable) {
DataSetOutputFormat.setOutput(job, outputDatasetName);
return;
}
// must be output format provider
OutputFormatProvider outputDataset = (OutputFormatProvider) dataset;
String outputFormatClassName = outputDataset.getOutputFormatClassName();
if (outputFormatClassName == null) {
throw new DataSetException("Output dataset '" + outputDatasetName + "' provided null as the output format");
}
job.getConfiguration().set(Job.OUTPUT_FORMAT_CLASS_ATTR, outputFormatClassName);
Map<String, String> outputConfig = outputDataset.getOutputFormatConfiguration();
if (outputConfig != null) {
for (Map.Entry<String, String> entry : outputConfig.entrySet()) {
job.getConfiguration().set(entry.getKey(), entry.getValue());
}
}
}
/**
* Configures the MapReduce Job that uses stream as input.
*
* @param job The MapReduce job
* @param stream A {@link StreamBatchReadable} that carries information about the stream being used for input
* @throws IOException If fails to configure the job
*/
private void configureStreamInput(Job job, StreamBatchReadable stream) throws IOException {
Id.Stream streamId = Id.Stream.from(context.getNamespaceId(), stream.getStreamName());
StreamConfig streamConfig = streamAdmin.getConfig(streamId);
Location streamPath = StreamUtils.createGenerationLocation(streamConfig.getLocation(),
StreamUtils.getGeneration(streamConfig));
StreamInputFormat.setTTL(job, streamConfig.getTTL());
StreamInputFormat.setStreamPath(job, streamPath.toURI());
StreamInputFormat.setTimeRange(job, stream.getStartTime(), stream.getEndTime());
FormatSpecification formatSpecification = stream.getFormatSpecification();
if (formatSpecification != null) {
// this will set the decoder to the correct type. so no need to set it.
// TODO: allow type projection if the mapper type is compatible (CDAP-1149)
StreamInputFormat.setBodyFormatSpecification(job, formatSpecification);
} else {
String decoderType = stream.getDecoderType();
if (decoderType == null) {
// If the user don't specify the decoder, detect the type from Mapper/Reducer
setStreamEventDecoder(job.getConfiguration());
} else {
StreamInputFormat.setDecoderClassName(job, decoderType);
}
}
job.setInputFormatClass(StreamInputFormat.class);
try {
usageRegistry.register(context.getProgram().getId(), streamId);
} catch (Exception e) {
LOG.warn("Failed to register usage {} -> {}", context.getProgram().getId(), streamId, e);
}
LOG.info("Using Stream as input from {}", streamPath.toURI());
}
/**
* Detects what {@link StreamEventDecoder} to use based on the job Mapper/Reducer type. It does so by
* inspecting the Mapper/Reducer type parameters to figure out what the input type is, and pick the appropriate
* {@link StreamEventDecoder}.
*
* @param hConf The job configuration
* @throws IOException If fails to detect what decoder to use for decoding StreamEvent.
*/
@VisibleForTesting
void setStreamEventDecoder(Configuration hConf) throws IOException {
// Try to set from mapper
TypeToken<Mapper> mapperType = resolveClass(hConf, MRJobConfig.MAP_CLASS_ATTR, Mapper.class);
if (mapperType != null) {
setStreamEventDecoder(hConf, mapperType);
return;
}
// If there is no Mapper, it's a Reducer only job, hence get the decoder type from Reducer class
TypeToken<Reducer> reducerType = resolveClass(hConf, MRJobConfig.REDUCE_CLASS_ATTR, Reducer.class);
setStreamEventDecoder(hConf, reducerType);
}
/**
* Optionally sets the {@link StreamEventDecoder}.
*
* @throws IOException If the type is an instance of {@link ParameterizedType} and is not able to determine
* what {@link StreamEventDecoder} class should use.
*
* @param <V> type of the super class
*/
private <V> void setStreamEventDecoder(Configuration hConf, TypeToken<V> type) throws IOException {
// The super type must be a parametrized type with <IN_KEY, IN_VALUE, OUT_KEY, OUT_VALUE>
Type valueType = StreamEvent.class;
if ((type.getType() instanceof ParameterizedType)) {
// Try to determine the decoder to use from the first input types
// The first argument must be LongWritable for it to consumer stream event, as it carries the event timestamp
Type inputValueType = ((ParameterizedType) type.getType()).getActualTypeArguments()[1];
// If the Mapper/Reducer class is not parameterized (meaning not extends with parameters),
// then assume StreamEvent as the input value type.
// We need to check if the TypeVariable is the same as the one in the parent type.
// This avoid the case where a subclass that has "class InvalidMapper<I, O> extends Mapper<I, O>"
if (inputValueType instanceof TypeVariable && inputValueType.equals(type.getRawType().getTypeParameters()[1])) {
inputValueType = StreamEvent.class;
}
// Only Class type is support for inferring stream decoder class
if (!(inputValueType instanceof Class)) {
throw new IllegalArgumentException("Input value type not supported for stream input: " + type);
}
valueType = inputValueType;
}
try {
StreamInputFormat.inferDecoderClass(hConf, valueType);
} catch (IllegalArgumentException e) {
throw new IOException("Type not support for consuming StreamEvent from " + type, e);
}
}
private String getJobName(BasicMapReduceContext context) {
Id.Program programId = context.getProgram().getId();
// MRJobClient expects the following format (for RunId to be the first component)
return String.format("%s.%s.%s.%s.%s",
context.getRunId().getId(), ProgramType.MAPREDUCE.name().toLowerCase(),
programId.getNamespaceId(), programId.getApplicationId(), programId.getId());
}
/**
* Creates a jar that contains everything that are needed for running the MapReduce program by Hadoop.
*
* @return a new {@link Location} containing the job jar
*/
private Location buildJobJar(BasicMapReduceContext context) throws IOException {
// Excludes libraries that are for sure not needed.
// Hadoop - Available from the cluster
// Spark - MR never uses Spark
ApplicationBundler appBundler = new ApplicationBundler(ImmutableList.of("org.apache.hadoop",
"org.apache.spark"),
ImmutableList.of("org.apache.hadoop.hbase",
"org.apache.hadoop.hive"));
Id.Program programId = context.getProgram().getId();
Location jobJar =
locationFactory.create(String.format("%s.%s.%s.%s.%s.jar",
ProgramType.MAPREDUCE.name().toLowerCase(),
programId.getNamespaceId(), programId.getApplicationId(),
programId.getId(), context.getRunId().getId()));
LOG.debug("Creating Job jar: {}", jobJar.toURI());
Set<Class<?>> classes = Sets.newHashSet();
classes.add(MapReduce.class);
classes.add(MapperWrapper.class);
classes.add(ReducerWrapper.class);
Job jobConf = context.getHadoopJob();
// We only need to trace the Input/OutputFormat class due to MAPREDUCE-5957 so that those classes are included
// in the job.jar and be available in the MR system classpath before our job classloader (ApplicationClassLoader)
// take over the classloading.
if (cConf.getBoolean(Constants.AppFabric.MAPREDUCE_INCLUDE_CUSTOM_CLASSES)) {
try {
Class<? extends InputFormat<?, ?>> inputFormatClass = jobConf.getInputFormatClass();
LOG.info("InputFormat class: {} {}", inputFormatClass, inputFormatClass.getClassLoader());
classes.add(inputFormatClass);
// If it is StreamInputFormat, also add the StreamEventCodec class as well.
if (StreamInputFormat.class.isAssignableFrom(inputFormatClass)) {
Class<? extends StreamEventDecoder> decoderType =
StreamInputFormat.getDecoderClass(jobConf.getConfiguration());
if (decoderType != null) {
classes.add(decoderType);
}
}
} catch (Throwable t) {
LOG.info("InputFormat class not found: {}", t.getMessage(), t);
// Ignore
}
try {
Class<? extends OutputFormat<?, ?>> outputFormatClass = jobConf.getOutputFormatClass();
LOG.info("OutputFormat class: {} {}", outputFormatClass, outputFormatClass.getClassLoader());
classes.add(outputFormatClass);
} catch (Throwable t) {
LOG.info("OutputFormat class not found: {}", t.getMessage(), t);
// Ignore
}
}
// End of MAPREDUCE-5957.
try {
Class<?> hbaseTableUtilClass = HBaseTableUtilFactory.getHBaseTableUtilClass();
classes.add(hbaseTableUtilClass);
} catch (ProvisionException e) {
LOG.warn("Not including HBaseTableUtil classes in submitted Job Jar since they are not available");
}
ClassLoader oldCLassLoader = ClassLoaders.setContextClassLoader(jobConf.getConfiguration().getClassLoader());
appBundler.createBundle(jobJar, classes);
ClassLoaders.setContextClassLoader(oldCLassLoader);
LOG.info("Built MapReduce Job Jar at {}", jobJar.toURI());
return jobJar;
}
/**
* Returns a resolved {@link TypeToken} of the given super type by reading a class from the job configuration that
* extends from super type.
*
* @param conf the job configuration
* @param typeAttr The job configuration attribute for getting the user class
* @param superType Super type of the class to get from the configuration
* @param <V> Type of the super type
* @return A resolved {@link TypeToken} or {@code null} if no such class in the job configuration
*/
@SuppressWarnings("unchecked")
private <V> TypeToken<V> resolveClass(Configuration conf, String typeAttr, Class<V> superType) {
Class<? extends V> userClass = conf.getClass(typeAttr, null, superType);
if (userClass == null) {
return null;
}
return (TypeToken<V>) TypeToken.of(userClass).getSupertype(superType);
}
/**
* Sets the output key and value classes in the job configuration by inspecting the {@link Mapper} and {@link Reducer}
* if it is not set by the user.
*
* @param job the MapReduce job
*/
private void setOutputClassesIfNeeded(Job job) {
Configuration conf = job.getConfiguration();
// Try to get the type from reducer
TypeToken<?> type = resolveClass(conf, MRJobConfig.REDUCE_CLASS_ATTR, Reducer.class);
if (type == null) {
// Map only job
type = resolveClass(conf, MRJobConfig.MAP_CLASS_ATTR, Mapper.class);
}
// If not able to detect type, nothing to set
if (type == null || !(type.getType() instanceof ParameterizedType)) {
return;
}
Type[] typeArgs = ((ParameterizedType) type.getType()).getActualTypeArguments();
// Set it only if the user didn't set it in beforeSubmit
// The key and value type are in the 3rd and 4th type parameters
if (!isProgrammaticConfig(conf, MRJobConfig.OUTPUT_KEY_CLASS)) {
Class<?> cls = TypeToken.of(typeArgs[2]).getRawType();
LOG.debug("Set output key class to {}", cls);
job.setOutputKeyClass(cls);
}
if (!isProgrammaticConfig(conf, MRJobConfig.OUTPUT_VALUE_CLASS)) {
Class<?> cls = TypeToken.of(typeArgs[3]).getRawType();
LOG.debug("Set output value class to {}", cls);
job.setOutputValueClass(cls);
}
}
/**
* Sets the map output key and value classes in the job configuration by inspecting the {@link Mapper}
* if it is not set by the user.
*
* @param job the MapReduce job
*/
private void setMapOutputClassesIfNeeded(Job job) {
Configuration conf = job.getConfiguration();
int keyIdx = 2;
int valueIdx = 3;
TypeToken<?> type = resolveClass(conf, MRJobConfig.MAP_CLASS_ATTR, Mapper.class);
if (type == null) {
// Reducer only job. Use the Reducer input types as the key/value classes.
type = resolveClass(conf, MRJobConfig.REDUCE_CLASS_ATTR, Reducer.class);
keyIdx = 0;
valueIdx = 1;
}
// If not able to detect type, nothing to set.
if (type == null || !(type.getType() instanceof ParameterizedType)) {
return;
}
Type[] typeArgs = ((ParameterizedType) type.getType()).getActualTypeArguments();
// Set it only if the user didn't set it in beforeSubmit
// The key and value type are in the 3rd and 4th type parameters
if (!isProgrammaticConfig(conf, MRJobConfig.MAP_OUTPUT_KEY_CLASS)) {
Class<?> cls = TypeToken.of(typeArgs[keyIdx]).getRawType();
LOG.debug("Set map output key class to {}", cls);
job.setMapOutputKeyClass(cls);
}
if (!isProgrammaticConfig(conf, MRJobConfig.MAP_OUTPUT_VALUE_CLASS)) {
Class<?> cls = TypeToken.of(typeArgs[valueIdx]).getRawType();
LOG.debug("Set map output value class to {}", cls);
job.setMapOutputValueClass(cls);
}
}
private boolean isProgrammaticConfig(Configuration conf, String name) {
String[] sources = conf.getPropertySources(name);
return sources != null && sources.length > 0 && PROGRAMMATIC_SOURCE.equals(sources[sources.length - 1]);
}
/**
* Creates a temp copy of the program jar.
*
* @return a new {@link Location} which contains the same content as the program jar
*/
private Location copyProgramJar() throws IOException {
Id.Program programId = context.getProgram().getId();
Location programJarCopy = locationFactory.create(
String.format("%s.%s.%s.%s.%s.program.jar",
ProgramType.MAPREDUCE.name().toLowerCase(),
programId.getNamespaceId(), programId.getApplicationId(),
programId.getId(), context.getRunId().getId()));
ByteStreams.copy(Locations.newInputSupplier(programJarLocation), Locations.newOutputSupplier(programJarCopy));
LOG.info("Copied Program Jar to {}, source: {}", programJarCopy.toURI(), programJarLocation.toURI());
return programJarCopy;
}
/**
* Creates a JAR file that contains all the plugin jars that are needed by the job. The plugin directory
* structure is maintained inside the jar so that MR framework can correctly expand and recreate the required
* structure.
*
* @return the {@link Location} for the archive file or {@code null} if there is no plugin files need to be localized
*/
@Nullable
private Location createPluginArchive(@Nullable AdapterDefinition adapterSpec,
Id.Program programId) throws IOException {
if (adapterSpec == null) {
return null;
}
Set<PluginInfo> pluginInfos = adapterSpec.getPluginInfos();
if (pluginInfos.isEmpty()) {
return null;
}
// Find plugins that are used by this adapter.
File pluginDir = new File(cConf.get(Constants.AppFabric.APP_TEMPLATE_PLUGIN_DIR));
File templatePluginDir = new File(pluginDir, adapterSpec.getTemplate());
File jarFile = File.createTempFile("plugin", ".jar");
try {
String entryPrefix = pluginDir.getName() + "/" + adapterSpec.getTemplate();
try (JarOutputStream output = new JarOutputStream(new FileOutputStream(jarFile))) {
// Create the directory entries
output.putNextEntry(new JarEntry(entryPrefix + "/"));
output.putNextEntry(new JarEntry(entryPrefix + "/lib/"));
// copy the plugin jars
for (PluginInfo plugin : pluginInfos) {
String entryName = String.format("%s/%s", entryPrefix, plugin.getFileName());
output.putNextEntry(new JarEntry(entryName));
Files.copy(new File(templatePluginDir, plugin.getFileName()), output);
}
// copy the common plugin lib jars
for (File libJar : DirUtils.listFiles(new File(templatePluginDir, "lib"), "jar")) {
String entryName = String.format("%s/lib/%s", entryPrefix, libJar.getName());
output.putNextEntry(new JarEntry(entryName));
Files.copy(libJar, output);
}
}
// Copy the jar to a location, based on the location factory
Location location = locationFactory.create(
String.format("%s.%s.%s.%s.%s.plugins.jar",
ProgramType.MAPREDUCE.name().toLowerCase(),
programId.getNamespaceId(), programId.getApplicationId(),
programId.getId(), context.getRunId().getId()));
try {
Files.copy(jarFile, Locations.newOutputSupplier(location));
return location;
} catch (IOException e) {
Locations.deleteQuietly(location);
throw e;
}
} finally {
jarFile.delete();
}
}
private Runnable createCleanupTask(final Location... locations) {
return new Runnable() {
@Override
public void run() {
for (Location location : locations) {
if (location != null) {
Locations.deleteQuietly(location);
}
}
}
};
}
}
| cdap-app-fabric/src/main/java/co/cask/cdap/internal/app/runtime/batch/MapReduceRuntimeService.java | /*
* Copyright © 2014-2015 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package co.cask.cdap.internal.app.runtime.batch;
import co.cask.cdap.api.Resources;
import co.cask.cdap.api.data.batch.BatchReadable;
import co.cask.cdap.api.data.batch.BatchWritable;
import co.cask.cdap.api.data.batch.DatasetOutputCommitter;
import co.cask.cdap.api.data.batch.InputFormatProvider;
import co.cask.cdap.api.data.batch.OutputFormatProvider;
import co.cask.cdap.api.data.batch.Split;
import co.cask.cdap.api.data.format.FormatSpecification;
import co.cask.cdap.api.data.stream.StreamBatchReadable;
import co.cask.cdap.api.dataset.DataSetException;
import co.cask.cdap.api.dataset.Dataset;
import co.cask.cdap.api.flow.flowlet.StreamEvent;
import co.cask.cdap.api.mapreduce.MapReduce;
import co.cask.cdap.api.mapreduce.MapReduceSpecification;
import co.cask.cdap.api.stream.StreamEventDecoder;
import co.cask.cdap.api.templates.plugins.PluginInfo;
import co.cask.cdap.common.conf.CConfiguration;
import co.cask.cdap.common.conf.Constants;
import co.cask.cdap.common.io.Locations;
import co.cask.cdap.common.lang.ClassLoaders;
import co.cask.cdap.common.lang.WeakReferenceDelegatorClassLoader;
import co.cask.cdap.common.logging.LoggingContextAccessor;
import co.cask.cdap.common.utils.ApplicationBundler;
import co.cask.cdap.common.utils.DirUtils;
import co.cask.cdap.data.stream.StreamInputFormat;
import co.cask.cdap.data.stream.StreamUtils;
import co.cask.cdap.data2.registry.UsageRegistry;
import co.cask.cdap.data2.transaction.Transactions;
import co.cask.cdap.data2.transaction.stream.StreamAdmin;
import co.cask.cdap.data2.transaction.stream.StreamConfig;
import co.cask.cdap.data2.util.hbase.HBaseTableUtilFactory;
import co.cask.cdap.internal.app.runtime.batch.dataset.DataSetInputFormat;
import co.cask.cdap.internal.app.runtime.batch.dataset.DataSetOutputFormat;
import co.cask.cdap.proto.Id;
import co.cask.cdap.proto.ProgramType;
import co.cask.cdap.templates.AdapterDefinition;
import co.cask.tephra.Transaction;
import co.cask.tephra.TransactionContext;
import co.cask.tephra.TransactionExecutor;
import co.cask.tephra.TransactionFailureException;
import co.cask.tephra.TransactionSystemClient;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import com.google.common.io.ByteStreams;
import com.google.common.io.Files;
import com.google.common.reflect.TypeToken;
import com.google.common.util.concurrent.AbstractExecutionThreadService;
import com.google.inject.ProvisionException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.MRJobConfig;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.OutputFormat;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.twill.filesystem.Location;
import org.apache.twill.filesystem.LocationFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Performs the actual execution of mapreduce job.
*
* Service start -> Performs job setup, beforeSubmit and submit job
* Service run -> Poll for job completion
* Service triggerStop -> kill job
* Service stop -> Commit/abort transaction, onFinish, cleanup
*/
final class MapReduceRuntimeService extends AbstractExecutionThreadService {
private static final Logger LOG = LoggerFactory.getLogger(MapReduceRuntimeService.class);
/**
* Do not remove: we need this variable for loading MRClientSecurityInfo class required for communicating with
* AM in secure mode.
*/
@SuppressWarnings("unused")
private org.apache.hadoop.mapreduce.v2.app.MRClientSecurityInfo mrClientSecurityInfo;
// Name of configuration source if it is set programmatically. This constant is not defined in Hadoop
private static final String PROGRAMMATIC_SOURCE = "programmatically";
private final CConfiguration cConf;
private final Configuration hConf;
private final MapReduce mapReduce;
private final MapReduceSpecification specification;
private final Location programJarLocation;
private final DynamicMapReduceContext context;
private final LocationFactory locationFactory;
private final StreamAdmin streamAdmin;
private final TransactionSystemClient txClient;
private final UsageRegistry usageRegistry;
private Job job;
private Transaction transaction;
private Runnable cleanupTask;
private ClassLoader classLoader;
private volatile boolean stopRequested;
MapReduceRuntimeService(CConfiguration cConf, Configuration hConf,
MapReduce mapReduce, MapReduceSpecification specification,
DynamicMapReduceContext context,
Location programJarLocation, LocationFactory locationFactory,
StreamAdmin streamAdmin, TransactionSystemClient txClient,
UsageRegistry usageRegistry) {
this.cConf = cConf;
this.hConf = hConf;
this.mapReduce = mapReduce;
this.specification = specification;
this.programJarLocation = programJarLocation;
this.locationFactory = locationFactory;
this.streamAdmin = streamAdmin;
this.txClient = txClient;
this.context = context;
this.usageRegistry = usageRegistry;
}
@Override
protected String getServiceName() {
return "MapReduceRunner-" + specification.getName();
}
@Override
protected void startUp() throws Exception {
final Job job = Job.getInstance(new Configuration(hConf));
job.setJobName(getJobName(context));
Configuration mapredConf = job.getConfiguration();
if (UserGroupInformation.isSecurityEnabled()) {
// If runs in secure cluster, this program runner is running in a yarn container, hence not able
// to get authenticated with the history.
mapredConf.unset("mapreduce.jobhistory.address");
mapredConf.setBoolean(Job.JOB_AM_ACCESS_DISABLED, false);
Credentials credentials = UserGroupInformation.getCurrentUser().getCredentials();
LOG.info("Running in secure mode; adding all user credentials: {}", credentials.getAllTokens());
job.getCredentials().addAll(credentials);
}
// We need to hold a strong reference to the ClassLoader until the end of the MapReduce job.
classLoader = new MapReduceClassLoader(context.getProgram().getClassLoader());
job.getConfiguration().setClassLoader(new WeakReferenceDelegatorClassLoader(classLoader));
ClassLoaders.setContextClassLoader(job.getConfiguration().getClassLoader());
context.setJob(job);
// both beforeSubmit() and setInput/OutputDataset() may call dataset methods. They must be run inside a tx
runUserCodeInTx(new TransactionExecutor.Subroutine() {
// Call the user MapReduce for initialization
@Override
public void apply() throws Exception {
beforeSubmit();
// set input/output datasets info
setInputDatasetIfNeeded(job);
setOutputDatasetIfNeeded(job);
}
}, "startUp()");
// After calling beforeSubmit, we know what plugins are needed for adapter, hence construct the proper
// ClassLoader from here and use it for setting up the job
Location pluginArchive = createPluginArchive(context.getAdapterSpecification(), context.getProgram().getId());
try {
if (pluginArchive != null) {
job.addCacheArchive(pluginArchive.toURI());
}
// Alter the configuration ClassLoader to a MapReduceClassLoader that supports plugin
// It is mainly for standalone mode to have the same ClassLoader as in distributed mode
// It can only be constructed here because we need to have all adapter plugins information
classLoader = new MapReduceClassLoader(context.getProgram().getClassLoader(), context.getAdapterSpecification(),
context.getPluginInstantiator());
job.getConfiguration().setClassLoader(new WeakReferenceDelegatorClassLoader(classLoader));
ClassLoaders.setContextClassLoader(job.getConfiguration().getClassLoader());
setOutputClassesIfNeeded(job);
setMapOutputClassesIfNeeded(job);
// Prefer our job jar in the classpath
// Set both old and new keys
mapredConf.setBoolean("mapreduce.user.classpath.first", true);
mapredConf.setBoolean(Job.MAPREDUCE_JOB_USER_CLASSPATH_FIRST, true);
mapredConf.setBoolean(Job.MAPREDUCE_JOB_CLASSLOADER, true);
// Make CDAP classes (which is in the job.jar created below) to have higher precedence
// It is needed to override the ApplicationClassLoader to use our implementation
String yarnAppClassPath = mapredConf.get(YarnConfiguration.YARN_APPLICATION_CLASSPATH, Joiner.on(',')
.join(YarnConfiguration.DEFAULT_YARN_APPLICATION_CLASSPATH));
mapredConf.set(YarnConfiguration.YARN_APPLICATION_CLASSPATH, "job.jar/lib/*,job.jar/classes," + yarnAppClassPath);
// set resources for the job
Resources mapperResources = context.getMapperResources();
Resources reducerResources = context.getReducerResources();
// this will determine how much memory and virtual cores the yarn container will run with
if (mapperResources != null) {
mapredConf.setInt(Job.MAP_MEMORY_MB, mapperResources.getMemoryMB());
// Also set the Xmx to be smaller than the container memory.
mapredConf.set(Job.MAP_JAVA_OPTS, "-Xmx" + (int) (mapperResources.getMemoryMB() * 0.8) + "m");
setVirtualCores(mapredConf, mapperResources.getVirtualCores(), "MAP");
}
if (reducerResources != null) {
mapredConf.setInt(Job.REDUCE_MEMORY_MB, reducerResources.getMemoryMB());
// Also set the Xmx to be smaller than the container memory.
mapredConf.set(Job.REDUCE_JAVA_OPTS, "-Xmx" + (int) (reducerResources.getMemoryMB() * 0.8) + "m");
setVirtualCores(mapredConf, reducerResources.getVirtualCores(), "REDUCE");
}
// replace user's Mapper & Reducer's with our wrappers in job config
MapperWrapper.wrap(job);
ReducerWrapper.wrap(job);
// packaging job jar which includes cdap classes with dependencies
Location jobJar = buildJobJar(context);
try {
Location programJarCopy = copyProgramJar();
try {
job.setJar(jobJar.toURI().toString());
// Localize the program jar, but not add it to class path
// The ApplicationLoader will create ProgramClassLoader from it
job.addCacheFile(programJarCopy.toURI());
MapReduceContextConfig contextConfig = new MapReduceContextConfig(job.getConfiguration());
// We start long-running tx to be used by mapreduce job tasks.
Transaction tx = txClient.startLong();
try {
// We remember tx, so that we can re-use it in mapreduce tasks
// Make a copy of the conf and rewrite the template plugin directory to be the plugin archive name
CConfiguration cConfCopy = cConf;
if (pluginArchive != null) {
cConfCopy = CConfiguration.copy(cConf);
cConfCopy.set(Constants.AppFabric.APP_TEMPLATE_DIR, pluginArchive.getName());
}
contextConfig.set(context, cConfCopy, tx, programJarCopy.toURI());
LOG.info("Submitting MapReduce Job: {}", context);
// submits job and returns immediately. Shouldn't need to set context ClassLoader.
job.submit();
this.job = job;
this.transaction = tx;
this.cleanupTask = createCleanupTask(jobJar, programJarCopy, pluginArchive);
} catch (Throwable t) {
Transactions.invalidateQuietly(txClient, tx);
throw Throwables.propagate(t);
}
} catch (Throwable t) {
Locations.deleteQuietly(programJarCopy);
throw Throwables.propagate(t);
}
} catch (Throwable t) {
Locations.deleteQuietly(jobJar);
throw Throwables.propagate(t);
}
} catch (Throwable t) {
if (pluginArchive != null) {
Locations.deleteQuietly(pluginArchive);
}
LOG.error("Exception when submitting MapReduce Job: {}", context, t);
throw Throwables.propagate(t);
}
}
@Override
protected void run() throws Exception {
MapReduceMetricsWriter metricsWriter = new MapReduceMetricsWriter(job, context);
// until job is complete report stats
while (!job.isComplete()) {
metricsWriter.reportStats();
// we report to metrics backend every second, so 1 sec is enough here. That's mapreduce job anyways (not
// short) ;)
TimeUnit.SECONDS.sleep(1);
}
LOG.info("MapReduce Job is complete, status: {}, job: {}", job.isSuccessful(), context);
// NOTE: we want to report the final stats (they may change since last report and before job completed)
metricsWriter.reportStats();
// If we don't sleep, the final stats may not get sent before shutdown.
TimeUnit.SECONDS.sleep(2L);
// If the job is not successful, throw exception so that this service will terminate with a failure state
// Shutdown will still get executed, but the service will notify failure after that.
// However, if it's the job is requested to stop (via triggerShutdown, meaning it's a user action), don't throw
if (!stopRequested) {
Preconditions.checkState(job.isSuccessful(), "MapReduce execution failure: %s", job.getStatus());
}
}
@Override
protected void shutDown() throws Exception {
boolean success = job.isSuccessful();
try {
if (success) {
LOG.info("Committing MapReduce Job transaction: {}", context);
// committing long running tx: no need to commit datasets, as they were committed in external processes
// also no need to rollback changes if commit fails, as these changes where performed by mapreduce tasks
// NOTE: can't call afterCommit on datasets in this case: the changes were made by external processes.
if (!txClient.commit(transaction)) {
LOG.warn("MapReduce Job transaction failed to commit");
throw new TransactionFailureException("Failed to commit transaction for MapReduce " + context.toString());
}
} else {
// invalids long running tx. All writes done by MR cannot be undone at this point.
txClient.invalidate(transaction.getWritePointer());
}
} finally {
// whatever happens we want to call this
try {
onFinish(success);
} finally {
context.close();
cleanupTask.run();
}
}
}
@Override
protected void triggerShutdown() {
try {
stopRequested = true;
if (job != null && !job.isComplete()) {
job.killJob();
}
} catch (IOException e) {
LOG.error("Failed to kill MapReduce job {}", context, e);
throw Throwables.propagate(e);
}
}
@Override
protected Executor executor() {
// Always execute in new daemon thread.
return new Executor() {
@Override
public void execute(@Nonnull final Runnable runnable) {
final Thread t = new Thread(new Runnable() {
@Override
public void run() {
// note: this sets logging context on the thread level
LoggingContextAccessor.setLoggingContext(context.getLoggingContext());
runnable.run();
}
});
t.setDaemon(true);
t.setName(getServiceName());
t.start();
}
};
}
/**
* Sets mapper/reducer virtual cores into job configuration if the platform supports it.
*
* @param conf The job configuration
* @param vcores Number of virtual cores to use
* @param type Either {@code MAP} or {@code REDUCE}.
*/
private void setVirtualCores(Configuration conf, int vcores, String type) {
// Try to set virtual cores if the platform supports it
try {
String fieldName = type + "_CPU_VCORES";
Field field = Job.class.getField(fieldName);
conf.setInt(field.get(null).toString(), vcores);
} catch (Exception e) {
// OK to ignore
// Some older version of hadoop-mr-client doesn't has the VCORES field as vcores was not supported in YARN.
}
}
/**
* Calls the {@link MapReduce#beforeSubmit(co.cask.cdap.api.mapreduce.MapReduceContext)} method.
*/
private void beforeSubmit() throws Exception {
ClassLoader oldClassLoader = ClassLoaders.setContextClassLoader(context.getProgram().getClassLoader());
try {
mapReduce.beforeSubmit(context);
} finally {
ClassLoaders.setContextClassLoader(oldClassLoader);
}
}
/**
* Calls the {@link MapReduce#onFinish(boolean, co.cask.cdap.api.mapreduce.MapReduceContext)} method.
*/
private void onFinish(final boolean succeeded) throws TransactionFailureException, InterruptedException {
runUserCodeInTx(new TransactionExecutor.Subroutine() {
@Override
public void apply() throws Exception {
ClassLoader oldClassLoader = ClassLoaders.setContextClassLoader(context.getProgram().getClassLoader());
try {
// TODO this should be done in the output committer, to make the M/R fail if addPartition fails
boolean success = succeeded;
Dataset outputDataset = context.getOutputDataset();
if (outputDataset != null && outputDataset instanceof DatasetOutputCommitter) {
try {
if (succeeded) {
((DatasetOutputCommitter) outputDataset).onSuccess();
} else {
((DatasetOutputCommitter) outputDataset).onFailure();
}
} catch (Throwable t) {
LOG.error(String.format("Error from %s method of output dataset %s.",
succeeded ? "onSuccess" : "onFailure", context.getOutputDatasetName()), t);
success = false;
}
}
mapReduce.onFinish(success, context);
} finally {
ClassLoaders.setContextClassLoader(oldClassLoader);
}
}
}, "onFinish()");
}
// instead of using Tephra's TransactionExecutor, we must implement the transaction lifecycle
// ourselves. This is because the user code may add new datasets through the dynamic mr context,
// which is not supported by the TransactionExecutor. Instead, we reuse the same txContext
// (which is managed by the mr context) for all transactions.
private void runUserCodeInTx(TransactionExecutor.Subroutine userCode, String methodName) {
TransactionContext txContext = context.getTransactionContext();
try {
txContext.start();
userCode.apply();
txContext.finish();
} catch (TransactionFailureException e) {
abortTransaction(e, "Failed to commit after running " + methodName + ". Aborting transaction.", txContext);
} catch (Throwable t) {
abortTransaction(t, "Exception occurred running " + methodName + ". Aborting transaction.", txContext);
}
}
private void abortTransaction(Throwable t, String message, TransactionContext context) {
try {
LOG.error(message, t);
context.abort();
Throwables.propagate(t);
} catch (TransactionFailureException e) {
LOG.error("Failed to abort transaction.", e);
Throwables.propagate(e);
}
}
@SuppressWarnings("unchecked")
private void setInputDatasetIfNeeded(Job job) throws IOException {
String inputDatasetName = context.getInputDatasetName();
// TODO: It's a hack for stream
if (inputDatasetName != null && inputDatasetName.startsWith(Constants.Stream.URL_PREFIX)) {
StreamBatchReadable stream = new StreamBatchReadable(URI.create(inputDatasetName));
configureStreamInput(job, stream);
return;
}
Dataset dataset = context.getInputDataset();
if (dataset == null) {
return;
}
LOG.debug("Using Dataset {} as input for MapReduce Job", inputDatasetName);
// We checked on validation phase that it implements BatchReadable or InputFormatProvider
if (dataset instanceof BatchReadable) {
BatchReadable inputDataset = (BatchReadable) dataset;
List<Split> inputSplits = context.getInputDataSelection();
if (inputSplits == null) {
inputSplits = inputDataset.getSplits();
}
context.setInput(inputDatasetName, inputSplits);
DataSetInputFormat.setInput(job, inputDatasetName);
return;
}
// must be input format provider
InputFormatProvider inputDataset = (InputFormatProvider) dataset;
String inputFormatClassName = inputDataset.getInputFormatClassName();
if (inputFormatClassName == null) {
throw new DataSetException("Input dataset '" + inputDatasetName + "' provided null as the input format");
}
job.getConfiguration().set(Job.INPUT_FORMAT_CLASS_ATTR, inputFormatClassName);
Map<String, String> inputConfig = inputDataset.getInputFormatConfiguration();
if (inputConfig != null) {
for (Map.Entry<String, String> entry : inputConfig.entrySet()) {
job.getConfiguration().set(entry.getKey(), entry.getValue());
}
}
}
/**
* Sets the configurations for Dataset used for output.
*/
private void setOutputDatasetIfNeeded(Job job) {
String outputDatasetName = context.getOutputDatasetName();
Dataset dataset = context.getOutputDataset();
if (dataset == null) {
return;
}
LOG.debug("Using Dataset {} as output for MapReduce Job", outputDatasetName);
// We checked on validation phase that it implements BatchWritable or OutputFormatProvider
if (dataset instanceof BatchWritable) {
DataSetOutputFormat.setOutput(job, outputDatasetName);
return;
}
// must be output format provider
OutputFormatProvider outputDataset = (OutputFormatProvider) dataset;
String outputFormatClassName = outputDataset.getOutputFormatClassName();
if (outputFormatClassName == null) {
throw new DataSetException("Output dataset '" + outputDatasetName + "' provided null as the output format");
}
job.getConfiguration().set(Job.OUTPUT_FORMAT_CLASS_ATTR, outputFormatClassName);
Map<String, String> outputConfig = outputDataset.getOutputFormatConfiguration();
if (outputConfig != null) {
for (Map.Entry<String, String> entry : outputConfig.entrySet()) {
job.getConfiguration().set(entry.getKey(), entry.getValue());
}
}
}
/**
* Configures the MapReduce Job that uses stream as input.
*
* @param job The MapReduce job
* @param stream A {@link StreamBatchReadable} that carries information about the stream being used for input
* @throws IOException If fails to configure the job
*/
private void configureStreamInput(Job job, StreamBatchReadable stream) throws IOException {
Id.Stream streamId = Id.Stream.from(context.getNamespaceId(), stream.getStreamName());
StreamConfig streamConfig = streamAdmin.getConfig(streamId);
Location streamPath = StreamUtils.createGenerationLocation(streamConfig.getLocation(),
StreamUtils.getGeneration(streamConfig));
StreamInputFormat.setTTL(job, streamConfig.getTTL());
StreamInputFormat.setStreamPath(job, streamPath.toURI());
StreamInputFormat.setTimeRange(job, stream.getStartTime(), stream.getEndTime());
FormatSpecification formatSpecification = stream.getFormatSpecification();
if (formatSpecification != null) {
// this will set the decoder to the correct type. so no need to set it.
// TODO: allow type projection if the mapper type is compatible (CDAP-1149)
StreamInputFormat.setBodyFormatSpecification(job, formatSpecification);
} else {
String decoderType = stream.getDecoderType();
if (decoderType == null) {
// If the user don't specify the decoder, detect the type from Mapper/Reducer
setStreamEventDecoder(job.getConfiguration());
} else {
StreamInputFormat.setDecoderClassName(job, decoderType);
}
}
job.setInputFormatClass(StreamInputFormat.class);
try {
usageRegistry.register(context.getProgram().getId(), streamId);
} catch (Exception e) {
LOG.warn("Failed to register usage {} -> {}", context.getProgram().getId(), streamId, e);
}
LOG.info("Using Stream as input from {}", streamPath.toURI());
}
/**
* Detects what {@link StreamEventDecoder} to use based on the job Mapper/Reducer type. It does so by
* inspecting the Mapper/Reducer type parameters to figure out what the input type is, and pick the appropriate
* {@link StreamEventDecoder}.
*
* @param hConf The job configuration
* @throws IOException If fails to detect what decoder to use for decoding StreamEvent.
*/
@VisibleForTesting
void setStreamEventDecoder(Configuration hConf) throws IOException {
// Try to set from mapper
TypeToken<Mapper> mapperType = resolveClass(hConf, MRJobConfig.MAP_CLASS_ATTR, Mapper.class);
if (mapperType != null) {
setStreamEventDecoder(hConf, mapperType);
return;
}
// If there is no Mapper, it's a Reducer only job, hence get the decoder type from Reducer class
TypeToken<Reducer> reducerType = resolveClass(hConf, MRJobConfig.REDUCE_CLASS_ATTR, Reducer.class);
setStreamEventDecoder(hConf, reducerType);
}
/**
* Optionally sets the {@link StreamEventDecoder}.
*
* @throws IOException If the type is an instance of {@link ParameterizedType} and is not able to determine
* what {@link StreamEventDecoder} class should use.
*
* @param <V> type of the super class
*/
private <V> void setStreamEventDecoder(Configuration hConf, TypeToken<V> type) throws IOException {
// The super type must be a parametrized type with <IN_KEY, IN_VALUE, OUT_KEY, OUT_VALUE>
Type valueType = StreamEvent.class;
if ((type.getType() instanceof ParameterizedType)) {
// Try to determine the decoder to use from the first input types
// The first argument must be LongWritable for it to consumer stream event, as it carries the event timestamp
Type inputValueType = ((ParameterizedType) type.getType()).getActualTypeArguments()[1];
// If the Mapper/Reducer class is not parameterized (meaning not extends with parameters),
// then assume StreamEvent as the input value type.
// We need to check if the TypeVariable is the same as the one in the parent type.
// This avoid the case where a subclass that has "class InvalidMapper<I, O> extends Mapper<I, O>"
if (inputValueType instanceof TypeVariable && inputValueType.equals(type.getRawType().getTypeParameters()[1])) {
inputValueType = StreamEvent.class;
}
// Only Class type is support for inferring stream decoder class
if (!(inputValueType instanceof Class)) {
throw new IllegalArgumentException("Input value type not supported for stream input: " + type);
}
valueType = inputValueType;
}
try {
StreamInputFormat.inferDecoderClass(hConf, valueType);
} catch (IllegalArgumentException e) {
throw new IOException("Type not support for consuming StreamEvent from " + type, e);
}
}
private String getJobName(BasicMapReduceContext context) {
Id.Program programId = context.getProgram().getId();
// MRJobClient expects the following format (for RunId to be the first component)
return String.format("%s.%s.%s.%s.%s",
context.getRunId().getId(), ProgramType.MAPREDUCE.name().toLowerCase(),
programId.getNamespaceId(), programId.getApplicationId(), programId.getId());
}
/**
* Creates a jar that contains everything that are needed for running the MapReduce program by Hadoop.
*
* @return a new {@link Location} containing the job jar
*/
private Location buildJobJar(BasicMapReduceContext context) throws IOException {
// Excludes libraries that are for sure not needed.
// Hadoop - Available from the cluster
// Spark - MR never uses Spark
ApplicationBundler appBundler = new ApplicationBundler(ImmutableList.of("org.apache.hadoop",
"org.apache.spark"),
ImmutableList.of("org.apache.hadoop.hbase",
"org.apache.hadoop.hive"));
Id.Program programId = context.getProgram().getId();
Location jobJar =
locationFactory.create(String.format("%s.%s.%s.%s.%s.jar",
ProgramType.MAPREDUCE.name().toLowerCase(),
programId.getNamespaceId(), programId.getApplicationId(),
programId.getId(), context.getRunId().getId()));
LOG.debug("Creating Job jar: {}", jobJar.toURI());
Set<Class<?>> classes = Sets.newHashSet();
classes.add(MapReduce.class);
classes.add(MapperWrapper.class);
classes.add(ReducerWrapper.class);
Job jobConf = context.getHadoopJob();
// We only need to trace the Input/OutputFormat class due to MAPREDUCE-5957 so that those classes are included
// in the job.jar and be available in the MR system classpath before our job classloader (ApplicationClassLoader)
// take over the classloading.
if (cConf.getBoolean(Constants.AppFabric.MAPREDUCE_INCLUDE_CUSTOM_CLASSES)) {
try {
Class<? extends InputFormat<?, ?>> inputFormatClass = jobConf.getInputFormatClass();
LOG.info("InputFormat class: {} {}", inputFormatClass, inputFormatClass.getClassLoader());
classes.add(inputFormatClass);
// If it is StreamInputFormat, also add the StreamEventCodec class as well.
if (StreamInputFormat.class.isAssignableFrom(inputFormatClass)) {
Class<? extends StreamEventDecoder> decoderType =
StreamInputFormat.getDecoderClass(jobConf.getConfiguration());
if (decoderType != null) {
classes.add(decoderType);
}
}
} catch (Throwable t) {
LOG.info("InputFormat class not found: {}", t.getMessage(), t);
// Ignore
}
try {
Class<? extends OutputFormat<?, ?>> outputFormatClass = jobConf.getOutputFormatClass();
LOG.info("OutputFormat class: {} {}", outputFormatClass, outputFormatClass.getClassLoader());
classes.add(outputFormatClass);
} catch (Throwable t) {
LOG.info("OutputFormat class not found: {}", t.getMessage(), t);
// Ignore
}
}
// End of MAPREDUCE-5957.
try {
Class<?> hbaseTableUtilClass = HBaseTableUtilFactory.getHBaseTableUtilClass();
classes.add(hbaseTableUtilClass);
} catch (ProvisionException e) {
LOG.warn("Not including HBaseTableUtil classes in submitted Job Jar since they are not available");
}
ClassLoader oldCLassLoader = ClassLoaders.setContextClassLoader(jobConf.getConfiguration().getClassLoader());
appBundler.createBundle(jobJar, classes);
ClassLoaders.setContextClassLoader(oldCLassLoader);
LOG.info("Built MapReduce Job Jar at {}", jobJar.toURI());
return jobJar;
}
/**
* Returns a resolved {@link TypeToken} of the given super type by reading a class from the job configuration that
* extends from super type.
*
* @param conf the job configuration
* @param typeAttr The job configuration attribute for getting the user class
* @param superType Super type of the class to get from the configuration
* @param <V> Type of the super type
* @return A resolved {@link TypeToken} or {@code null} if no such class in the job configuration
*/
@SuppressWarnings("unchecked")
private <V> TypeToken<V> resolveClass(Configuration conf, String typeAttr, Class<V> superType) {
Class<? extends V> userClass = conf.getClass(typeAttr, null, superType);
if (userClass == null) {
return null;
}
return (TypeToken<V>) TypeToken.of(userClass).getSupertype(superType);
}
/**
* Sets the output key and value classes in the job configuration by inspecting the {@link Mapper} and {@link Reducer}
* if it is not set by the user.
*
* @param job the MapReduce job
*/
private void setOutputClassesIfNeeded(Job job) {
Configuration conf = job.getConfiguration();
// Try to get the type from reducer
TypeToken<?> type = resolveClass(conf, MRJobConfig.REDUCE_CLASS_ATTR, Reducer.class);
if (type == null) {
// Map only job
type = resolveClass(conf, MRJobConfig.MAP_CLASS_ATTR, Mapper.class);
}
// If not able to detect type, nothing to set
if (type == null || !(type.getType() instanceof ParameterizedType)) {
return;
}
Type[] typeArgs = ((ParameterizedType) type.getType()).getActualTypeArguments();
// Set it only if the user didn't set it in beforeSubmit
// The key and value type are in the 3rd and 4th type parameters
if (!isProgrammaticConfig(conf, MRJobConfig.OUTPUT_KEY_CLASS)) {
Class<?> cls = TypeToken.of(typeArgs[2]).getRawType();
LOG.debug("Set output key class to {}", cls);
job.setOutputKeyClass(cls);
}
if (!isProgrammaticConfig(conf, MRJobConfig.OUTPUT_VALUE_CLASS)) {
Class<?> cls = TypeToken.of(typeArgs[3]).getRawType();
LOG.debug("Set output value class to {}", cls);
job.setOutputValueClass(cls);
}
}
/**
* Sets the map output key and value classes in the job configuration by inspecting the {@link Mapper}
* if it is not set by the user.
*
* @param job the MapReduce job
*/
private void setMapOutputClassesIfNeeded(Job job) {
Configuration conf = job.getConfiguration();
int keyIdx = 2;
int valueIdx = 3;
TypeToken<?> type = resolveClass(conf, MRJobConfig.MAP_CLASS_ATTR, Mapper.class);
if (type == null) {
// Reducer only job. Use the Reducer input types as the key/value classes.
type = resolveClass(conf, MRJobConfig.REDUCE_CLASS_ATTR, Reducer.class);
keyIdx = 0;
valueIdx = 1;
}
// If not able to detect type, nothing to set.
if (type == null || !(type.getType() instanceof ParameterizedType)) {
return;
}
Type[] typeArgs = ((ParameterizedType) type.getType()).getActualTypeArguments();
// Set it only if the user didn't set it in beforeSubmit
// The key and value type are in the 3rd and 4th type parameters
if (!isProgrammaticConfig(conf, MRJobConfig.MAP_OUTPUT_KEY_CLASS)) {
Class<?> cls = TypeToken.of(typeArgs[keyIdx]).getRawType();
LOG.debug("Set map output key class to {}", cls);
job.setMapOutputKeyClass(cls);
}
if (!isProgrammaticConfig(conf, MRJobConfig.MAP_OUTPUT_VALUE_CLASS)) {
Class<?> cls = TypeToken.of(typeArgs[valueIdx]).getRawType();
LOG.debug("Set map output value class to {}", cls);
job.setMapOutputValueClass(cls);
}
}
private boolean isProgrammaticConfig(Configuration conf, String name) {
String[] sources = conf.getPropertySources(name);
return sources != null && sources.length > 0 && PROGRAMMATIC_SOURCE.equals(sources[sources.length - 1]);
}
/**
* Creates a temp copy of the program jar.
*
* @return a new {@link Location} which contains the same content as the program jar
*/
private Location copyProgramJar() throws IOException {
Id.Program programId = context.getProgram().getId();
Location programJarCopy = locationFactory.create(
String.format("%s.%s.%s.%s.%s.program.jar",
ProgramType.MAPREDUCE.name().toLowerCase(),
programId.getNamespaceId(), programId.getApplicationId(),
programId.getId(), context.getRunId().getId()));
ByteStreams.copy(Locations.newInputSupplier(programJarLocation), Locations.newOutputSupplier(programJarCopy));
LOG.info("Copied Program Jar to {}, source: {}", programJarCopy.toURI(), programJarLocation.toURI());
return programJarCopy;
}
/**
* Creates a JAR file that contains all the plugin jars that are needed by the job. The plugin directory
* structure is maintained inside the jar so that MR framework can correctly expand and recreate the required
* structure.
*
* @return the {@link Location} for the archive file or {@code null} if there is no plugin files need to be localized
*/
@Nullable
private Location createPluginArchive(@Nullable AdapterDefinition adapterSpec,
Id.Program programId) throws IOException {
if (adapterSpec == null) {
return null;
}
Set<PluginInfo> pluginInfos = adapterSpec.getPluginInfos();
if (pluginInfos.isEmpty()) {
return null;
}
// Find plugins that are used by this adapter.
File pluginDir = new File(cConf.get(Constants.AppFabric.APP_TEMPLATE_PLUGIN_DIR));
File templatePluginDir = new File(pluginDir, adapterSpec.getTemplate());
File jarFile = File.createTempFile("plugin", ".jar");
try {
String entryPrefix = pluginDir.getName() + "/" + adapterSpec.getTemplate();
try (JarOutputStream output = new JarOutputStream(new FileOutputStream(jarFile))) {
// Create the directory entries
output.putNextEntry(new JarEntry(entryPrefix + "/"));
output.putNextEntry(new JarEntry(entryPrefix + "/lib/"));
// copy the plugin jars
for (PluginInfo plugin : pluginInfos) {
String entryName = String.format("%s/%s", entryPrefix, plugin.getFileName());
output.putNextEntry(new JarEntry(entryName));
Files.copy(new File(templatePluginDir, plugin.getFileName()), output);
}
// copy the common plugin lib jars
for (File libJar : DirUtils.listFiles(new File(templatePluginDir, "lib"), "jar")) {
String entryName = String.format("%s/lib/%s", entryPrefix, libJar.getName());
output.putNextEntry(new JarEntry(entryName));
Files.copy(libJar, output);
}
}
// Copy the jar to a location, based on the location factory
Location location = locationFactory.create(
String.format("%s.%s.%s.%s.%s.plugins.jar",
ProgramType.MAPREDUCE.name().toLowerCase(),
programId.getNamespaceId(), programId.getApplicationId(),
programId.getId(), context.getRunId().getId()));
try {
Files.copy(jarFile, Locations.newOutputSupplier(location));
return location;
} catch (IOException e) {
Locations.deleteQuietly(location);
throw e;
}
} finally {
jarFile.delete();
}
}
private Runnable createCleanupTask(final Location... locations) {
return new Runnable() {
@Override
public void run() {
for (Location location : locations) {
if (location != null) {
Locations.deleteQuietly(location);
}
}
}
};
}
}
| CDAP-2441 - Override MR job name in case user set it in beforeSubmit. Does not fully resolve CDAP-2441.
| cdap-app-fabric/src/main/java/co/cask/cdap/internal/app/runtime/batch/MapReduceRuntimeService.java | CDAP-2441 - Override MR job name in case user set it in beforeSubmit. Does not fully resolve CDAP-2441. | |
Java | apache-2.0 | 9760d31e290778fa4b4d38796285759ff2b5a790 | 0 | outjie/jqm4gwt,jqm4gwt/jqm4gwt,outjie/jqm4gwt,jqm4gwt/jqm4gwt,outjie/jqm4gwt | package com.sksamuel.jqm4gwt;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* @author Stephen K Samuel samspade79@gmail.com 9 Jul 2011 12:57:43
*
* The {@link JQMContent} provides methods that facilitate interaction
* between GWT, JQM and the DOM.
*
*/
public class JQMContext {
private static Transition defaultTransition = Transition.POP;
private static boolean defaultTransistionDirection = false;
private static boolean defaultChangeHash = true;
public static native void disableHashListening() /*-{
$wnd.$.mobile.hashListeningEnabled = false;
}-*/;
/**
* Appends the given {@link JQMPage} to the DOM so that JQueryMobile is
* able to manipulate it and render it. This should only be done once per
* page, otherwise duplicate HTML would be added to the DOM and this would
* result in elements with overlapping IDs.
*
*/
public static void attachAndEnhance(JQMContainer container) {
RootPanel.get().add(container);
enhance(container);
container.setEnhanced(true);
}
/**
* Programatically change the displayed page to the given {@link JQMPage}
* instance. This uses the default transition which is Transition.POP
*/
public static void changePage(JQMContainer container) {
changePage(container, defaultTransition);
}
/**
* Change the displayed page to the given {@link JQMPage} instance using
* the supplied transition.
*/
public static void changePage(JQMContainer container, Transition transition) {
Mobile.changePage("#" + container.getId(), transition, defaultTransistionDirection, defaultChangeHash);
}
/**
* Change the displayed page to the given {@link JQMPage} instance using
* the supplied transition and reverse setting.
*/
public static void changePage(JQMContainer container, Transition transition, boolean reverse) {
Mobile.changePage("#" + container.getId(), transition, reverse, defaultChangeHash);
}
private static void enhance(JQMContainer c) {
render(c.getId());
}
public static Transition getDefaultTransition() {
return defaultTransition;
}
/**
* Return the pixel offset of an element from the left of the document.
* This can also be thought of as the y coordinate of the top of the
* elements bounding box.
*
* @param id
* the id of the element to find the offset
*/
public native static int getLeft(String id) /*-{
return $wnd.$("#" + id).offset().left;
}-*/;
/**
* Return the pixel offset of an element from the top of the document.
* This can also be thought of as the x coordinate of the left of the
* elements bounding box.
*
* @param id
* the id of the element to find the offset
*/
public native static int getTop(String id) /*-{
return $wnd.$("#" + id).offset().top;
}-*/;
public native static void initializePage() /*-{
$wnd.$.mobile.initializePage();
}-*/;
/**
* Ask JQuery Mobile to "render" the element with the given id.
*/
public static void render(String id) {
if (id == null || "".equals(id))
throw new IllegalArgumentException("render for empty id not possible");
renderImpl(id);
}
private static native void renderImpl(String id) /*-{
$wnd.$("#" + id).page();
}-*/;
public static void setDefaultTransition(Transition defaultTransition) {
JQMContext.defaultTransition = defaultTransition;
}
public static void setDefaultTransition(Transition defaultTransition, boolean direction) {
JQMContext.defaultTransition = defaultTransition;
defaultTransistionDirection = direction;
}
public static void setDefaultChangeHash(boolean defaultChangeHash) {
JQMContext.defaultChangeHash = defaultChangeHash;
}
/**
* Scroll the page to the y-position of the given element. The element
* must be attached to the DOM (obviously!).
*
* This method will not fire jquery mobile scroll events.
*/
public static void silentScroll(Element e) {
if (e.getId() != null)
Mobile.silentScroll(getTop(e.getId()));
}
/**
* Scroll the page to the y-position of the given widget. The widget must
* be attached to the DOM (obviously!)
*
* This method will not fire jquery mobile scroll events.
*/
public static void silentScroll(Widget widget) {
silentScroll(widget.getElement());
}
}
| library/src/main/java/com/sksamuel/jqm4gwt/JQMContext.java | package com.sksamuel.jqm4gwt;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* @author Stephen K Samuel samspade79@gmail.com 9 Jul 2011 12:57:43
*
* The {@link JQMContent} provides methods that facilitate interaction
* between GWT, JQM and the DOM.
*
*/
public class JQMContext {
private static Transition defaultTransition = Transition.POP;
private static boolean defaultTransistionDirection = false;
private static boolean defaultChangeHash = true;
public static native void disableHashListening() /*-{
$wnd.$.mobile.hashListeningEnabled = false;
}-*/;
/**
* Appends the given {@link JQMPage} to the DOM so that JQueryMobile is
* able to manipulate it and render it. This should only be done once per
* page, otherwise duplicate HTML would be added to the DOM and this would
* result in elements with overlapping IDs.
*
*/
public static void attachAndEnhance(JQMContainer container) {
RootPanel.get().add(container);
enhance(container);
container.setEnhanced(true);
}
/**
* Programatically change the displayed page to the given {@link JQMPage}
* instance. This uses the default transition which is Transition.POP
*/
public static void changePage(JQMContainer container) {
changePage(container, defaultTransition);
}
/**
* Change the displayed page to the given {@link JQMPage} instance using
* the supplied transition.
*/
public static void changePage(JQMContainer container, Transition transition) {
Mobile.changePage("#" + container.getId(), transition, defaultTransistionDirection, defaultChangeHash);
}
private static void enhance(JQMContainer c) {
render(c.getId());
}
public static Transition getDefaultTransition() {
return defaultTransition;
}
/**
* Return the pixel offset of an element from the left of the document.
* This can also be thought of as the y coordinate of the top of the
* elements bounding box.
*
* @param id
* the id of the element to find the offset
*/
public native static int getLeft(String id) /*-{
return $wnd.$("#" + id).offset().left;
}-*/;
/**
* Return the pixel offset of an element from the top of the document.
* This can also be thought of as the x coordinate of the left of the
* elements bounding box.
*
* @param id
* the id of the element to find the offset
*/
public native static int getTop(String id) /*-{
return $wnd.$("#" + id).offset().top;
}-*/;
public native static void initializePage() /*-{
$wnd.$.mobile.initializePage();
}-*/;
/**
* Ask JQuery Mobile to "render" the element with the given id.
*/
public static void render(String id) {
if (id == null || "".equals(id))
throw new IllegalArgumentException("render for empty id not possible");
renderImpl(id);
}
private static native void renderImpl(String id) /*-{
$wnd.$("#" + id).page();
}-*/;
public static void setDefaultTransition(Transition defaultTransition) {
JQMContext.defaultTransition = defaultTransition;
}
public static void setDefaultTransition(Transition defaultTransition, boolean direction) {
JQMContext.defaultTransition = defaultTransition;
defaultTransistionDirection = direction;
}
public static void setDefaultChangeHash(boolean defaultChangeHash) {
JQMContext.defaultChangeHash = defaultChangeHash;
}
/**
* Scroll the page to the y-position of the given element. The element
* must be attached to the DOM (obviously!).
*
* This method will not fire jquery mobile scroll events.
*/
public static void silentScroll(Element e) {
if (e.getId() != null)
Mobile.silentScroll(getTop(e.getId()));
}
/**
* Scroll the page to the y-position of the given widget. The widget must
* be attached to the DOM (obviously!)
*
* This method will not fire jquery mobile scroll events.
*/
public static void silentScroll(Widget widget) {
silentScroll(widget.getElement());
}
}
| Added JQMContext submission from Staffan.
| library/src/main/java/com/sksamuel/jqm4gwt/JQMContext.java | Added JQMContext submission from Staffan. | |
Java | apache-2.0 | 06e670193507e43f8a19c53e8f378b7b146c9712 | 0 | bazaarvoice/astyanax,DavidHerzogTU-Berlin/astyanax,Netflix/astyanax,gorcz/astyanax,DavidHerzogTU-Berlin/astyanax,fengshao0907/astyanax,maxtomassi/ds-astyanax,fengshao0907/astyanax,bazaarvoice/astyanax,gorcz/astyanax,Netflix/astyanax,Netflix/astyanax,DavidHerzogTU-Berlin/astyanax,apigee/astyanax,maxtomassi/ds-astyanax,apigee/astyanax | package com.netflix.astyanax.recipes.scheduler;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.netflix.astyanax.Keyspace;
import com.netflix.astyanax.MutationBatch;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.model.ColumnFamily;
import com.netflix.astyanax.model.ColumnList;
import com.netflix.astyanax.model.ConsistencyLevel;
import com.netflix.astyanax.recipes.locks.BusyLockException;
import com.netflix.astyanax.recipes.queue.Message;
import com.netflix.astyanax.recipes.queue.MessageConsumer;
import com.netflix.astyanax.recipes.queue.MessageProducer;
import com.netflix.astyanax.recipes.queue.MessageQueueException;
import com.netflix.astyanax.recipes.queue.MessageQueueHooks;
import com.netflix.astyanax.recipes.queue.ShardedDistributedMessageQueue;
import com.netflix.astyanax.recipes.uniqueness.ColumnPrefixUniquenessConstraint;
import com.netflix.astyanax.recipes.uniqueness.NotUniqueException;
import com.netflix.astyanax.serializers.StringSerializer;
import com.netflix.astyanax.serializers.TimeUUIDSerializer;
import com.netflix.astyanax.util.TimeUUIDUtils;
/**
* Implementation of a task scheduler on top of the MessageQueue recipe.
*
* @author elandau
*
* TODO: Execute the tasks in a separate executor
*/
public class DistributedTaskScheduler implements MessageQueueHooks, TaskScheduler {
private final static Logger LOG = LoggerFactory.getLogger(DistributedTaskScheduler.class);
private final static String DEFAULT_SCHEDULER_NAME = "Tasks";
private final static ConsistencyLevel DEFAULT_CONSISTENCY_LEVEL = ConsistencyLevel.CL_QUORUM;
private final static int DEFAULT_BATCH_SIZE = 5;
private final static int DEFAULT_CONSUMER_THREAD_COUNT = 1;
private final static Integer DEFAULT_ERROR_TTL = (int)TimeUnit.SECONDS.convert(14, TimeUnit.DAYS);
private final static int DEFAULT_SCHEMA_AGREEMENT_GRACE_PERIOD = 3000;
private final static int DEFAULT_SHARD_COUNT = 1;
private final static int DEFAULT_BUCKET_COUNT = 1;
private final static int DEFAULT_BUCKET_DURATION = 1;
private final static int DEFAULT_POLLING_INTERVAL = 1; // Seconds
private final static int THROTTLE_DURATION = 1000;
private final static String TASKS_SUFFIX = "_Tasks";
private final static String QUEUE_SUFFIX = "_Queue";
private final static String HISTORY_SUFFIX = "_History";
private final static String COLUMN_TASK_INFO = "task_info";
private final static String COLUMN_TRIGGER_CLASS = "trigger_class";
private final static String COLUMN_TRIGGER = "trigger";
private final static String COLUMN_TOKEN = "token";
private final static String COLUMN_STATE = "state";
private final static String PARAM_KEY = "key";
private final ObjectMapper mapper;
{
mapper = new ObjectMapper();
mapper.configure(SerializationConfig.Feature.USE_STATIC_TYPING, true);
}
/**
* Builder for the scheduler
*
* @author elandau
*/
public static class Builder {
private DistributedTaskScheduler taskExecutor = new DistributedTaskScheduler();
/**
* You should only really call this if you want to change the consistency level
* to CL_QUORUM_EACH for multi-dc deploayment, which wouldn't make much sense
* for a distributed scheduler due to the increased locking latency.
*
* @param consistencyLevel
*/
public Builder withConsistencyLevel(ConsistencyLevel consistencyLevel) {
taskExecutor.consistencyLevel = consistencyLevel;
return this;
}
/**
* Change the number of threads reading from the queue
*
* @param threadCount
*/
public Builder withThreadCount(int threadCount) {
taskExecutor.threadCount = threadCount;
return this;
}
/**
* Number of 'triggers' to read from the queue in each call.
* Default is 1
* @param batchSize
*/
public Builder withBatchSize(int batchSize) {
taskExecutor.batchSize = batchSize;
return this;
}
/**
* Unique name given to the scheduler. The scheduler uses 3 column families
* with the following naming convension
*
* {name}_Tasks
* {name}_History
* {name}_Queue
*
* @param schedulerName
*/
public Builder withName(String schedulerName) {
taskExecutor.name = schedulerName;
return this;
}
/**
* Group name within the column families. This allows for multiple schedulers
* to run in the same column famil.
* @param schedulerName
* @return
*/
public Builder withGroupName(String groupName) {
taskExecutor.groupName = groupName;
return this;
}
/**
* The keyspace client to use
* @param keyspace
*/
public Builder withKeyspace(Keyspace keyspace) {
taskExecutor.keyspace = keyspace;
return this;
}
/**
* Set the polling interval for checking for events to execute.
*
* @param interval
* @param units Lowest granularity is in seconds
* @return
*/
public Builder withPollingInterval(long interval, TimeUnit units) {
taskExecutor.pollingInterval = TimeUnit.SECONDS.convert(interval, units);
return this;
}
public TaskScheduler build() {
taskExecutor.intialize();
return taskExecutor;
}
}
private ShardedDistributedMessageQueue messageQueue;
private ExecutorService executor;
private int threadCount = DEFAULT_CONSUMER_THREAD_COUNT;
private int batchSize = DEFAULT_BATCH_SIZE;
private volatile boolean terminate = false;
private ConsistencyLevel consistencyLevel = DEFAULT_CONSISTENCY_LEVEL;
private String name = DEFAULT_SCHEDULER_NAME;
private String groupName;
private MessageProducer producer;
private Keyspace keyspace;
private ColumnFamily<String, String> taskCf;
private ColumnFamily<String, UUID> historyCf;
private long pollingInterval = DEFAULT_POLLING_INTERVAL;
public DistributedTaskScheduler() {
}
/**
* Perform initialization after the scheduler is built by the Builder
*/
private void intialize() {
Preconditions.checkNotNull(keyspace, "Must specify keyspace");
taskCf = new ColumnFamily<String, String>(name + TASKS_SUFFIX, StringSerializer.get(), StringSerializer.get());
historyCf = new ColumnFamily<String, UUID> (name + HISTORY_SUFFIX, StringSerializer.get(), TimeUUIDSerializer.get());
if (groupName == null)
groupName = name;
executor = Executors.newFixedThreadPool(threadCount);
messageQueue = new ShardedDistributedMessageQueue.Builder()
.withColumnFamily(taskCf.getName() + QUEUE_SUFFIX)
.withQueueName(groupName)
.withKeyspace(keyspace)
.withConsistencyLevel(consistencyLevel)
.withShardCount(DEFAULT_SHARD_COUNT)
.withHook(this)
.withBuckets(DEFAULT_BUCKET_COUNT, DEFAULT_BUCKET_DURATION, TimeUnit.HOURS)
.withPollInterval(pollingInterval, TimeUnit.SECONDS)
.build();
producer = messageQueue.createProducer();
}
/* (non-Javadoc)
* @see com.netflix.astyanax.recipes.scheduler.TaskScheduler#create()
*/
@Override
public void create() throws TaskSchedulerException {
// Create the message queue and wait for the schema agreement to propograte
try {
messageQueue.createQueue();
} catch (MessageQueueException e) {
// TODO: Ignore if already exists
throw new TaskSchedulerException("Failed to create message queue for scheduler " + taskCf.getName(), e);
}
try {
Thread.sleep(DEFAULT_SCHEMA_AGREEMENT_GRACE_PERIOD);
} catch (InterruptedException e1) {
Thread.currentThread().interrupt();
}
// Create the Task column family and wait for the schema agreement to propogate
try {
keyspace.createColumnFamily(taskCf, ImmutableMap.<String, Object>builder()
.put("column_metadata", ImmutableMap.<String, Object>builder()
.put(COLUMN_TASK_INFO, ImmutableMap.<String, Object>builder()
.put("validation_class", "UTF8Type")
.build())
.put(COLUMN_TRIGGER_CLASS, ImmutableMap.<String, Object>builder()
.put("validation_class", "UTF8Type")
.build())
.put(COLUMN_TRIGGER, ImmutableMap.<String, Object>builder()
.put("validation_class", "UTF8Type")
.build())
.put(COLUMN_STATE, ImmutableMap.<String, Object>builder()
.put("validation_class", "UTF8Type")
.build())
.put(COLUMN_TOKEN, ImmutableMap.<String, Object>builder()
.put("validation_class", "UUIDType")
.build())
.build())
.build());
} catch (ConnectionException e) {
// TODO: Ignore if already exists
throw new TaskSchedulerException("Failed to create column family for scheduler " + taskCf.getName(), e);
}
try {
Thread.sleep(DEFAULT_SCHEMA_AGREEMENT_GRACE_PERIOD);
} catch (InterruptedException e1) {
Thread.currentThread().interrupt();
}
// Create the history column family and wait for it to propogate
try {
keyspace.createColumnFamily(historyCf, ImmutableMap.<String, Object>builder()
.put("default_validation_class", "UTF8Type")
.build());
} catch (ConnectionException e) {
throw new TaskSchedulerException("Failed to create column family for scheduler history " + historyCf.getName(), e);
}
try {
Thread.sleep(DEFAULT_SCHEMA_AGREEMENT_GRACE_PERIOD);
} catch (InterruptedException e1) {
Thread.currentThread().interrupt();
}
}
/* (non-Javadoc)
* @see com.netflix.astyanax.recipes.scheduler.TaskScheduler#start()
*/
@Override
public void start() {
for (int i = 0; i < threadCount; i++) {
startConsumer(i);
}
}
/* (non-Javadoc)
* @see com.netflix.astyanax.recipes.scheduler.TaskScheduler#stop()
*/
@Override
public boolean stop() throws TaskSchedulerException {
terminate = true;
executor.shutdown();
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
return false;
}
return true;
}
/**
* Start a consumer thread to process events
* @param id
*/
private void startConsumer(final int id) {
executor.submit(new Runnable() {
private String name;
@Override
public void run() {
// Give it a name
name = StringUtils.join(Lists.newArrayList(messageQueue.getName(), "Consumer", Integer.toString(id)), ":");
Thread.currentThread().setName(name);
// Create the consumer context
MessageConsumer consumer = messageQueue.createConsumer();
try {
// Process events in a tight loop, until asked to terminate
while (!terminate) {
Collection<Message> messages = null;
try {
messages = consumer.readMessages(batchSize);
try {
for (Message message : messages) {
TaskInfo info = null;
String taskKey = null;
ColumnList<String> columns = null;
TaskHistory history = new TaskHistory();
history.setStartTime(System.currentTimeMillis());
history.setTriggerTime(message.getTriggerTime());
UUID historyUUID = TimeUUIDUtils.getTimeUUID(history.getStartTime());
try {
// Get the key from the message parameters
Map<String, Object> parameters = message.getParameters();
taskKey = (String)parameters.get(PARAM_KEY);
// Get all column data for the task
columns = keyspace.prepareQuery(taskCf)
.getRow(taskKey)
.execute()
.getResult();
// TODO: Check that the token isn't stale
if (columns.isEmpty()) {
// Task was deleted so just ignore it
continue;
}
String triggerClassName = columns.getStringValue(COLUMN_TRIGGER_CLASS, null);
// String triggerData = columns.getStringValue(COLUMN_TRIGGER, null);
// TODO: Compare triggers for updates
String triggerData = (String)message.getParameters().get(COLUMN_TRIGGER);
TaskState state = TaskState.valueOf(columns.getStringValue(COLUMN_STATE, TaskState.Active.name()));
// If inactive then we simply skip processing the trigger
info = deserializeString(columns.getStringValue(COLUMN_TASK_INFO, null), TaskInfo.class);
if (state == TaskState.Inactive)
history.setStatus(TaskStatus.SKIPPED);
else
history.setStatus(TaskStatus.RUNNING);
// Log that the task is starting processing. The same column will be updated
// when processing is done
if (info.isKeepHistory()) {
keyspace.prepareColumnMutation(historyCf, taskKey, historyUUID)
.putValue(serializeToString(history), info.getHistoryTtl())
.execute();
}
// Resubmit the trigger if it is a repeating trigger
Task task = (Task) Class.forName(info.getClassName()).newInstance();
Trigger trigger = null;
if (triggerClassName != null) {
trigger = deserializeString(triggerData, triggerClassName);
Trigger nextTrigger = trigger.nextTrigger();
if (nextTrigger != null) {
sendMessage(taskKey, nextTrigger);
}
}
// Execute the task
if (state == TaskState.Active) {
task.execute(info);
history.setStatus(TaskStatus.DONE);
}
}
catch (Throwable t) {
// On any exception
LOG.warn("Error executing task " + taskKey, t);
history.setError(t.getMessage());
history.setStackTrace(ExceptionUtils.getStackTrace(t));
history.setStatus(TaskStatus.FAILED);
}
finally {
// Track processing history
if (columns != null && taskKey != null && (info == null || info.isKeepHistory())) {
try {
history.setEndTime(System.currentTimeMillis());
String value = serializeToString(history);
Integer ttl = DEFAULT_ERROR_TTL;
if (info != null)
ttl = info.getHistoryTtl();
keyspace.prepareColumnMutation(historyCf, taskKey, historyUUID)
.putValue(value, ttl)
.execute();
}
catch (Exception e) {
LOG.warn("Error saving history for " + taskKey, e);
}
}
}
}
}
finally {
consumer.ackMessages(messages);
}
}
catch (BusyLockException e) {
try {
Thread.sleep(THROTTLE_DURATION);
} catch (InterruptedException e1) {
}
}
catch (Exception e) {
LOG.warn("Error consuming messages ", e);
try {
Thread.sleep(THROTTLE_DURATION);
} catch (InterruptedException e1) {
}
}
}
}
finally {
LOG.info("Done with consumer " + name);
}
}
});
}
/* (non-Javadoc)
* @see com.netflix.astyanax.recipes.scheduler.TaskScheduler#scheduleTask(com.netflix.astyanax.recipes.scheduler.TaskInfo, com.netflix.astyanax.recipes.scheduler.Trigger)
*/
@Override
public void scheduleTask(final TaskInfo task, final Trigger trigger) throws TaskSchedulerException, NotUniqueException {
final String rowKey = getGroupKey(task.getKey());
ColumnPrefixUniquenessConstraint<String> unique = new ColumnPrefixUniquenessConstraint<String>(keyspace, taskCf, rowKey)
.withConsistencyLevel(consistencyLevel);
final String serializedTask;
final String serializedTrigger;
try {
serializedTask = serializeToString(task);
serializedTrigger = serializeToString(trigger);
} catch (Exception e) {
throw new TaskSchedulerException("Failed to serialize trigger or task for " + rowKey, e);
}
try {
unique.acquireAndApplyMutation(new Function<MutationBatch, Boolean>() {
@Override
public Boolean apply(@Nullable MutationBatch mb) {
mb.withRow(taskCf, rowKey)
.putColumn(COLUMN_TASK_INFO, serializedTask)
.putColumn(COLUMN_TRIGGER, serializedTrigger)
.putColumn(COLUMN_TRIGGER_CLASS, trigger.getClass().getCanonicalName());
return true;
}
});
} catch (Exception e) {
throw new TaskSchedulerException("Failed to serialize trigger or task for " + rowKey, e);
}
// Now, send
try {
sendMessage(rowKey, trigger);
} catch (Exception e) {
throw new TaskSchedulerException("Failed to send message for task " + rowKey, e);
}
}
/* (non-Javadoc)
* @see com.netflix.astyanax.recipes.scheduler.TaskScheduler#stopTask(java.lang.String)
*/
@Override
public void stopTask(String taskKey) throws TaskSchedulerException {
String rowKey = getGroupKey(taskKey);
try {
keyspace.prepareColumnMutation(taskCf, rowKey, COLUMN_STATE)
.putValue(TaskState.Inactive.name(), null)
.execute();
} catch (ConnectionException e) {
throw new TaskSchedulerException("Failed to deactive task " + rowKey, e);
}
}
/* (non-Javadoc)
* @see com.netflix.astyanax.recipes.scheduler.TaskScheduler#startTask(java.lang.String)
*/
@Override
public void startTask(String taskKey) throws TaskSchedulerException {
String rowKey = getGroupKey(taskKey);
try {
keyspace.prepareColumnMutation(taskCf, rowKey, COLUMN_STATE)
.putValue(TaskState.Active.name(), null)
.execute();
} catch (ConnectionException e) {
throw new TaskSchedulerException("Failed to deactive task " + rowKey, e);
}
}
/* (non-Javadoc)
* @see com.netflix.astyanax.recipes.scheduler.TaskScheduler#deleteTask(java.lang.String)
*/
@Override
public void deleteTask(String taskKey) throws TaskSchedulerException {
String rowKey = getGroupKey(taskKey);
MutationBatch mb = keyspace.prepareMutationBatch().setConsistencyLevel(consistencyLevel);
mb.withRow(taskCf, rowKey).delete();
try {
mb.execute();
} catch (ConnectionException e) {
throw new TaskSchedulerException("Failed to delete task " + rowKey, e);
}
}
/* (non-Javadoc)
* @see com.netflix.astyanax.recipes.scheduler.TaskScheduler#getTaskHistory(java.lang.String, java.lang.Long, java.lang.Long)
*/
@Override
public Collection<TaskHistory> getTaskHistory(String taskKey, Long timeFrom, Long timeTo, int count) throws TaskSchedulerException {
return null;
}
/**
* Send a message to the queue. The message contains references to the actual task recoed.
* @param taskKey
* @param trigger
* @return Message that was sent. This includes the token representing the column in the message queue.
* @throws Exception
*/
private Message sendMessage(String taskKey, Trigger trigger) throws Exception {
Message message = new Message();
message.setParameters(ImmutableMap.<String, Object>builder()
.put(PARAM_KEY, taskKey)
.put(COLUMN_TRIGGER, serializeToString(trigger))
.build());
message.setTriggerTime(trigger.getTriggerTime());
producer.sendMessage(message);
return message;
}
private <T> String serializeToString(T trigger) throws JsonGenerationException, JsonMappingException, IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
mapper.writeValue(baos, trigger);
baos.flush();
return baos.toString();
}
private <T> T deserializeString(String data, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
return (T) mapper.readValue(
new ByteArrayInputStream(data.getBytes()),
clazz);
}
private <T> T deserializeString(String data, String className) throws JsonParseException, JsonMappingException, IOException, ClassNotFoundException {
return (T) mapper.readValue(
new ByteArrayInputStream(data.getBytes()),
Class.forName(className));
}
@Override
public void beforeAckMessages(Collection<Message> messages, MutationBatch mb) {
}
@Override
public void beforeAckMessage(Message message, MutationBatch mb) {
}
@Override
public void beforeSendMessage(Message message, MutationBatch mb) {
// Update the queued token in the task so it can be used to cancel the task
// execution later
try {
mb.withRow(taskCf, (String)message.getParameters().get(PARAM_KEY))
.putColumn(COLUMN_TOKEN, message.getToken());
}
catch (Exception e) {
e.printStackTrace();
}
}
private String getGroupKey(String key) {
return groupName + "$" + key;
}
}
| src/main/java/com/netflix/astyanax/recipes/scheduler/DistributedTaskScheduler.java | package com.netflix.astyanax.recipes.scheduler;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.netflix.astyanax.Keyspace;
import com.netflix.astyanax.MutationBatch;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.model.ColumnFamily;
import com.netflix.astyanax.model.ColumnList;
import com.netflix.astyanax.model.ConsistencyLevel;
import com.netflix.astyanax.recipes.locks.BusyLockException;
import com.netflix.astyanax.recipes.queue.Message;
import com.netflix.astyanax.recipes.queue.MessageConsumer;
import com.netflix.astyanax.recipes.queue.MessageProducer;
import com.netflix.astyanax.recipes.queue.MessageQueueException;
import com.netflix.astyanax.recipes.queue.MessageQueueHooks;
import com.netflix.astyanax.recipes.queue.ShardedDistributedMessageQueue;
import com.netflix.astyanax.recipes.uniqueness.ColumnPrefixUniquenessConstraint;
import com.netflix.astyanax.recipes.uniqueness.NotUniqueException;
import com.netflix.astyanax.serializers.StringSerializer;
import com.netflix.astyanax.serializers.TimeUUIDSerializer;
import com.netflix.astyanax.util.TimeUUIDUtils;
/**
* Implementation of a task scheduler on top of the MessageQueue recipe.
*
* @author elandau
*
* TODO: Execute the tasks in a separate executor
*/
public class DistributedTaskScheduler implements MessageQueueHooks, TaskScheduler {
private final static Logger LOG = LoggerFactory.getLogger(DistributedTaskScheduler.class);
private final static String DEFAULT_SCHEDULER_NAME = "Tasks";
private final static ConsistencyLevel DEFAULT_CONSISTENCY_LEVEL = ConsistencyLevel.CL_QUORUM;
private final static int DEFAULT_BATCH_SIZE = 5;
private final static int DEFAULT_CONSUMER_THREAD_COUNT = 1;
private final static Integer DEFAULT_ERROR_TTL = (int)TimeUnit.SECONDS.convert(14, TimeUnit.DAYS);
private final static int DEFAULT_SCHEMA_AGREEMENT_GRACE_PERIOD = 3000;
private final static int DEFAULT_SHARD_COUNT = 1;
private final static int DEFAULT_BUCKET_COUNT = 1;
private final static int DEFAULT_BUCKET_DURATION = 1;
private final static int THROTTLE_DURATION = 1000;
private final static String TASKS_SUFFIX = "_Tasks";
private final static String QUEUE_SUFFIX = "_Queue";
private final static String HISTORY_SUFFIX = "_History";
private final static String COLUMN_TASK_INFO = "task_info";
private final static String COLUMN_TRIGGER_CLASS = "trigger_class";
private final static String COLUMN_TRIGGER = "trigger";
private final static String COLUMN_TOKEN = "token";
private final static String COLUMN_STATE = "state";
private final static String PARAM_KEY = "key";
private final ObjectMapper mapper;
{
mapper = new ObjectMapper();
mapper.configure(SerializationConfig.Feature.USE_STATIC_TYPING, true);
}
/**
* Builder for the scheduler
*
* @author elandau
*/
public static class Builder {
private DistributedTaskScheduler taskExecutor = new DistributedTaskScheduler();
/**
* You should only really call this if you want to change the consistency level
* to CL_QUORUM_EACH for multi-dc deploayment, which wouldn't make much sense
* for a distributed scheduler due to the increased locking latency.
*
* @param consistencyLevel
*/
public Builder withConsistencyLevel(ConsistencyLevel consistencyLevel) {
taskExecutor.consistencyLevel = consistencyLevel;
return this;
}
/**
* Change the number of threads reading from the queue
*
* @param threadCount
*/
public Builder withThreadCount(int threadCount) {
taskExecutor.threadCount = threadCount;
return this;
}
/**
* Number of 'triggers' to read from the queue in each call.
* Default is 1
* @param batchSize
*/
public Builder withBatchSize(int batchSize) {
taskExecutor.batchSize = batchSize;
return this;
}
/**
* Unique name given to the scheduler. The scheduler uses 3 column families
* with the following naming convension
*
* {name}_Tasks
* {name}_History
* {name}_Queue
*
* @param schedulerName
*/
public Builder withName(String schedulerName) {
taskExecutor.name = schedulerName;
return this;
}
/**
* Group name within the column families. This allows for multiple schedulers
* to run in the same column famil.
* @param schedulerName
* @return
*/
public Builder withGroupName(String groupName) {
taskExecutor.groupName = groupName;
return this;
}
/**
* The keyspace client to use
* @param keyspace
*/
public Builder withKeyspace(Keyspace keyspace) {
taskExecutor.keyspace = keyspace;
return this;
}
public TaskScheduler build() {
taskExecutor.intialize();
return taskExecutor;
}
}
private ShardedDistributedMessageQueue messageQueue;
private ExecutorService executor;
private int threadCount = DEFAULT_CONSUMER_THREAD_COUNT;
private int batchSize = DEFAULT_BATCH_SIZE;
private volatile boolean terminate = false;
private ConsistencyLevel consistencyLevel = DEFAULT_CONSISTENCY_LEVEL;
private String name = DEFAULT_SCHEDULER_NAME;
private String groupName;
private MessageProducer producer;
private Keyspace keyspace;
private ColumnFamily<String, String> taskCf;
private ColumnFamily<String, UUID> historyCf;
public DistributedTaskScheduler() {
}
/**
* Perform initialization after the scheduler is built by the Builder
*/
private void intialize() {
Preconditions.checkNotNull(keyspace, "Must specify keyspace");
taskCf = new ColumnFamily<String, String>(name + TASKS_SUFFIX, StringSerializer.get(), StringSerializer.get());
historyCf = new ColumnFamily<String, UUID> (name + HISTORY_SUFFIX, StringSerializer.get(), TimeUUIDSerializer.get());
if (groupName == null)
groupName = name;
executor = Executors.newFixedThreadPool(threadCount);
messageQueue = new ShardedDistributedMessageQueue.Builder()
.withColumnFamily(taskCf.getName() + QUEUE_SUFFIX)
.withQueueName(groupName)
.withKeyspace(keyspace)
.withConsistencyLevel(consistencyLevel)
.withShardCount(DEFAULT_SHARD_COUNT)
.withHook(this)
.withBuckets(DEFAULT_BUCKET_COUNT, DEFAULT_BUCKET_DURATION, TimeUnit.HOURS)
.build();
producer = messageQueue.createProducer();
}
/* (non-Javadoc)
* @see com.netflix.astyanax.recipes.scheduler.TaskScheduler#create()
*/
@Override
public void create() throws TaskSchedulerException {
// Create the message queue and wait for the schema agreement to propograte
try {
messageQueue.createQueue();
} catch (MessageQueueException e) {
// TODO: Ignore if already exists
throw new TaskSchedulerException("Failed to create message queue for scheduler " + taskCf.getName(), e);
}
try {
Thread.sleep(DEFAULT_SCHEMA_AGREEMENT_GRACE_PERIOD);
} catch (InterruptedException e1) {
Thread.currentThread().interrupt();
}
// Create the Task column family and wait for the schema agreement to propogate
try {
keyspace.createColumnFamily(taskCf, ImmutableMap.<String, Object>builder()
.put("column_metadata", ImmutableMap.<String, Object>builder()
.put(COLUMN_TASK_INFO, ImmutableMap.<String, Object>builder()
.put("validation_class", "UTF8Type")
.build())
.put(COLUMN_TRIGGER_CLASS, ImmutableMap.<String, Object>builder()
.put("validation_class", "UTF8Type")
.build())
.put(COLUMN_TRIGGER, ImmutableMap.<String, Object>builder()
.put("validation_class", "UTF8Type")
.build())
.put(COLUMN_STATE, ImmutableMap.<String, Object>builder()
.put("validation_class", "UTF8Type")
.build())
.put(COLUMN_TOKEN, ImmutableMap.<String, Object>builder()
.put("validation_class", "UUIDType")
.build())
.build())
.build());
} catch (ConnectionException e) {
// TODO: Ignore if already exists
throw new TaskSchedulerException("Failed to create column family for scheduler " + taskCf.getName(), e);
}
try {
Thread.sleep(DEFAULT_SCHEMA_AGREEMENT_GRACE_PERIOD);
} catch (InterruptedException e1) {
Thread.currentThread().interrupt();
}
// Create the history column family and wait for it to propogate
try {
keyspace.createColumnFamily(historyCf, ImmutableMap.<String, Object>builder()
.put("default_validation_class", "UTF8Type")
.build());
} catch (ConnectionException e) {
throw new TaskSchedulerException("Failed to create column family for scheduler history " + historyCf.getName(), e);
}
try {
Thread.sleep(DEFAULT_SCHEMA_AGREEMENT_GRACE_PERIOD);
} catch (InterruptedException e1) {
Thread.currentThread().interrupt();
}
}
/* (non-Javadoc)
* @see com.netflix.astyanax.recipes.scheduler.TaskScheduler#start()
*/
@Override
public void start() {
for (int i = 0; i < threadCount; i++) {
startConsumer(i);
}
}
/* (non-Javadoc)
* @see com.netflix.astyanax.recipes.scheduler.TaskScheduler#stop()
*/
@Override
public boolean stop() throws TaskSchedulerException {
terminate = true;
executor.shutdown();
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
return false;
}
return true;
}
/**
* Start a consumer thread to process events
* @param id
*/
private void startConsumer(final int id) {
executor.submit(new Runnable() {
private String name;
@Override
public void run() {
// Give it a name
name = StringUtils.join(Lists.newArrayList(messageQueue.getName(), "Consumer", Integer.toString(id)), ":");
Thread.currentThread().setName(name);
// Create the consumer context
MessageConsumer consumer = messageQueue.createConsumer();
try {
// Process events in a tight loop, until asked to terminate
while (!terminate) {
Collection<Message> messages = null;
try {
messages = consumer.readMessages(batchSize);
try {
for (Message message : messages) {
TaskInfo info = null;
String taskKey = null;
ColumnList<String> columns = null;
TaskHistory history = new TaskHistory();
history.setStartTime(System.currentTimeMillis());
history.setTriggerTime(message.getTriggerTime());
UUID historyUUID = TimeUUIDUtils.getTimeUUID(history.getStartTime());
try {
// Get the key from the message parameters
Map<String, Object> parameters = message.getParameters();
taskKey = (String)parameters.get(PARAM_KEY);
// Get all column data for the task
columns = keyspace.prepareQuery(taskCf)
.getRow(taskKey)
.execute()
.getResult();
// TODO: Check that the token isn't stale
if (columns.isEmpty()) {
// Task was deleted so just ignore it
continue;
}
String triggerClassName = columns.getStringValue(COLUMN_TRIGGER_CLASS, null);
// String triggerData = columns.getStringValue(COLUMN_TRIGGER, null);
// TODO: Compare triggers for updates
String triggerData = (String)message.getParameters().get(COLUMN_TRIGGER);
TaskState state = TaskState.valueOf(columns.getStringValue(COLUMN_STATE, TaskState.Active.name()));
// If inactive then we simply skip processing the trigger
info = deserializeString(columns.getStringValue(COLUMN_TASK_INFO, null), TaskInfo.class);
if (state == TaskState.Inactive)
history.setStatus(TaskStatus.SKIPPED);
else
history.setStatus(TaskStatus.RUNNING);
// Log that the task is starting processing. The same column will be updated
// when processing is done
if (info.isKeepHistory()) {
keyspace.prepareColumnMutation(historyCf, taskKey, historyUUID)
.putValue(serializeToString(history), info.getHistoryTtl())
.execute();
}
// Resubmit the trigger if it is a repeating trigger
Task task = (Task) Class.forName(info.getClassName()).newInstance();
Trigger trigger = null;
if (triggerClassName != null) {
trigger = deserializeString(triggerData, triggerClassName);
Trigger nextTrigger = trigger.nextTrigger();
if (nextTrigger != null) {
sendMessage(taskKey, nextTrigger);
}
}
// Execute the task
if (state == TaskState.Active) {
task.execute(info);
history.setStatus(TaskStatus.DONE);
}
}
catch (Throwable t) {
// On any exception
LOG.warn("Error executing task " + taskKey, t);
history.setError(t.getMessage());
history.setStackTrace(ExceptionUtils.getStackTrace(t));
history.setStatus(TaskStatus.FAILED);
}
finally {
// Track processing history
if (columns != null && taskKey != null && (info == null || info.isKeepHistory())) {
try {
history.setEndTime(System.currentTimeMillis());
String value = serializeToString(history);
Integer ttl = DEFAULT_ERROR_TTL;
if (info != null)
ttl = info.getHistoryTtl();
keyspace.prepareColumnMutation(historyCf, taskKey, historyUUID)
.putValue(value, ttl)
.execute();
}
catch (Exception e) {
LOG.warn("Error saving history for " + taskKey, e);
}
}
}
}
}
finally {
consumer.ackMessages(messages);
}
}
catch (BusyLockException e) {
try {
Thread.sleep(THROTTLE_DURATION);
} catch (InterruptedException e1) {
}
}
catch (Exception e) {
LOG.warn("Error consuming messages ", e);
try {
Thread.sleep(THROTTLE_DURATION);
} catch (InterruptedException e1) {
}
}
}
}
finally {
LOG.info("Done with consumer " + name);
}
}
});
}
/* (non-Javadoc)
* @see com.netflix.astyanax.recipes.scheduler.TaskScheduler#scheduleTask(com.netflix.astyanax.recipes.scheduler.TaskInfo, com.netflix.astyanax.recipes.scheduler.Trigger)
*/
@Override
public void scheduleTask(final TaskInfo task, final Trigger trigger) throws TaskSchedulerException, NotUniqueException {
final String rowKey = getGroupKey(task.getKey());
ColumnPrefixUniquenessConstraint<String> unique = new ColumnPrefixUniquenessConstraint<String>(keyspace, taskCf, rowKey)
.withConsistencyLevel(consistencyLevel);
final String serializedTask;
final String serializedTrigger;
try {
serializedTask = serializeToString(task);
serializedTrigger = serializeToString(trigger);
} catch (Exception e) {
throw new TaskSchedulerException("Failed to serialize trigger or task for " + rowKey, e);
}
try {
unique.acquireAndApplyMutation(new Function<MutationBatch, Boolean>() {
@Override
public Boolean apply(@Nullable MutationBatch mb) {
mb.withRow(taskCf, rowKey)
.putColumn(COLUMN_TASK_INFO, serializedTask)
.putColumn(COLUMN_TRIGGER, serializedTrigger)
.putColumn(COLUMN_TRIGGER_CLASS, trigger.getClass().getCanonicalName());
return true;
}
});
} catch (Exception e) {
throw new TaskSchedulerException("Failed to serialize trigger or task for " + rowKey, e);
}
// Now, send
try {
sendMessage(rowKey, trigger);
} catch (Exception e) {
throw new TaskSchedulerException("Failed to send message for task " + rowKey, e);
}
}
/* (non-Javadoc)
* @see com.netflix.astyanax.recipes.scheduler.TaskScheduler#stopTask(java.lang.String)
*/
@Override
public void stopTask(String taskKey) throws TaskSchedulerException {
String rowKey = getGroupKey(taskKey);
try {
keyspace.prepareColumnMutation(taskCf, rowKey, COLUMN_STATE)
.putValue(TaskState.Inactive.name(), null)
.execute();
} catch (ConnectionException e) {
throw new TaskSchedulerException("Failed to deactive task " + rowKey, e);
}
}
/* (non-Javadoc)
* @see com.netflix.astyanax.recipes.scheduler.TaskScheduler#startTask(java.lang.String)
*/
@Override
public void startTask(String taskKey) throws TaskSchedulerException {
String rowKey = getGroupKey(taskKey);
try {
keyspace.prepareColumnMutation(taskCf, rowKey, COLUMN_STATE)
.putValue(TaskState.Active.name(), null)
.execute();
} catch (ConnectionException e) {
throw new TaskSchedulerException("Failed to deactive task " + rowKey, e);
}
}
/* (non-Javadoc)
* @see com.netflix.astyanax.recipes.scheduler.TaskScheduler#deleteTask(java.lang.String)
*/
@Override
public void deleteTask(String taskKey) throws TaskSchedulerException {
String rowKey = getGroupKey(taskKey);
MutationBatch mb = keyspace.prepareMutationBatch().setConsistencyLevel(consistencyLevel);
mb.withRow(taskCf, rowKey).delete();
try {
mb.execute();
} catch (ConnectionException e) {
throw new TaskSchedulerException("Failed to delete task " + rowKey, e);
}
}
/* (non-Javadoc)
* @see com.netflix.astyanax.recipes.scheduler.TaskScheduler#getTaskHistory(java.lang.String, java.lang.Long, java.lang.Long)
*/
@Override
public Collection<TaskHistory> getTaskHistory(String taskKey, Long timeFrom, Long timeTo, int count) throws TaskSchedulerException {
return null;
}
/**
* Send a message to the queue. The message contains references to the actual task recoed.
* @param taskKey
* @param trigger
* @return Message that was sent. This includes the token representing the column in the message queue.
* @throws Exception
*/
private Message sendMessage(String taskKey, Trigger trigger) throws Exception {
Message message = new Message();
message.setParameters(ImmutableMap.<String, Object>builder()
.put(PARAM_KEY, taskKey)
.put(COLUMN_TRIGGER, serializeToString(trigger))
.build());
message.setTriggerTime(trigger.getTriggerTime());
producer.sendMessage(message);
return message;
}
private <T> String serializeToString(T trigger) throws JsonGenerationException, JsonMappingException, IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
mapper.writeValue(baos, trigger);
baos.flush();
return baos.toString();
}
private <T> T deserializeString(String data, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
return (T) mapper.readValue(
new ByteArrayInputStream(data.getBytes()),
clazz);
}
private <T> T deserializeString(String data, String className) throws JsonParseException, JsonMappingException, IOException, ClassNotFoundException {
return (T) mapper.readValue(
new ByteArrayInputStream(data.getBytes()),
Class.forName(className));
}
@Override
public void beforeAckMessages(Collection<Message> messages, MutationBatch mb) {
}
@Override
public void beforeAckMessage(Message message, MutationBatch mb) {
}
@Override
public void beforeSendMessage(Message message, MutationBatch mb) {
// Update the queued token in the task so it can be used to cancel the task
// execution later
try {
mb.withRow(taskCf, (String)message.getParameters().get(PARAM_KEY))
.putColumn(COLUMN_TOKEN, message.getToken());
}
catch (Exception e) {
e.printStackTrace();
}
}
private String getGroupKey(String key) {
return groupName + "$" + key;
}
}
| Option to customize the polling interval for the task scheduler
| src/main/java/com/netflix/astyanax/recipes/scheduler/DistributedTaskScheduler.java | Option to customize the polling interval for the task scheduler | |
Java | apache-2.0 | 69dcad2ebb41773dcbb476ee29ac6164e6c334b6 | 0 | hgschmie/presto,hgschmie/presto,smartnews/presto,ebyhr/presto,11xor6/presto,martint/presto,smartnews/presto,losipiuk/presto,martint/presto,wyukawa/presto,treasure-data/presto,electrum/presto,hgschmie/presto,dain/presto,smartnews/presto,electrum/presto,martint/presto,11xor6/presto,erichwang/presto,wyukawa/presto,ebyhr/presto,electrum/presto,Praveen2112/presto,Praveen2112/presto,Praveen2112/presto,treasure-data/presto,electrum/presto,losipiuk/presto,dain/presto,11xor6/presto,dain/presto,wyukawa/presto,dain/presto,smartnews/presto,wyukawa/presto,martint/presto,treasure-data/presto,ebyhr/presto,electrum/presto,erichwang/presto,martint/presto,losipiuk/presto,11xor6/presto,erichwang/presto,losipiuk/presto,erichwang/presto,hgschmie/presto,losipiuk/presto,11xor6/presto,treasure-data/presto,smartnews/presto,erichwang/presto,dain/presto,wyukawa/presto,ebyhr/presto,treasure-data/presto,hgschmie/presto,ebyhr/presto,treasure-data/presto,Praveen2112/presto,Praveen2112/presto | /*
* 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 io.prestosql.plugin.hive.authentication;
import org.apache.hadoop.security.UserGroupInformation;
import javax.annotation.concurrent.GuardedBy;
import javax.security.auth.Subject;
import javax.security.auth.kerberos.KerberosTicket;
import static com.google.common.base.Preconditions.checkArgument;
import static io.prestosql.plugin.hive.authentication.KerberosTicketUtils.getTicketGrantingTicket;
import static java.util.Objects.requireNonNull;
import static org.apache.hadoop.security.UserGroupInformationShim.getSubject;
public class CachingKerberosHadoopAuthentication
implements HadoopAuthentication
{
private final KerberosHadoopAuthentication delegate;
@GuardedBy("this")
private UserGroupInformation userGroupInformation;
@GuardedBy("this")
private long nextRefreshTime;
public CachingKerberosHadoopAuthentication(KerberosHadoopAuthentication delegate)
{
this.delegate = requireNonNull(delegate, "hadoopAuthentication is null");
}
@Override
public synchronized UserGroupInformation getUserGroupInformation()
{
if (nextRefreshTime < System.currentTimeMillis() || userGroupInformation == null) {
userGroupInformation = requireNonNull(delegate.getUserGroupInformation(), "delegate.getUserGroupInformation() is null");
nextRefreshTime = calculateNextRefreshTime(userGroupInformation);
}
return userGroupInformation;
}
private static long calculateNextRefreshTime(UserGroupInformation userGroupInformation)
{
Subject subject = getSubject(userGroupInformation);
checkArgument(subject != null, "subject must be present in kerberos based UGI");
KerberosTicket tgtTicket = getTicketGrantingTicket(subject);
return KerberosTicketUtils.getRefreshTime(tgtTicket);
}
}
| presto-hive/src/main/java/io/prestosql/plugin/hive/authentication/CachingKerberosHadoopAuthentication.java | /*
* 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 io.prestosql.plugin.hive.authentication;
import org.apache.hadoop.security.UserGroupInformation;
import javax.annotation.concurrent.GuardedBy;
import javax.security.auth.Subject;
import javax.security.auth.kerberos.KerberosTicket;
import static com.google.common.base.Preconditions.checkArgument;
import static io.prestosql.plugin.hive.authentication.KerberosTicketUtils.getTicketGrantingTicket;
import static java.util.Objects.requireNonNull;
import static org.apache.hadoop.security.UserGroupInformationShim.getSubject;
public class CachingKerberosHadoopAuthentication
implements HadoopAuthentication
{
private final KerberosHadoopAuthentication delegate;
private final Object lock = new Object();
@GuardedBy("lock")
private UserGroupInformation userGroupInformation;
@GuardedBy("lock")
private long nextRefreshTime = Long.MIN_VALUE;
public CachingKerberosHadoopAuthentication(KerberosHadoopAuthentication delegate)
{
this.delegate = requireNonNull(delegate, "hadoopAuthentication is null");
}
@Override
public UserGroupInformation getUserGroupInformation()
{
synchronized (lock) {
if (refreshIsNeeded()) {
refreshUgi();
}
return userGroupInformation;
}
}
@GuardedBy("lock")
private void refreshUgi()
{
userGroupInformation = delegate.getUserGroupInformation();
nextRefreshTime = calculateNextRefreshTime(userGroupInformation);
}
@GuardedBy("lock")
private boolean refreshIsNeeded()
{
return nextRefreshTime < System.currentTimeMillis() || userGroupInformation == null;
}
private static long calculateNextRefreshTime(UserGroupInformation userGroupInformation)
{
Subject subject = getSubject(userGroupInformation);
checkArgument(subject != null, "subject must be present in kerberos based UGI");
KerberosTicket tgtTicket = getTicketGrantingTicket(subject);
return KerberosTicketUtils.getRefreshTime(tgtTicket);
}
}
| Simplify CachingKerberosHadoopAuthentication
| presto-hive/src/main/java/io/prestosql/plugin/hive/authentication/CachingKerberosHadoopAuthentication.java | Simplify CachingKerberosHadoopAuthentication | |
Java | apache-2.0 | fcbebd771f68ebf7c91a5c1509cf250d415f7457 | 0 | ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma | /*
* The Gemma project
*
* Copyright (c) 2007 University of British Columbia
*
* 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 ubic.gemma.loader.expression;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ubic.gemma.analysis.service.ExpressionExperimentVectorManipulatingService;
import ubic.gemma.model.common.auditAndSecurity.AuditTrailService;
import ubic.gemma.model.common.auditAndSecurity.eventType.AuditEventType;
import ubic.gemma.model.common.auditAndSecurity.eventType.ExpressionExperimentPlatformSwitchEvent;
import ubic.gemma.model.common.quantitationtype.QuantitationType;
import ubic.gemma.model.expression.arrayDesign.ArrayDesign;
import ubic.gemma.model.expression.arrayDesign.ArrayDesignService;
import ubic.gemma.model.expression.bioAssay.BioAssay;
import ubic.gemma.model.expression.bioAssay.BioAssayService;
import ubic.gemma.model.expression.bioAssayData.BioAssayDimension;
import ubic.gemma.model.expression.bioAssayData.DesignElementDataVector;
import ubic.gemma.model.expression.bioAssayData.ProcessedExpressionDataVector;
import ubic.gemma.model.expression.bioAssayData.RawExpressionDataVector;
import ubic.gemma.model.expression.designElement.CompositeSequence;
import ubic.gemma.model.expression.designElement.DesignElement;
import ubic.gemma.model.expression.experiment.ExpressionExperiment;
import ubic.gemma.model.expression.experiment.ExpressionExperimentService;
import ubic.gemma.model.genome.biosequence.BioSequence;
/**
* Switch an expression experiment from one array design to another. This is valuable when the EE uses more than on AD,
* and a merged AD exists. The following steps are needed:
* <ul>
* <li>For each array design, for each probe, identify the matching probe on the merged AD. Have to deal with situation
* <li>where more than one occurrence of each sequence is found.
* <li>all DEDVs must be switched to use the new AD's design elements
* <li>all bioassays must be switched to the new AD.
* <li>update the EE description
* <li>commit changes.
* </ul>
*
* @author pavlidis
* @version $Id$
*/
@Service
public class ExpressionExperimentPlatformSwitchService extends ExpressionExperimentVectorManipulatingService {
/**
* Used to identify design elements that have no sequence associated with them.
*/
private static BioSequence NULL_BIOSEQUENCE;
static {
NULL_BIOSEQUENCE = BioSequence.Factory.newInstance();
NULL_BIOSEQUENCE.setName( "______NULL______" );
NULL_BIOSEQUENCE.setId( -1L );
}
private static Log log = LogFactory.getLog( ExpressionExperimentPlatformSwitchService.class.getName() );
@Autowired
ExpressionExperimentService expressionExperimentService;
@Autowired
ArrayDesignService arrayDesignService;
@Autowired
BioAssayService bioAssayService;
@Autowired
private AuditTrailService auditTrailService;
public void setAuditTrailService( AuditTrailService auditTrailService ) {
this.auditTrailService = auditTrailService;
}
/**
* @param arrayDesign
*/
private void audit( ExpressionExperiment ee, String note ) {
AuditEventType eventType = ExpressionExperimentPlatformSwitchEvent.Factory.newInstance();
auditTrailService.addUpdateEvent( ee, eventType, note );
}
/**
* @param expExp
* @param arrayDesign
*/
public void switchExperimentToMergedPlatform( ExpressionExperiment expExp ) {
ArrayDesign arrayDesign = locateMergedDesign( expExp );
if ( arrayDesign == null )
throw new IllegalArgumentException( "Experiment has no merged design to switch to" );
this.switchExperimentToArrayDesign( expExp, arrayDesign );
}
/**
* If you know the arraydesigns are already in a merged state, you should use switchExperimentToMergedPlatform
*
* @param expExp
* @param arrayDesign The array design to switch to. If some samples already use that array design, nothing will be
* changed for them.
*/
@SuppressWarnings("unchecked")
public void switchExperimentToArrayDesign( ExpressionExperiment expExp, ArrayDesign arrayDesign ) {
assert arrayDesign != null;
// get relation between sequence and designelements.
Map<BioSequence, Collection<DesignElement>> designElementMap = new HashMap<BioSequence, Collection<DesignElement>>();
Collection<DesignElement> elsWithNoSeq = new HashSet<DesignElement>();
for ( CompositeSequence cs : arrayDesign.getCompositeSequences() ) {
BioSequence bs = cs.getBiologicalCharacteristic();
if ( bs == null ) {
elsWithNoSeq.add( cs );
} else {
if ( !designElementMap.containsKey( bs ) ) {
designElementMap.put( bs, new HashSet<DesignElement>() );
}
designElementMap.get( bs ).add( cs );
}
}
log.info( elsWithNoSeq.size()
+ " composite sequences on the new array design have no biologicalcharacteristic." );
designElementMap.put( NULL_BIOSEQUENCE, elsWithNoSeq );
Collection<ArrayDesign> oldArrayDesigns = expressionExperimentService.getArrayDesignsUsed( expExp );
Map<DesignElement, Collection<BioAssayDimension>> usedDesignElements = new HashMap<DesignElement, Collection<BioAssayDimension>>();
for ( ArrayDesign oldAd : oldArrayDesigns ) {
if ( oldAd.equals( arrayDesign ) ) continue; // no need to switch
oldAd = arrayDesignService.thaw( oldAd );
if ( oldAd.getCompositeSequences().size() == 0 ) {
throw new IllegalStateException( oldAd + " has no composite sequences" );
}
Collection<QuantitationType> qts = expressionExperimentService.getQuantitationTypes( expExp, oldAd );
log.info( "Processing " + qts.size() + " quantitation types for vectors on " + oldAd );
for ( QuantitationType type : qts ) {
// use each design element only once per quantitation type + bioassaydimension per array design
usedDesignElements.clear();
Collection<? extends DesignElementDataVector> vectorsForQt = getVectorsForOneQuantitationType( oldAd,
type );
if ( vectorsForQt == null || vectorsForQt.size() == 0 ) {
/*
* This can happen when the quantitation types vary for the array designs.
*/
log.debug( "No vectors for " + type + " on " + oldAd );
continue;
}
log.info( "Processing " + vectorsForQt.size() + " vectors for " + type + " on " + oldAd );
int count = 0;
Class<? extends DesignElementDataVector> vectorClass = null;
for ( DesignElementDataVector vector : vectorsForQt ) {
if ( vectorClass == null ) {
vectorClass = vector.getClass();
}
if ( !vector.getClass().equals( vectorClass ) ) {
throw new IllegalStateException( "Two types of vector for one quantitationtype: " + type );
}
// we're doing this by array design; nice to have a method to fetch those only, oh well.
if ( !vector.getDesignElement().getArrayDesign().equals( oldAd ) ) {
continue;
}
processVector( designElementMap, usedDesignElements, vector );
if ( ++count % 20000 == 0 ) {
log.info( "Found matches for " + count + " vectors for " + type );
}
}
log.info( "Updating " + count + " vectors for " + type );
if ( vectorClass != null ) {
if ( vectorClass.equals( RawExpressionDataVector.class ) ) {
designElementDataVectorService.update( vectorsForQt );
} else {
processedExpressionDataVectorService
.update( ( Collection<ProcessedExpressionDataVector> ) vectorsForQt );
}
}
}
}
log.info( "Updating bioAssays ... " );
for ( BioAssay assay : expExp.getBioAssays() ) {
assay.setArrayDesignUsed( arrayDesign );
bioAssayService.update( assay );
}
expExp.setDescription( expExp.getDescription() + " [Switched to use " + arrayDesign.getShortName()
+ " by Gemma]" );
expressionExperimentService.update( expExp );
log.info( "Done switching " + expExp );
audit( expExp, "Switch to use " + arrayDesign.getShortName() );
}
/**
* @param expExp
* @return
*/
private ArrayDesign locateMergedDesign( ExpressionExperiment expExp ) {
// get the array designs for this EE
ArrayDesign arrayDesign = null;
Collection<ArrayDesign> oldArrayDesigns = expressionExperimentService.getArrayDesignsUsed( expExp );
// find the AD they have been merged into, make sure it is exists and they are all merged into the same AD.
for ( ArrayDesign design : oldArrayDesigns ) {
ArrayDesign mergedInto = design.getMergedInto();
mergedInto = arrayDesignService.thaw( mergedInto );
if ( mergedInto == null ) {
throw new IllegalArgumentException( design + " used by " + expExp
+ " is not merged into another design" );
}
// TODO: go up the merge tree to find the root. This is too slow.
// while ( mergedInto.getMergedInto() != null ) {
// mergedInto = arrayDesignService.thaw( mergedInto.getMergedInto() );
// }
if ( arrayDesign == null ) {
arrayDesign = mergedInto;
arrayDesignService.thaw( arrayDesign );
}
if ( !mergedInto.equals( arrayDesign ) ) {
throw new IllegalArgumentException( design + " used by " + expExp + " is not merged into "
+ arrayDesign );
}
}
return arrayDesign;
}
/**
* @param designElementMap
* @param usedDesignElements probes from the new design that have already been assigned to probes from the old
* design. If things are done correctly (the old design was merged into the new) then there should be enough.
* Map is of the new design probe to the old design probe it was used for (this is debugging information)
* @param vector
* @throw IllegalStateException if there is no (unused) design element matching the vector's biosequence
*/
private boolean processVector( Map<BioSequence, Collection<DesignElement>> designElementMap,
Map<DesignElement, Collection<BioAssayDimension>> usedDesignElements, DesignElementDataVector vector ) {
CompositeSequence oldDe = ( CompositeSequence ) vector.getDesignElement();
Collection<DesignElement> newElCandidates = null;
BioSequence seq = oldDe.getBiologicalCharacteristic();
if ( seq == null ) {
newElCandidates = designElementMap.get( NULL_BIOSEQUENCE );
} else {
newElCandidates = designElementMap.get( seq );
}
boolean found = false;
if ( newElCandidates != null && !newElCandidates.isEmpty() ) {
for ( DesignElement newEl : newElCandidates ) {
if ( !usedDesignElements.containsKey( newEl ) ) {
vector.setDesignElement( newEl );
usedDesignElements.put( newEl, new HashSet<BioAssayDimension>() );
usedDesignElements.get( newEl ).add( vector.getBioAssayDimension() );
found = true;
break;
}
if ( !usedDesignElements.get( newEl ).contains( vector.getBioAssayDimension() ) ) {
/*
* Then it's okay to use it.
*/
vector.setDesignElement( newEl );
usedDesignElements.get( newEl ).add( vector.getBioAssayDimension() );
found = true;
break;
}
}
// if ( !found ) {
//
// // This means that the quantitation type + bioassaydimension has two vectors for the same probe, which
// // should not happen.
//
// /*
// * The bioassaydimension will not be the same I hope?
// */
//
// throw new IllegalStateException(
// "Experiment has more than one vector for the same quantitation type - bioassaydimension - design element combination: "
// + oldDe + " (seq=" + seq + "; array=" + oldDe.getArrayDesign() + " and "
// + usedDesignElements.get( newElCandidates.iterator().next() ) );
//
// // /*
// // * This is also a case that should not happen if merging etc. is correct.
// // */
// // throw new IllegalStateException( "Matching candidate probes for " + oldDe + " (seq=" + seq +
// // "; array="
// // + oldDe.getArrayDesign() + ") were already used: " + StringUtils.join( newElCandidates, "," )
// // + ", mapped by [first one shown] " + usedDesignElements.get( newElCandidates.iterator().next() ) );
//
// }
}
if ( !found ) {
throw new IllegalStateException( "No new design element available to match " + oldDe + " (seq=" + seq
+ "; array=" + oldDe.getArrayDesign() + ")" );
}
return true;
}
public void setExpressionExperimentService( ExpressionExperimentService expressionExperimentService ) {
this.expressionExperimentService = expressionExperimentService;
}
public void setBioAssayService( BioAssayService bioAssayService ) {
this.bioAssayService = bioAssayService;
}
public void setArrayDesignService( ArrayDesignService arrayDesignService ) {
this.arrayDesignService = arrayDesignService;
}
}
| gemma-core/src/main/java/ubic/gemma/loader/expression/ExpressionExperimentPlatformSwitchService.java | /*
* The Gemma project
*
* Copyright (c) 2007 University of British Columbia
*
* 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 ubic.gemma.loader.expression;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ubic.gemma.analysis.service.ExpressionExperimentVectorManipulatingService;
import ubic.gemma.model.common.auditAndSecurity.AuditTrailService;
import ubic.gemma.model.common.auditAndSecurity.eventType.AuditEventType;
import ubic.gemma.model.common.auditAndSecurity.eventType.ExpressionExperimentPlatformSwitchEvent;
import ubic.gemma.model.common.quantitationtype.QuantitationType;
import ubic.gemma.model.expression.arrayDesign.ArrayDesign;
import ubic.gemma.model.expression.arrayDesign.ArrayDesignService;
import ubic.gemma.model.expression.bioAssay.BioAssay;
import ubic.gemma.model.expression.bioAssay.BioAssayService;
import ubic.gemma.model.expression.bioAssayData.DesignElementDataVector;
import ubic.gemma.model.expression.bioAssayData.ProcessedExpressionDataVector;
import ubic.gemma.model.expression.bioAssayData.RawExpressionDataVector;
import ubic.gemma.model.expression.designElement.CompositeSequence;
import ubic.gemma.model.expression.designElement.DesignElement;
import ubic.gemma.model.expression.experiment.ExpressionExperiment;
import ubic.gemma.model.expression.experiment.ExpressionExperimentService;
import ubic.gemma.model.genome.biosequence.BioSequence;
/**
* Switch an expression experiment from one array design to another. This is valuable when the EE uses more than on AD,
* and a merged AD exists. The following steps are needed:
* <ul>
* <li>For each array design, for each probe, identify the matching probe on the merged AD. Have to deal with situation
* <li>where more than one occurrence of each sequence is found.
* <li>all DEDVs must be switched to use the new AD's design elements
* <li>all bioassays must be switched to the new AD.
* <li>update the EE description
* <li>commit changes.
* </ul>
*
* @author pavlidis
* @version $Id$
*/
@Service
public class ExpressionExperimentPlatformSwitchService extends ExpressionExperimentVectorManipulatingService {
/**
* Used to identify design elements that have no sequence associated with them.
*/
private static BioSequence NULL_BIOSEQUENCE;
static {
NULL_BIOSEQUENCE = BioSequence.Factory.newInstance();
NULL_BIOSEQUENCE.setName( "______NULL______" );
NULL_BIOSEQUENCE.setId( -1L );
}
private static Log log = LogFactory.getLog( ExpressionExperimentPlatformSwitchService.class.getName() );
@Autowired
ExpressionExperimentService expressionExperimentService;
@Autowired
ArrayDesignService arrayDesignService;
@Autowired
BioAssayService bioAssayService;
@Autowired
private AuditTrailService auditTrailService;
public void setAuditTrailService( AuditTrailService auditTrailService ) {
this.auditTrailService = auditTrailService;
}
/**
* @param arrayDesign
*/
private void audit( ExpressionExperiment ee, String note ) {
AuditEventType eventType = ExpressionExperimentPlatformSwitchEvent.Factory.newInstance();
auditTrailService.addUpdateEvent( ee, eventType, note );
}
/**
* @param expExp
* @param arrayDesign
*/
public void switchExperimentToMergedPlatform( ExpressionExperiment expExp ) {
ArrayDesign arrayDesign = locateMergedDesign( expExp );
if ( arrayDesign == null )
throw new IllegalArgumentException( "Experiment has no merged design to switch to" );
this.switchExperimentToArrayDesign( expExp, arrayDesign );
}
/**
* If you know the arraydesigns are already in a merged state, you should use switchExperimentToMergedPlatform
*
* @param expExp
* @param arrayDesign The array design to switch to. If some samples already use that array design, nothing will be
* changed for them.
*/
@SuppressWarnings("unchecked")
public void switchExperimentToArrayDesign( ExpressionExperiment expExp, ArrayDesign arrayDesign ) {
assert arrayDesign != null;
// get relation between sequence and designelements.
Map<BioSequence, Collection<DesignElement>> designElementMap = new HashMap<BioSequence, Collection<DesignElement>>();
Collection<DesignElement> elsWithNoSeq = new HashSet<DesignElement>();
for ( CompositeSequence cs : arrayDesign.getCompositeSequences() ) {
BioSequence bs = cs.getBiologicalCharacteristic();
if ( bs == null ) {
elsWithNoSeq.add( cs );
} else {
if ( !designElementMap.containsKey( bs ) ) {
designElementMap.put( bs, new HashSet<DesignElement>() );
}
designElementMap.get( bs ).add( cs );
}
}
log.info( elsWithNoSeq.size()
+ " composite sequences on the new array design have no biologicalcharacteristic." );
designElementMap.put( NULL_BIOSEQUENCE, elsWithNoSeq );
Collection<ArrayDesign> oldArrayDesigns = expressionExperimentService.getArrayDesignsUsed( expExp );
Map<DesignElement, DesignElement> usedDesignElements = new HashMap<DesignElement, DesignElement>();
for ( ArrayDesign oldAd : oldArrayDesigns ) {
if ( oldAd.equals( arrayDesign ) ) continue; // no need to switch
oldAd = arrayDesignService.thaw( oldAd );
if ( oldAd.getCompositeSequences().size() == 0 ) {
throw new IllegalStateException( oldAd + " has no composite sequences" );
}
Collection<QuantitationType> qts = expressionExperimentService.getQuantitationTypes( expExp, oldAd );
log.info( "Processing " + qts.size() + " quantitation types for vectors on " + oldAd );
for ( QuantitationType type : qts ) {
// use each design element only once per quantitation type per array design.
usedDesignElements.clear();
Collection<? extends DesignElementDataVector> vectorsForQt = getVectorsForOneQuantitationType( oldAd,
type );
if ( vectorsForQt == null || vectorsForQt.size() == 0 ) {
/*
* This can happen when the quantitation types vary for the array designs.
*/
log.debug( "No vectors for " + type + " on " + oldAd );
continue;
}
log.info( "Processing " + vectorsForQt.size() + " vectors for " + type + " on " + oldAd );
int count = 0;
Class<? extends DesignElementDataVector> vectorClass = null;
for ( DesignElementDataVector vector : vectorsForQt ) {
if ( vectorClass == null ) {
vectorClass = vector.getClass();
}
if ( !vector.getClass().equals( vectorClass ) ) {
throw new IllegalStateException( "Two types of vector for one quantitationtype: " + type );
}
// we're doing this by array design; nice to have a method to fetch those only, oh well.
if ( !vector.getDesignElement().getArrayDesign().equals( oldAd ) ) {
continue;
}
processVector( designElementMap, usedDesignElements, vector );
if ( ++count % 20000 == 0 ) {
log.info( "Found matches for " + count + " vectors for " + type );
}
}
log.info( "Updating " + count + " vectors for " + type );
if ( vectorClass != null ) {
if ( vectorClass.equals( RawExpressionDataVector.class ) ) {
designElementDataVectorService.update( vectorsForQt );
} else {
processedExpressionDataVectorService
.update( ( Collection<ProcessedExpressionDataVector> ) vectorsForQt );
}
}
}
}
log.info( "Updating bioAssays ... " );
for ( BioAssay assay : expExp.getBioAssays() ) {
assay.setArrayDesignUsed( arrayDesign );
bioAssayService.update( assay );
}
expExp.setDescription( expExp.getDescription() + " [Switched to use " + arrayDesign.getShortName()
+ " by Gemma]" );
expressionExperimentService.update( expExp );
log.info( "Done switching " + expExp );
audit( expExp, "Switch to use " + arrayDesign.getShortName() );
}
/**
* @param expExp
* @return
*/
private ArrayDesign locateMergedDesign( ExpressionExperiment expExp ) {
// get the array designs for this EE
ArrayDesign arrayDesign = null;
Collection<ArrayDesign> oldArrayDesigns = expressionExperimentService.getArrayDesignsUsed( expExp );
// find the AD they have been merged into, make sure it is exists and they are all merged into the same AD.
for ( ArrayDesign design : oldArrayDesigns ) {
ArrayDesign mergedInto = design.getMergedInto();
mergedInto = arrayDesignService.thaw( mergedInto );
if ( mergedInto == null ) {
throw new IllegalArgumentException( design + " used by " + expExp
+ " is not merged into another design" );
}
// TODO: go up the merge tree to find the root. This is too slow.
// while ( mergedInto.getMergedInto() != null ) {
// mergedInto = arrayDesignService.thaw( mergedInto.getMergedInto() );
// }
if ( arrayDesign == null ) {
arrayDesign = mergedInto;
arrayDesignService.thaw( arrayDesign );
}
if ( !mergedInto.equals( arrayDesign ) ) {
throw new IllegalArgumentException( design + " used by " + expExp + " is not merged into "
+ arrayDesign );
}
}
return arrayDesign;
}
/**
* @param designElementMap
* @param usedDesignElements probes from the new design that have already been assigned to probes from the old
* design. If things are done correctly (the old design was merged into the new) then there should be enough.
* Map is of the new design probe to the old design probe it was used for (this is debugging information)
* @param vector
* @throw IllegalStateException if there is no (unused) design element matching the vector's biosequence
*/
private boolean processVector( Map<BioSequence, Collection<DesignElement>> designElementMap,
Map<DesignElement, DesignElement> usedDesignElements, DesignElementDataVector vector ) {
CompositeSequence oldDe = ( CompositeSequence ) vector.getDesignElement();
Collection<DesignElement> newElCandidates = null;
BioSequence seq = oldDe.getBiologicalCharacteristic();
if ( seq == null ) {
newElCandidates = designElementMap.get( NULL_BIOSEQUENCE );
} else {
newElCandidates = designElementMap.get( seq );
}
boolean found = false;
if ( newElCandidates != null && !newElCandidates.isEmpty() ) {
for ( DesignElement newEl : newElCandidates ) {
if ( !usedDesignElements.containsKey( newEl ) ) {
vector.setDesignElement( newEl );
usedDesignElements.put( newEl, oldDe );
found = true;
break;
}
}
if ( !found ) {
throw new IllegalStateException( "Matching candidate probes for " + oldDe + " (seq=" + seq + "; array="
+ oldDe.getArrayDesign() + ") were already used: " + StringUtils.join( newElCandidates, "," )
+ ", mapped by [first one shown] " + usedDesignElements.get( newElCandidates.iterator().next() ) );
}
}
if ( !found ) {
throw new IllegalStateException( "No new design element available to match " + oldDe + " (seq=" + seq
+ "; array=" + oldDe.getArrayDesign() + ")" );
}
return true;
}
public void setExpressionExperimentService( ExpressionExperimentService expressionExperimentService ) {
this.expressionExperimentService = expressionExperimentService;
}
public void setBioAssayService( BioAssayService bioAssayService ) {
this.bioAssayService = bioAssayService;
}
public void setArrayDesignService( ArrayDesignService arrayDesignService ) {
this.arrayDesignService = arrayDesignService;
}
}
| allow reuse of design elements for different bioassay dimensions
| gemma-core/src/main/java/ubic/gemma/loader/expression/ExpressionExperimentPlatformSwitchService.java | allow reuse of design elements for different bioassay dimensions | |
Java | apache-2.0 | 4f067fda7a85aefb28f8dcd427ec408b8298b50e | 0 | EBISPOT/goci,EBISPOT/goci,EBISPOT/goci,EBISPOT/goci,EBISPOT/goci,EBISPOT/goci |
package uk.ac.ebi.spot.goci.curation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
* Created by emma on 09/02/15.
* @author emma
*/
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/users/**").hasAuthority("admin")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.usernameParameter("useremail")
.defaultSuccessUrl("/studies")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/")
.permitAll().and().rememberMe();
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
}
| goci-interfaces/goci-curation/src/main/java/uk/ac/ebi/spot/goci/curation/SecurityConfiguration.java |
package uk.ac.ebi.spot.goci.curation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
* Created by emma on 09/02/15.
* @author emma
*/
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/users/**").hasAuthority("admin")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.usernameParameter("useremail")
.defaultSuccessUrl("/studies")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/")
.permitAll();
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
}
| Added remember me parameter to security to see if it solves login/logout probelm on orange
| goci-interfaces/goci-curation/src/main/java/uk/ac/ebi/spot/goci/curation/SecurityConfiguration.java | Added remember me parameter to security to see if it solves login/logout probelm on orange | |
Java | apache-2.0 | 3011e19cdccbff9c302cc11d79d1a73b5658ed21 | 0 | hariss63/esb-connector-gmail | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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 org.wso2.carbon.connector;
import com.google.code.javax.mail.MessagingException;
import org.apache.synapse.MessageContext;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.wso2.carbon.connector.core.AbstractConnector;
import org.wso2.carbon.connector.core.ConnectException;
/**
* Class which reads OAuth access token and user name parameters from the
* message context to perform OAuth authentication for Gmail.
*/
public class GmailConfig extends AbstractConnector {
/*
* Extracts the values for OAuth access token and user name from the message
* context and stores them in the message context.
*/
@Override
public void connect(MessageContext messageContext) throws ConnectException {
try {
// Reading OAuth access token and user name from the message context
String accessToken = (String) messageContext.getProperty(GmailConstants.GMAIL_ACCESSTOKEN);
String userId = GmailUtils.lookupFunctionParam(messageContext, GmailConstants.GMAIL_PARAM_USERNAME);
// Storing OAuth user login details in the message context
this.storeOauthUserLogin(messageContext, userId, accessToken);
} catch (MessagingException e) {
GmailUtils.storeErrorResponseStatus(messageContext,
e,
GmailErrorCodes.GMAIL_ERROR_CODE_MESSAGING_EXCEPTION);
handleException(e.getMessage(), e, messageContext);
} catch (Exception e) {
GmailUtils.storeErrorResponseStatus(messageContext, e,
GmailErrorCodes.GMAIL_COMMON_EXCEPTION);
handleException(e.getMessage(), e, messageContext);
}
}
/**
* Stores user name and access token for OAuth authentication
*
* @param messageContext message context where the user login information should be
* stored
* @param userId user name
* @param accessToken access token
* @throws com.google.code.javax.mail.MessagingException
*/
private void storeOauthUserLogin(MessageContext messageContext, String userId,
String accessToken) throws MessagingException {
org.apache.axis2.context.MessageContext axis2MessageContext =
((Axis2MessageContext) messageContext).getAxis2MessageContext();
Object loginMode = axis2MessageContext.getProperty(GmailConstants.GMAIL_LOGIN_MODE);
if (loginMode != null &&
(loginMode.toString() == GmailConstants.GMAIL_OAUTH_LOGIN_MODE) &&
messageContext.getProperty(GmailConstants.GMAIL_OAUTH_USERNAME).toString()
.equals(userId) &&
messageContext.getProperty(GmailConstants.GMAIL_OAUTH_ACCESS_TOKEN).toString()
.equals(accessToken)) {
log.info("The same authentication is already available. Hence no changes are needed.");
return;
}
// Reset already stored instances
GmailUtils.closeConnection(axis2MessageContext);
if (log.isDebugEnabled()) {
log.debug("Setting the logging mode to \"OAUTH\"");
}
axis2MessageContext.setProperty(GmailConstants.GMAIL_LOGIN_MODE,
GmailConstants.GMAIL_OAUTH_LOGIN_MODE);
if (log.isDebugEnabled()) {
log.debug("Storing the new username and access token");
}
messageContext.setProperty(GmailConstants.GMAIL_OAUTH_USERNAME, userId);
messageContext.setProperty(GmailConstants.GMAIL_OAUTH_ACCESS_TOKEN, accessToken);
}
}
| src/main/java/org/wso2/carbon/connector/GmailConfig.java | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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 org.wso2.carbon.connector;
import com.google.code.javax.mail.MessagingException;
import org.apache.synapse.MessageContext;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.wso2.carbon.connector.core.AbstractConnector;
import org.wso2.carbon.connector.core.ConnectException;
/**
* Class which reads OAuth access token and user name parameters from the
* message context to perform OAuth authentication for Gmail.
*/
public class GmailConfig extends AbstractConnector {
/*
* Extracts the values for OAuth access token and user name from the message
* context and stores them in the message context.
*/
@Override
public void connect(MessageContext messageContext) throws ConnectException {
try {
// Reading OAuth access token and user name from the message context
String accessToken =
(String) messageContext.getProperty(GmailConstants.GMAIL_ACCESSTOKEN);
String userId =
GmailUtils.lookupFunctionParam(messageContext,
GmailConstants.GMAIL_PARAM_USERNAME);
// Storing OAuth user login details in the message context
this.storeOauthUserLogin(messageContext, userId, accessToken);
} catch (MessagingException e) {
GmailUtils.storeErrorResponseStatus(messageContext,
e,
GmailErrorCodes.GMAIL_ERROR_CODE_MESSAGING_EXCEPTION);
handleException(e.getMessage(), e, messageContext);
} catch (Exception e) {
GmailUtils.storeErrorResponseStatus(messageContext, e,
GmailErrorCodes.GMAIL_COMMON_EXCEPTION);
handleException(e.getMessage(), e, messageContext);
}
}
/**
* Stores user name and access token for OAuth authentication
*
* @param messageContext message context where the user login information should be
* stored
* @param userId user name
* @param accessToken access token
* @throws com.google.code.javax.mail.MessagingException
*/
private void storeOauthUserLogin(MessageContext messageContext, String userId,
String accessToken) throws MessagingException {
org.apache.axis2.context.MessageContext axis2MessageContext =
((Axis2MessageContext) messageContext).getAxis2MessageContext();
Object loginMode = axis2MessageContext.getProperty(GmailConstants.GMAIL_LOGIN_MODE);
if (loginMode != null &&
(loginMode.toString() == GmailConstants.GMAIL_OAUTH_LOGIN_MODE) &&
messageContext.getProperty(GmailConstants.GMAIL_OAUTH_USERNAME).toString()
.equals(userId) &&
messageContext.getProperty(GmailConstants.GMAIL_OAUTH_ACCESS_TOKEN).toString()
.equals(accessToken)) {
log.info("The same authentication is already available. Hence no changes are needed.");
return;
}
// Reset already stored instances
GmailUtils.closeConnection(axis2MessageContext);
log.info("Setting the logging mode to \"OAUTH\"");
axis2MessageContext.setProperty(GmailConstants.GMAIL_LOGIN_MODE,
GmailConstants.GMAIL_OAUTH_LOGIN_MODE);
log.info("Storing the new username and access token");
messageContext.setProperty(GmailConstants.GMAIL_OAUTH_USERNAME, userId);
messageContext.setProperty(GmailConstants.GMAIL_OAUTH_ACCESS_TOKEN, accessToken);
}
}
| Gmail Connector PR Review
| src/main/java/org/wso2/carbon/connector/GmailConfig.java | Gmail Connector PR Review | |
Java | apache-2.0 | 036f8813d1273cc7b6f5d93228ed0732fc9ac2e1 | 0 | GlenRSmith/elasticsearch,GlenRSmith/elasticsearch,GlenRSmith/elasticsearch,GlenRSmith/elasticsearch,GlenRSmith/elasticsearch | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.common.lucene.store;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.util.BitUtil;
import java.io.EOFException;
import java.io.IOException;
/**
* Wraps array of bytes into IndexInput
*/
public class ByteArrayIndexInput extends IndexInput {
private final byte[] bytes;
private int pos;
private int offset;
private int length;
public ByteArrayIndexInput(String resourceDesc, byte[] bytes) {
this(resourceDesc, bytes, 0, bytes.length);
}
public ByteArrayIndexInput(String resourceDesc, byte[] bytes, int offset, int length) {
super(resourceDesc);
this.bytes = bytes;
this.offset = offset;
this.length = length;
}
@Override
public void close() throws IOException {
}
@Override
public long getFilePointer() {
return pos;
}
@Override
public void seek(long l) throws IOException {
if (l < 0) {
throw new IllegalArgumentException("Seeking to negative position: " + pos);
} else if (l > length) {
throw new EOFException("seek past EOF");
}
pos = (int)l;
}
@Override
public long length() {
return length;
}
@Override
public IndexInput slice(String sliceDescription, long offset, long length) throws IOException {
if (offset >= 0L && length >= 0L && offset + length <= this.length) {
return new ByteArrayIndexInput(sliceDescription, bytes, this.offset + (int)offset, (int)length);
} else {
throw new IllegalArgumentException("slice() " + sliceDescription + " out of bounds: offset=" + offset
+ ",length=" + length + ",fileLength=" + this.length + ": " + this);
}
}
@Override
public byte readByte() throws IOException {
if (pos >= offset + length) {
throw new EOFException("seek past EOF");
}
return bytes[offset + pos++];
}
@Override
public void readBytes(final byte[] b, final int offset, int len) throws IOException {
if (pos + len > this.offset + length) {
throw new EOFException("seek past EOF");
}
System.arraycopy(bytes, this.offset + pos, b, offset, len);
pos += len;
}
@Override
public short readShort() throws IOException {
try {
return (short) BitUtil.VH_LE_SHORT.get(bytes, pos);
} finally {
pos += Short.BYTES;
}
}
@Override
public int readInt() throws IOException {
try {
return (int) BitUtil.VH_LE_INT.get(bytes, pos);
} finally {
pos += Integer.BYTES;
}
}
@Override
public long readLong() throws IOException {
try {
return (long) BitUtil.VH_LE_LONG.get(bytes, pos);
} finally {
pos += Long.BYTES;
}
}
}
| server/src/main/java/org/elasticsearch/common/lucene/store/ByteArrayIndexInput.java | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.common.lucene.store;
import org.apache.lucene.store.IndexInput;
import java.io.EOFException;
import java.io.IOException;
/**
* Wraps array of bytes into IndexInput
*/
public class ByteArrayIndexInput extends IndexInput {
private final byte[] bytes;
private int pos;
private int offset;
private int length;
public ByteArrayIndexInput(String resourceDesc, byte[] bytes) {
this(resourceDesc, bytes, 0, bytes.length);
}
public ByteArrayIndexInput(String resourceDesc, byte[] bytes, int offset, int length) {
super(resourceDesc);
this.bytes = bytes;
this.offset = offset;
this.length = length;
}
@Override
public void close() throws IOException {
}
@Override
public long getFilePointer() {
return pos;
}
@Override
public void seek(long l) throws IOException {
if (l < 0) {
throw new IllegalArgumentException("Seeking to negative position: " + pos);
} else if (l > length) {
throw new EOFException("seek past EOF");
}
pos = (int)l;
}
@Override
public long length() {
return length;
}
@Override
public IndexInput slice(String sliceDescription, long offset, long length) throws IOException {
if (offset >= 0L && length >= 0L && offset + length <= this.length) {
return new ByteArrayIndexInput(sliceDescription, bytes, this.offset + (int)offset, (int)length);
} else {
throw new IllegalArgumentException("slice() " + sliceDescription + " out of bounds: offset=" + offset
+ ",length=" + length + ",fileLength=" + this.length + ": " + this);
}
}
@Override
public byte readByte() throws IOException {
if (pos >= offset + length) {
throw new EOFException("seek past EOF");
}
return bytes[offset + pos++];
}
@Override
public void readBytes(final byte[] b, final int offset, int len) throws IOException {
if (pos + len > this.offset + length) {
throw new EOFException("seek past EOF");
}
System.arraycopy(bytes, this.offset + pos, b, offset, len);
pos += len;
}
}
| Implement primitives reads in ByteArrayIndexInput (#79885)
enhance performance of those actions | server/src/main/java/org/elasticsearch/common/lucene/store/ByteArrayIndexInput.java | Implement primitives reads in ByteArrayIndexInput (#79885) | |
Java | apache-2.0 | 86e1d52a05d00bcdef3cad5d29e1ffa8f1a0e2eb | 0 | Libertymutual/ssh-key-enforcer-stash,Libertymutual/ssh-key-enforcer-stash,Libertymutual/ssh-key-enforcer-stash | /*
* Copyright 2015, Liberty Mutual Group
*
* 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 ut.com.lmig.forge.stash.ssh.keys;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.atlassian.bitbucket.ssh.SshKey;
import com.lmig.forge.stash.ssh.crypto.JschSshKeyPairGenerator;
import com.lmig.forge.stash.ssh.crypto.SshKeyPairGenerator;
import com.lmig.forge.stash.ssh.rest.KeyPairResourceModel;
import net.java.ao.DBParam;
import net.java.ao.EntityManager;
import net.java.ao.test.jdbc.Data;
import net.java.ao.test.jdbc.DatabaseUpdater;
import net.java.ao.test.jdbc.Jdbc;
import net.java.ao.test.jdbc.NonTransactional;
import net.java.ao.test.junit.ActiveObjectsJUnitRunner;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.atlassian.activeobjects.external.ActiveObjects;
import com.atlassian.activeobjects.test.TestActiveObjects;
import com.atlassian.bitbucket.ssh.SshKeyService;
import com.atlassian.bitbucket.user.ApplicationUser;
import com.atlassian.bitbucket.user.UserService;
import com.lmig.forge.stash.ssh.ao.EnterpriseKeyRepository;
import com.lmig.forge.stash.ssh.ao.EnterpriseKeyRepositoryImpl;
import com.lmig.forge.stash.ssh.ao.SshKeyEntity;
import com.lmig.forge.stash.ssh.ao.SshKeyEntity.KeyType;
import com.lmig.forge.stash.ssh.config.PluginSettingsService;
import com.lmig.forge.stash.ssh.keys.EnterpriseSshKeyService;
import com.lmig.forge.stash.ssh.keys.EnterpriseSshKeyServiceImpl;
import com.lmig.forge.stash.ssh.notifications.NotificationService;
import com.lmig.forge.stash.ssh.scheduler.KeyRotationJobRunner;
import org.mockito.ArgumentCaptor;
/**
* Must run all methods that interact with service as @NonTransactional or
* otherwise the multiple layers of transactions cause issues. Also
* http://grepcode
* .com/file/repo1.maven.org/maven2/net.java.dev.activeobjects/activeobjects
* -test/0.23.0/net/java/ao/test/jdbc/DynamicJdbcConfiguration.java#
* DynamicJdbcConfiguration.0jdbcSupplier has all the databtase types and
* connection info needed in maven arguments.
*
* @author Eddie Webb
*
*/
@RunWith(ActiveObjectsJUnitRunner.class)
@Data(value = EnterpriseSshKeyManagerImplTest.EnterpriseSshKeyRepositoryTestData.class)
@Jdbc(net.java.ao.test.jdbc.DynamicJdbcConfiguration.class)
public class EnterpriseSshKeyManagerImplTest {
//this key is pre-saved in our meta tables (see EnterpriseSshKeyRepositoryTestData_, thus 'allowed'
private static final String APPROVED_PUBLIC_KEY_ONE = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC0O2PpfWd0RuoveFkSLP8DaL2ZekQZJM7gzQFi/cavziK8jnAY+xtNIAF1K7EN64JSM2DTMU7BZUFkJvqqbugzc29A/LOfZ6GzvMhSiR7YR2J/eOkVZbmPPyC1qWDCc5Ne71pEJhU5OdlFd4Hj5XgDzNyMANoYlO+xm1IDzHBxDSrvY++VGrnZG1rJ6aSdxyRCoE7MVtQkLuIMDSVPTVfdqDV4oKlH2bzd4LyA1Jm01+MBmWq2qVcKcF6UYKaUILVreZZZSm2/PBbgQ+H5yzjNeEbvdnAr7bcn+xRdhEM0ZGm/RRDRIvwkTlWJ2y9M3KvnJEKbv/c9ZAlOmbs5K1OhfGL/jCU8h1EslwQ9euFp0wjKUMj5u9ll8QqpNcXxsfUnaN9qc2rrm5FS5t5TFAkbIX5fOTJCPb+seE146ax/cNovzOoJUPvF+qBfvJLQGX2L/4JdPqDQ6FkLbvJy194/K5oWag8w4F9ftYIfd/SOgatPMiKuhOls2zYufm34UBbksc7qxDD12JUiI/q7JNted53tnPVBSDLM5RYtohDq/w4MfyFmA51UeETSLumlwg9kOuqaWBYjr2Esn09EtkQNIhQxxt3w47O0RFghZgJdnP3VORju3v2l0Qfo7A/EbeDGKXQhCl6yeMv82lmUtzOhVN6IAApOwMH7Hmh/z209jw==";
//this key does not match any key in our meta tables and considered invalid/unapproved.
private static final String UNAPPROVED_PUBLIC_KEY_ONE = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC0O2PpfWd0RuoveFkSLP8DaL2ZekQZJM7gzQFi/cavziK8jnAY+xtNIAF1K7EN64JSM2DTMU7BZUFkJvqqbugzc29A/LOfZ6GzvMhSiR7YR2J/eOkVZbmPPyC1qWDCc5Ne71pEJhU5OdlFd4Hj5XgDzNyMANoYlO+xm1IDzHBxDSrvY++VGrnZG1rJ6aSdxyRCoE7MVtQkLuIMDSVPTVfdqDV4oKlH2bzd4LyA1Jm01+MBmWq2qVcKcF6UYKaUILVreZZZSm2/PBbgQ+H5yzjNeEbvdnAr7bcn+xRdhEM0ZGm/RRDRIvwkTlWJ2y9M3KvnJEKbv/c9ZAlOmbs5K1OhfGL/jCU8h1EslwQ9euFp0wjKUMj5u9ll8QqpNcXxsfUnaN9qc2rrm5FS5t5TFAkbIX5fOTJCPb+seE146ax/cNovzOoJUPvF+qBfvJLQGX2L/4JdPqDQ6FkLbvJy194/K5oWag8w4F9ftYIfd/SOgatPMiKuhOls2zYufm34UBbksc7qxDD1DG";
private static final int EXPIRED_USER_ID = 1;
private static final int VALID_USER_ID = 2;
private static final int EXPIRED_STASH_KEY_ID = 100;
private static final int VALID_STASH_KEY_ID = 200;
private static final int VALID_BYPASS_KEY_ID = 300;
private static final int DAYS_ALLOWED = 90;
private static final String AUTHED_GROUP = "the-monkeys";
// gets injected thanks to ActiveObjectsJUnitRunner.class
private EntityManager entityManager;
private ActiveObjects ao;
private EnterpriseKeyRepository keyRepo;
private EnterpriseSshKeyService ourKeyService;
private NotificationService notificationService;
private SshKeyService stashKeyService;
private SshKeyPairGenerator keyPairGenerator;
private UserService userService;
private PluginSettingsService pluginSettingsService;
private ApplicationUser unblessedUser ;
private ApplicationUser blessedUser;
private SshKey approvedUserKey = mock(SshKey.class);
private SshKey unapprovedUserKey = mock(SshKey.class);
private SshKey existingKeyForUnapprovedUser = mock(SshKey.class);
@Before
public void setup() {
//mock app users
userService = mock(UserService.class);
unblessedUser = mock(ApplicationUser.class);
when(unblessedUser.getId()).thenReturn(VALID_USER_ID);
when(userService.isUserInGroup(unblessedUser, AUTHED_GROUP)).thenReturn(false);
blessedUser = mock(ApplicationUser.class);
when(blessedUser.getId()).thenReturn(VALID_USER_ID);
when(userService.isUserInGroup(blessedUser, AUTHED_GROUP)).thenReturn(true);
// mock their keys and potential keys
when(approvedUserKey.getText()).thenReturn(APPROVED_PUBLIC_KEY_ONE);
when(approvedUserKey.getUser()).thenReturn(blessedUser);
when(unapprovedUserKey.getText()).thenReturn(UNAPPROVED_PUBLIC_KEY_ONE);
when(unapprovedUserKey.getUser()).thenReturn(unblessedUser);
when(existingKeyForUnapprovedUser.getText()).thenReturn(APPROVED_PUBLIC_KEY_ONE);
when(existingKeyForUnapprovedUser.getUser()).thenReturn(unblessedUser);
ao = new TestActiveObjects(entityManager);
keyRepo = new EnterpriseKeyRepositoryImpl(ao);
stashKeyService = mock(SshKeyService.class);
when(stashKeyService.addForUser(any(ApplicationUser.class),anyString())).thenReturn(approvedUserKey);
notificationService = mock(NotificationService.class);
keyPairGenerator = new JschSshKeyPairGenerator();
when(userService.existsGroup(anyString())).thenReturn(true);
pluginSettingsService = mock(PluginSettingsService.class);
when(pluginSettingsService.getMillisBetweenRuns()).thenReturn(60000L);
when(pluginSettingsService.getDaysAllowedForUserKeys()).thenReturn(DAYS_ALLOWED);
when(pluginSettingsService.getDaysAllowedForBambooKeys()).thenReturn(DAYS_ALLOWED);
when(pluginSettingsService.getAuthorizedGroup()).thenReturn(AUTHED_GROUP);
when(userService.getUserByName(KeyRotationJobRunner.ADMIN_ACCOUNT_NAME)).thenReturn(mock(ApplicationUser.class));//defeat NPE check
ourKeyService = new EnterpriseSshKeyServiceImpl(stashKeyService, keyRepo, keyPairGenerator, notificationService,userService, pluginSettingsService);
}
@Test
public void whenExpireTaskIsCalledValidKeysAreIgnored() {
SshKeyEntity validKey = ao.get(SshKeyEntity.class, EnterpriseSshKeyRepositoryTestData.validKey.getID());
assertThat(validKey, notNullValue());
assertThat(validKey.getKeyId(), is(VALID_STASH_KEY_ID));
ourKeyService.replaceExpiredKeysAndNotifyUsers();
// key survived?
validKey = ao.get(SshKeyEntity.class, EnterpriseSshKeyRepositoryTestData.validKey.getID());
assertThat(validKey, notNullValue());
// stash's ssh service was not invoked
verify(stashKeyService, times(0)).remove(VALID_STASH_KEY_ID);
}
@Test
@NonTransactional
public void whenExpireTaskIsCalledExpiredKeysAreDestroyed() {
SshKeyEntity validKey = ao.get(SshKeyEntity.class, EnterpriseSshKeyRepositoryTestData.expiredKey.getID());
assertThat(validKey, notNullValue());
assertThat(validKey.getKeyId(), is(EXPIRED_STASH_KEY_ID));
ourKeyService.replaceExpiredKeysAndNotifyUsers();
// key was purged?
validKey = ao.get(SshKeyEntity.class, EnterpriseSshKeyRepositoryTestData.expiredKey.getID());
assertThat(validKey, nullValue());
// stash ssh remve was called with ecxpired ssh key id
verify(stashKeyService).remove(EXPIRED_STASH_KEY_ID);
}
@Test
public void whenKeyIsExpiredTheAppropriateUserIsNotified() {
ourKeyService.replaceExpiredKeysAndNotifyUsers();
verify(notificationService).notifyUserOfExpiredKey(EXPIRED_USER_ID);
}
@Test
public void userInBlessedGroupMayByPassDirectService(){
//given unknown key from an authorized user
boolean isAllowed = ourKeyService.isKeyValidForUser(unapprovedUserKey, blessedUser);
// then the key is accepted by rules
assertThat(isAllowed,is(true));
}
@Test
public void unknownKeysCreatedByUnauthorizedUsersAreNotAllowed(){
//given an unknown key from a non-authorized (standard) user
boolean isAllowed = ourKeyService.isKeyValidForUser(unapprovedUserKey, unblessedUser);
//then the keys are rejected by rules
assertThat(isAllowed,is(false));
}
@Test
// EVen when we create keys the event will fire causing it to be checked against rules
// make sure we dont delete our own keys!
public void keyCreatedViaCustomServiceIsAccptedByValidator(){
//given a pre-registered (i.e. known) key from an unauthorized (standard) user,
boolean isAllowed = ourKeyService.isKeyValidForUser(existingKeyForUnapprovedUser, unblessedUser);
// then the key will be allowed
assertThat(isAllowed,is(true));
}
@Test
@NonTransactional
public void generatingNewUserKeysIgnoresNonUserTypeLeys(){
//given a user with existing USER and BYPASS keys
// (created via EnterpriseSshKeyRepositoryTestData below )
//when new USER key is created
ourKeyService.generateNewKeyPairFor(blessedUser);
//then previous BYPASS key remains
verify(stashKeyService,times(0)).removeAllForUser(blessedUser);
verify(stashKeyService, times(0)).remove(VALID_BYPASS_KEY_ID);
//but preivous USER key does not
verify(stashKeyService).remove(VALID_STASH_KEY_ID);
}
public static class EnterpriseSshKeyRepositoryTestData implements DatabaseUpdater {
private static SshKeyEntity expiredKey;
private static SshKeyEntity validKey;
@Override
public void update(EntityManager em) throws Exception {
em.migrate(SshKeyEntity.class);
// create an expired and non-expired ID.
// Also create a BYPASS ID so that all types are present
// IMPORTANT - only use APPROVED_PUBLIC_KEY to make sure validation rules dont allow UNAPPROVED key in test sabove
DateTime now = new DateTime();
expiredKey = em.create(SshKeyEntity.class, new DBParam("USERID", EXPIRED_USER_ID), new DBParam("KEYID",
EXPIRED_STASH_KEY_ID), new DBParam("TEXT", APPROVED_PUBLIC_KEY_ONE), new DBParam("LABEL", "COMPROMISED"), new DBParam("TYPE", KeyType.USER),
new DBParam("CREATED", now.minusDays(DAYS_ALLOWED+1).toDate()));
validKey = em.create(SshKeyEntity.class, new DBParam("USERID", VALID_USER_ID), new DBParam("KEYID",
VALID_STASH_KEY_ID), new DBParam("TEXT", APPROVED_PUBLIC_KEY_ONE), new DBParam("LABEL", "VALID"), new DBParam("TYPE", KeyType.USER),
new DBParam("CREATED", now.minusDays(DAYS_ALLOWED-1).toDate()));
SshKeyEntity bypassKey = em.create(SshKeyEntity.class, new DBParam("USERID", VALID_USER_ID), new DBParam("KEYID",
VALID_BYPASS_KEY_ID), new DBParam("TEXT", APPROVED_PUBLIC_KEY_ONE), new DBParam("LABEL", "BYPASS"), new DBParam("TYPE", KeyType.BYPASS),
new DBParam("CREATED", now.minusDays(DAYS_ALLOWED-1).toDate()));
}
}
}
| src/test/java/ut/com/lmig/forge/stash/ssh/keys/EnterpriseSshKeyManagerImplTest.java | /*
* Copyright 2015, Liberty Mutual Group
*
* 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 ut.com.lmig.forge.stash.ssh.keys;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.atlassian.bitbucket.ssh.SshKey;
import com.lmig.forge.stash.ssh.crypto.JschSshKeyPairGenerator;
import com.lmig.forge.stash.ssh.crypto.SshKeyPairGenerator;
import com.lmig.forge.stash.ssh.rest.KeyPairResourceModel;
import net.java.ao.DBParam;
import net.java.ao.EntityManager;
import net.java.ao.test.jdbc.Data;
import net.java.ao.test.jdbc.DatabaseUpdater;
import net.java.ao.test.jdbc.Jdbc;
import net.java.ao.test.jdbc.NonTransactional;
import net.java.ao.test.junit.ActiveObjectsJUnitRunner;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.atlassian.activeobjects.external.ActiveObjects;
import com.atlassian.activeobjects.test.TestActiveObjects;
import com.atlassian.bitbucket.ssh.SshKeyService;
import com.atlassian.bitbucket.user.ApplicationUser;
import com.atlassian.bitbucket.user.UserService;
import com.lmig.forge.stash.ssh.ao.EnterpriseKeyRepository;
import com.lmig.forge.stash.ssh.ao.EnterpriseKeyRepositoryImpl;
import com.lmig.forge.stash.ssh.ao.SshKeyEntity;
import com.lmig.forge.stash.ssh.ao.SshKeyEntity.KeyType;
import com.lmig.forge.stash.ssh.config.PluginSettingsService;
import com.lmig.forge.stash.ssh.keys.EnterpriseSshKeyService;
import com.lmig.forge.stash.ssh.keys.EnterpriseSshKeyServiceImpl;
import com.lmig.forge.stash.ssh.notifications.NotificationService;
import com.lmig.forge.stash.ssh.scheduler.KeyRotationJobRunner;
import org.mockito.ArgumentCaptor;
/**
* Must run all methods that interact with service as @NonTransactional or
* otherwise the multiple layers of transactions cause issues. Also
* http://grepcode
* .com/file/repo1.maven.org/maven2/net.java.dev.activeobjects/activeobjects
* -test/0.23.0/net/java/ao/test/jdbc/DynamicJdbcConfiguration.java#
* DynamicJdbcConfiguration.0jdbcSupplier has all the databtase types and
* connection info needed in maven arguments.
*
* @author Eddie Webb
*
*/
@RunWith(ActiveObjectsJUnitRunner.class)
@Data(value = EnterpriseSshKeyManagerImplTest.EnterpriseSshKeyRepositoryTestData.class)
@Jdbc(net.java.ao.test.jdbc.DynamicJdbcConfiguration.class)
public class EnterpriseSshKeyManagerImplTest {
private static final String APPROVED_PUBLIC_KEY_ONE = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC0O2PpfWd0RuoveFkSLP8DaL2ZekQZJM7gzQFi/cavziK8jnAY+xtNIAF1K7EN64JSM2DTMU7BZUFkJvqqbugzc29A/LOfZ6GzvMhSiR7YR2J/eOkVZbmPPyC1qWDCc5Ne71pEJhU5OdlFd4Hj5XgDzNyMANoYlO+xm1IDzHBxDSrvY++VGrnZG1rJ6aSdxyRCoE7MVtQkLuIMDSVPTVfdqDV4oKlH2bzd4LyA1Jm01+MBmWq2qVcKcF6UYKaUILVreZZZSm2/PBbgQ+H5yzjNeEbvdnAr7bcn+xRdhEM0ZGm/RRDRIvwkTlWJ2y9M3KvnJEKbv/c9ZAlOmbs5K1OhfGL/jCU8h1EslwQ9euFp0wjKUMj5u9ll8QqpNcXxsfUnaN9qc2rrm5FS5t5TFAkbIX5fOTJCPb+seE146ax/cNovzOoJUPvF+qBfvJLQGX2L/4JdPqDQ6FkLbvJy194/K5oWag8w4F9ftYIfd/SOgatPMiKuhOls2zYufm34UBbksc7qxDD12JUiI/q7JNted53tnPVBSDLM5RYtohDq/w4MfyFmA51UeETSLumlwg9kOuqaWBYjr2Esn09EtkQNIhQxxt3w47O0RFghZgJdnP3VORju3v2l0Qfo7A/EbeDGKXQhCl6yeMv82lmUtzOhVN6IAApOwMH7Hmh/z209jw==";
private static final String UNAPPROVED_PUBLIC_KEY_ONE = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC0O2PpfWd0RuoveFkSLP8DaL2ZekQZJM7gzQFi/cavziK8jnAY+xtNIAF1K7EN64JSM2DTMU7BZUFkJvqqbugzc29A/LOfZ6GzvMhSiR7YR2J/eOkVZbmPPyC1qWDCc5Ne71pEJhU5OdlFd4Hj5XgDzNyMANoYlO+xm1IDzHBxDSrvY++VGrnZG1rJ6aSdxyRCoE7MVtQkLuIMDSVPTVfdqDV4oKlH2bzd4LyA1Jm01+MBmWq2qVcKcF6UYKaUILVreZZZSm2/PBbgQ+H5yzjNeEbvdnAr7bcn+xRdhEM0ZGm/RRDRIvwkTlWJ2y9M3KvnJEKbv/c9ZAlOmbs5K1OhfGL/jCU8h1EslwQ9euFp0wjKUMj5u9ll8QqpNcXxsfUnaN9qc2rrm5FS5t5TFAkbIX5fOTJCPb+seE146ax/cNovzOoJUPvF+qBfvJLQGX2L/4JdPqDQ6FkLbvJy194/K5oWag8w4F9ftYIfd/SOgatPMiKuhOls2zYufm34UBbksc7qxDD1DG";
private static final int EXPIRED_USER_ID = 1;
private static final int VALID_USER_ID = 2;
private static final int EXPIRED_STASH_KEY_ID = 100;
private static final int VALID_STASH_KEY_ID = 200;
private static final int VALID_BYPASS_KEY_ID = 300;
private static final int DAYS_ALLOWED = 90;
private static final String AUTHED_GROUP = "the-monkeys";
// gets injected thanks to ActiveObjectsJUnitRunner.class
private EntityManager entityManager;
private ActiveObjects ao;
private EnterpriseKeyRepository keyRepo;
private EnterpriseSshKeyService ourKeyService;
private NotificationService notificationService;
private SshKeyService stashKeyService;
private SshKeyPairGenerator keyPairGenerator;
private UserService userService;
private PluginSettingsService pluginSettingsService;
private ApplicationUser unblessedUser ;
private ApplicationUser blessedUser;
private SshKey approvedUserKey = mock(SshKey.class);
private SshKey unapprovedUserKey = mock(SshKey.class);
private SshKey existingKeyForUnapprovedUser = mock(SshKey.class);
@Before
public void setup() {
//mock app users
userService = mock(UserService.class);
unblessedUser = mock(ApplicationUser.class);
when(unblessedUser.getId()).thenReturn(VALID_USER_ID);
when(userService.isUserInGroup(unblessedUser, AUTHED_GROUP)).thenReturn(false);
blessedUser = mock(ApplicationUser.class);
when(blessedUser.getId()).thenReturn(VALID_USER_ID);
when(userService.isUserInGroup(blessedUser, AUTHED_GROUP)).thenReturn(true);
// mock their keys and potential keys
when(approvedUserKey.getText()).thenReturn(APPROVED_PUBLIC_KEY_ONE);
when(approvedUserKey.getUser()).thenReturn(blessedUser);
when(unapprovedUserKey.getText()).thenReturn(UNAPPROVED_PUBLIC_KEY_ONE);
when(unapprovedUserKey.getUser()).thenReturn(unblessedUser);
when(existingKeyForUnapprovedUser.getText()).thenReturn(APPROVED_PUBLIC_KEY_ONE);
when(existingKeyForUnapprovedUser.getUser()).thenReturn(unblessedUser);
ao = new TestActiveObjects(entityManager);
keyRepo = new EnterpriseKeyRepositoryImpl(ao);
stashKeyService = mock(SshKeyService.class);
when(stashKeyService.addForUser(any(ApplicationUser.class),anyString())).thenReturn(approvedUserKey);
notificationService = mock(NotificationService.class);
keyPairGenerator = new JschSshKeyPairGenerator();
when(userService.existsGroup(anyString())).thenReturn(true);
pluginSettingsService = mock(PluginSettingsService.class);
when(pluginSettingsService.getMillisBetweenRuns()).thenReturn(60000L);
when(pluginSettingsService.getDaysAllowedForUserKeys()).thenReturn(DAYS_ALLOWED);
when(pluginSettingsService.getDaysAllowedForBambooKeys()).thenReturn(DAYS_ALLOWED);
when(pluginSettingsService.getAuthorizedGroup()).thenReturn(AUTHED_GROUP);
when(userService.getUserByName(KeyRotationJobRunner.ADMIN_ACCOUNT_NAME)).thenReturn(mock(ApplicationUser.class));//defeat NPE check
ourKeyService = new EnterpriseSshKeyServiceImpl(stashKeyService, keyRepo, keyPairGenerator, notificationService,userService, pluginSettingsService);
}
@Test
public void whenExpireTaskIsCalledValidKeysAreIgnored() {
SshKeyEntity validKey = ao.get(SshKeyEntity.class, EnterpriseSshKeyRepositoryTestData.validKey.getID());
assertThat(validKey, notNullValue());
assertThat(validKey.getKeyId(), is(VALID_STASH_KEY_ID));
ourKeyService.replaceExpiredKeysAndNotifyUsers();
// key survived?
validKey = ao.get(SshKeyEntity.class, EnterpriseSshKeyRepositoryTestData.validKey.getID());
assertThat(validKey, notNullValue());
// stash's ssh service was not invoked
verify(stashKeyService, times(0)).remove(VALID_STASH_KEY_ID);
}
@Test
@NonTransactional
public void whenExpireTaskIsCalledExpiredKeysAreDestroyed() {
SshKeyEntity validKey = ao.get(SshKeyEntity.class, EnterpriseSshKeyRepositoryTestData.expiredKey.getID());
assertThat(validKey, notNullValue());
assertThat(validKey.getKeyId(), is(EXPIRED_STASH_KEY_ID));
ourKeyService.replaceExpiredKeysAndNotifyUsers();
// key was purged?
validKey = ao.get(SshKeyEntity.class, EnterpriseSshKeyRepositoryTestData.expiredKey.getID());
assertThat(validKey, nullValue());
// stash ssh remve was called with ecxpired ssh key id
// stash's ssh service was not invoked
verify(stashKeyService).remove(EXPIRED_STASH_KEY_ID);
}
@Test
public void whenKeyIsExpiredTheAppropriateUserIsNotified() {
ourKeyService.replaceExpiredKeysAndNotifyUsers();
// stash's ssh service was not invoked
verify(notificationService).notifyUserOfExpiredKey(EXPIRED_USER_ID);
}
@Test
public void userInBlessedGroupMayByPassDirectService(){
boolean isAllowed = ourKeyService.isKeyValidForUser(approvedUserKey, blessedUser);
assertThat(isAllowed,is(true));
}
@Test
public void userNotInBlessedGroupAreNotAllowedDirect(){
boolean isAllowed = ourKeyService.isKeyValidForUser(unapprovedUserKey, unblessedUser);
assertThat(isAllowed,is(false));
}
@Test
// This test seems to rely on fact that the APPROVED_PUBLIC_KEY_ONE exists in DB wit TYPE BYPASS
// not sure what the use case is/was....
// I think it allows admins to create permanent keys on behalf od users. If key text exists in DB associated with that user its not purged...
public void userNotInBlessedGroupButUsedWrapperServiceAreAllowed(){
boolean isAllowed = ourKeyService.isKeyValidForUser(existingKeyForUnapprovedUser, unblessedUser);
assertThat(isAllowed,is(true));
}
@Test
@NonTransactional
public void generatingNewUserKeysIgnoresOtherTypes(){
//given a user with existing USER and BYPASS keys
// see EnterpriseSshKeyRepositoryTestData below and bypassKey
//when new USER key is created
ourKeyService.generateNewKeyPairFor(blessedUser);
//then previous BYPASS key remains
verify(stashKeyService,times(0)).removeAllForUser(blessedUser);
verify(stashKeyService, times(0)).remove(VALID_BYPASS_KEY_ID);
//but preivous USER key does not
verify(stashKeyService).remove(VALID_STASH_KEY_ID);
}
public static class EnterpriseSshKeyRepositoryTestData implements DatabaseUpdater {
private static SshKeyEntity expiredKey;
private static SshKeyEntity validKey;
@Override
public void update(EntityManager em) throws Exception {
em.migrate(SshKeyEntity.class);
// create a pre-expired key in DB for scheduler
DateTime now = new DateTime();
expiredKey = em.create(SshKeyEntity.class, new DBParam("USERID", EXPIRED_USER_ID), new DBParam("KEYID",
EXPIRED_STASH_KEY_ID), new DBParam("TEXT", APPROVED_PUBLIC_KEY_ONE), new DBParam("LABEL", "COMPROMISED"), new DBParam("TYPE", KeyType.USER),
new DBParam("CREATED", now.minusDays(DAYS_ALLOWED+1).toDate()));
validKey = em.create(SshKeyEntity.class, new DBParam("USERID", VALID_USER_ID), new DBParam("KEYID",
VALID_STASH_KEY_ID), new DBParam("TEXT", APPROVED_PUBLIC_KEY_ONE), new DBParam("LABEL", "VALID"), new DBParam("TYPE", KeyType.USER),
new DBParam("CREATED", now.minusDays(DAYS_ALLOWED-1).toDate()));
SshKeyEntity bypassKey = em.create(SshKeyEntity.class, new DBParam("USERID", VALID_USER_ID), new DBParam("KEYID",
VALID_BYPASS_KEY_ID), new DBParam("TEXT", APPROVED_PUBLIC_KEY_ONE), new DBParam("LABEL", "BYPASS"), new DBParam("TYPE", KeyType.BYPASS),
new DBParam("CREATED", now.minusDays(DAYS_ALLOWED-1).toDate()));
}
}
}
| issue #17 clarifying test names and intents
| src/test/java/ut/com/lmig/forge/stash/ssh/keys/EnterpriseSshKeyManagerImplTest.java | issue #17 clarifying test names and intents | |
Java | apache-2.0 | 1888c34eb7ba0c594a39a4b8725b0b111fd83718 | 0 | RuedigerMoeller/fast-serialization,RuedigerMoeller/fast-serialization,RuedigerMoeller/fast-serialization,RuedigerMoeller/fast-serialization | /*
* Copyright 2014 Ruediger Moeller.
*
* 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 org.nustaq.serialization;
import org.nustaq.serialization.coders.Unknown;
import org.nustaq.serialization.minbin.MBObject;
import org.nustaq.serialization.util.FSTUtil;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
/**
* Created with IntelliJ IDEA.
* User: Möller
* Date: 04.11.12
* Time: 11:53
*/
/**
* replacement of ObjectInputStream
*/
public class FSTObjectInput implements ObjectInput {
public static boolean REGISTER_ENUMS_READ = false; // do not register enums on read. Flag is saver in case things brake somewhere
public static ByteArrayInputStream emptyStream = new ByteArrayInputStream(new byte[0]);
protected FSTDecoder codec;
protected FSTObjectRegistry objects;
protected Stack<String> debugStack;
protected int curDepth;
protected ArrayList<CallbackEntry> callbacks;
// FSTConfiguration conf;
// mirrored from conf
protected boolean ignoreAnnotations;
protected FSTClazzInfoRegistry clInfoRegistry;
// done
protected ConditionalCallback conditionalCallback;
protected int readExternalReadAHead = 8000;
protected VersionConflictListener versionConflictListener;
protected FSTConfiguration conf;
// copied values from conf
protected boolean isCrossPlatform;
public FSTConfiguration getConf() {
return conf;
}
@Override
public void readFully(byte[] b) throws IOException {
readFully(b, 0, b.length);
}
@Override
public void readFully(byte[] b, int off, int len) throws IOException {
getCodec().readPlainBytes(b, off, len);
}
@Override
public int skipBytes(int n) throws IOException {
getCodec().skip(n);
return n;
}
@Override
public boolean readBoolean() throws IOException {
return getCodec().readFByte() == 0 ? false : true;
}
@Override
public byte readByte() throws IOException {
return getCodec().readFByte();
}
@Override
public int readUnsignedByte() throws IOException {
return ((int) getCodec().readFByte()+256) & 0xff;
}
@Override
public short readShort() throws IOException {
return getCodec().readFShort();
}
@Override
public int readUnsignedShort() throws IOException {
return ((int)readShort()+65536) & 0xffff;
}
@Override
public char readChar() throws IOException {
return getCodec().readFChar();
}
@Override
public int readInt() throws IOException {
return getCodec().readFInt();
}
@Override
public long readLong() throws IOException {
return getCodec().readFLong();
}
@Override
public float readFloat() throws IOException {
return getCodec().readFFloat();
}
@Override
public double readDouble() throws IOException {
return getCodec().readFDouble();
}
@Override
public String readLine() throws IOException {
throw new RuntimeException("not implemented");
}
@Override
public String readUTF() throws IOException {
return getCodec().readStringUTF();
}
public FSTDecoder getCodec() {
return codec;
}
protected void setCodec(FSTDecoder codec) {
this.codec = codec;
}
protected static class CallbackEntry {
ObjectInputValidation cb;
int prio;
CallbackEntry(ObjectInputValidation cb, int prio) {
this.cb = cb;
this.prio = prio;
}
}
public static interface ConditionalCallback {
public boolean shouldSkip(Object halfDecoded, int streamPosition, Field field);
}
public FSTObjectInput() throws IOException {
this(emptyStream, FSTConfiguration.getDefaultConfiguration());
}
public FSTObjectInput(FSTConfiguration conf) {
this(emptyStream, conf);
}
/**
* Creates a FSTObjectInput that uses the specified
* underlying InputStream.
*
* @param in the specified input stream
*/
public FSTObjectInput(InputStream in) throws IOException {
this(in, FSTConfiguration.getDefaultConfiguration());
}
/**
* Creates a FSTObjectInput that uses the specified
* underlying InputStream.
*
* Don't create a FSTConfiguration with each stream, just create one global static configuration and reuseit.
* FSTConfiguration is threadsafe.
*
* @param in the specified input stream
*/
public FSTObjectInput(InputStream in, FSTConfiguration conf) {
setCodec(conf.createStreamDecoder());
getCodec().setInputStream(in);
isCrossPlatform = conf.isCrossPlatform();
initRegistries(conf);
this.conf = conf;
}
public Class getClassForName(String name) throws ClassNotFoundException {
return getCodec().classForName(name);
}
protected void initRegistries(FSTConfiguration conf) {
ignoreAnnotations = conf.getCLInfoRegistry().isIgnoreAnnotations();
clInfoRegistry = conf.getCLInfoRegistry();
objects = (FSTObjectRegistry) conf.getCachedObject(FSTObjectRegistry.class);
if (objects == null) {
objects = new FSTObjectRegistry(conf);
} else {
objects.clearForRead(conf);
}
}
public ConditionalCallback getConditionalCallback() {
return conditionalCallback;
}
public void setConditionalCallback(ConditionalCallback conditionalCallback) {
this.conditionalCallback = conditionalCallback;
}
public int getReadExternalReadAHead() {
return readExternalReadAHead;
}
/**
* since the stock readXX methods on InputStream are final, i can't ensure sufficient readAhead on the inputStream
* before calling readExternal. Default value is 16000 bytes. If you make use of the externalizable interfac
* and write larger Objects a) cast the ObjectInput in readExternal to FSTObjectInput and call ensureReadAhead on this
* in your readExternal method b) set a sufficient maximum using this method before serializing.
* @param readExternalReadAHead
*/
public void setReadExternalReadAHead(int readExternalReadAHead) {
this.readExternalReadAHead = readExternalReadAHead;
}
@Override
public Object readObject() throws ClassNotFoundException, IOException {
try {
return readObject((Class[]) null);
} catch (Exception e) {
throw new IOException(e);
}
}
@Override
public int read() throws IOException {
return getCodec().readIntByte();
}
@Override
public int read(byte[] b) throws IOException {
getCodec().readPlainBytes(b, 0, b.length);
return b.length;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
getCodec().readPlainBytes(b, off, len);
return b.length;
}
@Override
public long skip(long n) throws IOException {
getCodec().skip((int) n);
return n;
}
@Override
public int available() throws IOException {
return getCodec().available();
}
protected void processValidation() throws InvalidObjectException {
if (callbacks == null) {
return;
}
Collections.sort(callbacks, new Comparator<CallbackEntry>() {
@Override
public int compare(CallbackEntry o1, CallbackEntry o2) {
return o2.prio - o1.prio;
}
});
for (int i = 0; i < callbacks.size(); i++) {
CallbackEntry callbackEntry = callbacks.get(i);
try {
callbackEntry.cb.validateObject();
} catch (Exception ex) {
FSTUtil.<RuntimeException>rethrow(ex);
}
}
}
public Object readObject(Class... possibles) throws Exception {
curDepth++;
if ( isCrossPlatform ) {
return readObjectInternal(null); // not supported cross platform
}
try {
if (possibles != null && possibles.length > 1 ) {
for (int i = 0; i < possibles.length; i++) {
Class possible = possibles[i];
getCodec().registerClass(possible);
}
}
Object res = readObjectInternal(possibles);
processValidation();
return res;
} catch (Throwable th) {
FSTUtil.<RuntimeException>rethrow(th);
} finally {
curDepth--;
}
return null;
}
protected FSTClazzInfo.FSTFieldInfo infoCache;
public Object readObjectInternal(Class... expected) throws ClassNotFoundException, IOException, IllegalAccessException, InstantiationException {
try {
FSTClazzInfo.FSTFieldInfo info = infoCache;
infoCache = null;
if (info == null )
info = new FSTClazzInfo.FSTFieldInfo(expected, null, ignoreAnnotations);
else
info.possibleClasses = expected;
Object res = readObjectWithHeader(info);
infoCache = info;
return res;
} catch (Throwable t) {
FSTUtil.<RuntimeException>rethrow(t);
}
return null;
}
public Object readObjectWithHeader(FSTClazzInfo.FSTFieldInfo referencee) throws Exception {
FSTClazzInfo clzSerInfo;
Class c;
final int readPos = getCodec().getInputPos();
byte code = getCodec().readObjectHeaderTag(); // NOTICE: THIS ADVANCES THE INPUT STREAM...
if (code == FSTObjectOutput.OBJECT ) {
// class name
clzSerInfo = readClass();
c = clzSerInfo.getClazz();
if ( c.isArray() )
return readArrayNoHeader(referencee,readPos,c);
// fall through
} else if ( code == FSTObjectOutput.TYPED ) {
c = referencee.getType();
clzSerInfo = getClazzInfo(c, referencee);
} else if ( code >= 1 ) {
try {
c = referencee.getPossibleClasses()[code - 1];
clzSerInfo = getClazzInfo(c, referencee);
} catch (Throwable th) {
clzSerInfo = null; c = null;
FSTUtil.<RuntimeException>rethrow(th);
}
} else {
Object res = instantiateSpecialTag(referencee, readPos, code);
return res;
}
try {
FSTObjectSerializer ser = clzSerInfo.getSer();
if (ser != null) {
Object res = instantiateAndReadWithSer(c, ser, clzSerInfo, referencee, readPos);
getCodec().readArrayEnd(clzSerInfo);
return res;
} else {
Object res = instantiateAndReadNoSer(c, clzSerInfo, referencee, readPos);
return res;
}
} catch (Exception e) {
FSTUtil.<RuntimeException>rethrow(e);
}
return null;
}
protected Object instantiateSpecialTag(FSTClazzInfo.FSTFieldInfo referencee, int readPos, byte code) throws Exception {
if ( code == FSTObjectOutput.STRING ) { // faster than switch, note: currently string tag not used by all codecs ..
String res = getCodec().readStringUTF();
objects.registerObjectForRead(res, readPos);
return res;
} else if ( code == FSTObjectOutput.BIG_INT ) {
return instantiateBigInt();
} else if ( code == FSTObjectOutput.NULL ) {
return null;
} else
{
switch (code) {
// case FSTObjectOutput.BIG_INT: { return instantiateBigInt(); }
case FSTObjectOutput.BIG_LONG: { return Long.valueOf(getCodec().readFLong()); }
case FSTObjectOutput.BIG_BOOLEAN_FALSE: { return Boolean.FALSE; }
case FSTObjectOutput.BIG_BOOLEAN_TRUE: { return Boolean.TRUE; }
case FSTObjectOutput.ONE_OF: { return referencee.getOneOf()[getCodec().readFByte()]; }
// case FSTObjectOutput.NULL: { return null; }
case FSTObjectOutput.DIRECT_ARRAY_OBJECT: {
Object directObject = getCodec().getDirectObject();
objects.registerObjectForRead(directObject,readPos);
return directObject;
}
case FSTObjectOutput.DIRECT_OBJECT: {
Object directObject = getCodec().getDirectObject();
if (directObject.getClass() == byte[].class) { // fixme. special for minibin, move it there
if ( referencee != null && referencee.getType() == boolean[].class )
{
byte[] ba = (byte[]) directObject;
boolean res[] = new boolean[ba.length];
for (int i = 0; i < res.length; i++) {
res[i] = ba[i] != 0;
}
directObject = res;
}
}
objects.registerObjectForRead(directObject,readPos);
return directObject;
}
// case FSTObjectOutput.STRING: return getCodec().readStringUTF();
case FSTObjectOutput.HANDLE: {
Object res = instantiateHandle(referencee);
getCodec().readObjectEnd();
return res;
}
case FSTObjectOutput.ARRAY: {
Object res = instantiateArray(referencee, readPos);
return res;
}
case FSTObjectOutput.ENUM: { return instantiateEnum(referencee, readPos); }
}
throw new RuntimeException("unknown object tag "+code);
}
}
protected FSTClazzInfo getClazzInfo(Class c, FSTClazzInfo.FSTFieldInfo referencee) {
FSTClazzInfo clzSerInfo;
FSTClazzInfo lastInfo = referencee.lastInfo;
if ( lastInfo != null && lastInfo.clazz == c && lastInfo.conf == conf) {
clzSerInfo = lastInfo;
} else {
clzSerInfo = clInfoRegistry.getCLInfo(c, conf);
referencee.lastInfo = clzSerInfo;
}
return clzSerInfo;
}
protected Object instantiateHandle(FSTClazzInfo.FSTFieldInfo referencee) throws IOException {
int handle = getCodec().readFInt();
Object res = objects.getReadRegisteredObject(handle);
if (res == null) {
throw new IOException("unable to ressolve handle " + handle + " " + referencee.getDesc() + " " + getCodec().getInputPos() );
}
return res;
}
protected Object instantiateArray(FSTClazzInfo.FSTFieldInfo referencee, int readPos) throws Exception {
Object res = readArray(referencee, readPos); // NEED TO PASS ALONG THE POS FOR THE ARRAY
/*
registerObjectForRead alerady gets called by readArray (and with the proper pos now). that said, I'm unclear
on the intent of the if ( ! referencee.isFlat() ) so I wanted to comment on that
if ( ! referencee.isFlat() ) {
objects.registerObjectForRead(res, readPos);
}
*/
return res;
}
protected Object instantiateEnum(FSTClazzInfo.FSTFieldInfo referencee, int readPos) throws IOException, ClassNotFoundException {
FSTClazzInfo clzSerInfo;
Class c;
clzSerInfo = readClass();
c = clzSerInfo.getClazz();
int ordinal = getCodec().readFInt();
Object[] enumConstants = clzSerInfo.getEnumConstants();
if ( enumConstants == null ) {
// pseudo enum of anonymous classes tom style ?
return null;
}
Object res = enumConstants[ordinal];
if ( REGISTER_ENUMS_READ ) {
if ( ! referencee.isFlat() ) { // should be unnecessary
objects.registerObjectForRead(res, readPos);
}
}
return res;
}
protected Object instantiateBigInt() throws IOException {
int val = getCodec().readFInt();
return Integer.valueOf(val);
}
protected Object instantiateAndReadWithSer(Class c, FSTObjectSerializer ser, FSTClazzInfo clzSerInfo, FSTClazzInfo.FSTFieldInfo referencee, int readPos) throws Exception {
boolean serInstance = false;
Object newObj = ser.instantiate(c, this, clzSerInfo, referencee, readPos);
if (newObj == null) {
newObj = clzSerInfo.newInstance(getCodec().isMapBased());
} else
serInstance = true;
if (newObj == null) {
throw new IOException(referencee.getDesc() + ":Failed to instantiate '" + c.getName() + "'. Register a custom serializer implementing instantiate or define empty constructor..");
}
if ( newObj == FSTObjectSerializer.REALLY_NULL ) {
newObj = null;
} else {
if (newObj.getClass() != c && ser == null ) {
// for advanced trickery (e.g. returning non-serializable from FSTSerializer)
// this hurts. so in case of FSTSerializers incoming clzInfo will refer to the
// original class, not the one actually instantiated
c = newObj.getClass();
clzSerInfo = clInfoRegistry.getCLInfo(c, conf);
}
if ( ! referencee.isFlat() && ! clzSerInfo.isFlat() && !ser.alwaysCopy()) {
objects.registerObjectForRead(newObj, readPos);
}
if ( !serInstance )
ser.readObject(this, newObj, clzSerInfo, referencee);
}
getCodec().consumeEndMarker(); //=> bug when writing objects unlimited
return newObj;
}
protected Object instantiateAndReadNoSer(Class c, FSTClazzInfo clzSerInfo, FSTClazzInfo.FSTFieldInfo referencee, int readPos) throws Exception {
Object newObj;
newObj = clzSerInfo.newInstance(getCodec().isMapBased());
if (newObj == null) {
throw new IOException(referencee.getDesc() + ":Failed to instantiate '" + c.getName() + "'. Register a custom serializer implementing instantiate or define empty constructor.");
}
//fixme: code below improves unshared decoding perf, however disables to run mixed mode (clients can decide)
//actually would need 2 flags for encode/decode
//tested with json mixed mode does not work anyway ...
final boolean needsRefLookup = conf.shareReferences && !referencee.isFlat() && !clzSerInfo.isFlat();
// previously :
// final boolean needsRefLookup = !referencee.isFlat() && !clzSerInfo.isFlat();
if (needsRefLookup) {
objects.registerObjectForRead(newObj, readPos);
}
if ( clzSerInfo.isExternalizable() )
{
int tmp = readPos;
getCodec().ensureReadAhead(readExternalReadAHead);
((Externalizable)newObj).readExternal(this);
getCodec().readExternalEnd();
if ( clzSerInfo.getReadResolveMethod() != null ) {
final Object prevNew = newObj;
newObj = handleReadRessolve(clzSerInfo, newObj);
if ( newObj != prevNew && needsRefLookup ) {
objects.replace(prevNew, newObj, tmp);
}
}
} else if (clzSerInfo.useCompatibleMode())
{
Object replaced = readObjectCompatible(referencee, clzSerInfo, newObj);
if (replaced != null && replaced != newObj) {
objects.replace(newObj, replaced, readPos);
newObj = replaced;
}
} else {
FSTClazzInfo.FSTFieldInfo[] fieldInfo = clzSerInfo.getFieldInfo();
readObjectFields(referencee, clzSerInfo, fieldInfo, newObj,0,0);
}
return newObj;
}
protected Object readObjectCompatible(FSTClazzInfo.FSTFieldInfo referencee, FSTClazzInfo serializationInfo, Object newObj) throws Exception {
Class cl = serializationInfo.getClazz();
readObjectCompatibleRecursive(referencee, newObj, serializationInfo, cl);
if (newObj != null &&
serializationInfo.getReadResolveMethod() != null) {
newObj = handleReadRessolve(serializationInfo, newObj);
}
return newObj;
}
protected Object handleReadRessolve(FSTClazzInfo serializationInfo, Object newObj) throws IllegalAccessException {
Object rep = null;
try {
rep = serializationInfo.getReadResolveMethod().invoke(newObj);
} catch (InvocationTargetException e) {
FSTUtil.<RuntimeException>rethrow(e);
}
newObj = rep;//FIXME: support this in call
return newObj;
}
protected void readObjectCompatibleRecursive(FSTClazzInfo.FSTFieldInfo referencee, Object toRead, FSTClazzInfo serializationInfo, Class cl) throws Exception {
FSTClazzInfo.FSTCompatibilityInfo fstCompatibilityInfo = serializationInfo.getCompInfo().get(cl);
if (!Serializable.class.isAssignableFrom(cl)) {
return; // ok here, as compatible mode will never be triggered for "forceSerializable"
}
readObjectCompatibleRecursive(referencee, toRead, serializationInfo, cl.getSuperclass());
if (fstCompatibilityInfo != null && fstCompatibilityInfo.getReadMethod() != null) {
try {
int tag = readByte(); // expect 55
if ( tag == 66 ) {
// no write method defined, but read method defined ...
// expect defaultReadObject
getCodec().moveTo(getCodec().getInputPos() - 1); // need to push back tag, cause defaultWriteObject on writer side does not write tag
// input.pos--;
}
ObjectInputStream objectInputStream = getObjectInputStream(cl, serializationInfo, referencee, toRead);
fstCompatibilityInfo.getReadMethod().invoke(toRead, objectInputStream);
fakeWrapper.pop();
} catch (Exception e) {
FSTUtil.<RuntimeException>rethrow(e);
}
} else {
if (fstCompatibilityInfo != null) {
int tag = readByte();
if ( tag == 55 )
{
// came from writeMethod, but no readMethod defined => assume defaultWriteObject
tag = readByte(); // consume tag of defaultwriteobject (99)
if ( tag == 77 ) // came from putfield
{
HashMap<String, Object> fieldMap = (HashMap<String, Object>) FSTObjectInput.this.readObjectInternal(HashMap.class);
final FSTClazzInfo.FSTFieldInfo[] fieldArray = fstCompatibilityInfo.getFieldArray();
for (int i = 0; i < fieldArray.length; i++) {
FSTClazzInfo.FSTFieldInfo fstFieldInfo = fieldArray[i];
final Object val = fieldMap.get(fstFieldInfo.getName());
if ( val != null ) {
fstFieldInfo.setObjectValue(toRead,val);
}
}
return;
}
}
readObjectFields(referencee, serializationInfo, fstCompatibilityInfo.getFieldArray(), toRead,0,0);
}
}
}
public void defaultReadObject(FSTClazzInfo.FSTFieldInfo referencee, FSTClazzInfo serializationInfo, Object newObj)
{
try {
readObjectFields(referencee,serializationInfo,serializationInfo.getFieldInfo(),newObj,0,-1); // -1 flag to indicate no object end should be called
} catch (Exception e) {
FSTUtil.<RuntimeException>rethrow(e);
}
}
protected void readObjectFields(FSTClazzInfo.FSTFieldInfo referencee, FSTClazzInfo serializationInfo, FSTClazzInfo.FSTFieldInfo[] fieldInfo, Object newObj, int startIndex, int version) throws Exception {
if ( getCodec().isMapBased() ) {
readFieldsMapBased(referencee, serializationInfo, newObj);
if ( version >= 0 && newObj instanceof Unknown == false)
getCodec().readObjectEnd();
return;
}
if ( version < 0 )
version = 0;
int booleanMask = 0;
int boolcount = 8;
final int length = fieldInfo.length;
int conditional = 0;
for (int i = startIndex; i < length; i++) {
try {
FSTClazzInfo.FSTFieldInfo subInfo = fieldInfo[i];
if (subInfo.getVersion() > version ) {
int nextVersion = getCodec().readVersionTag();
if ( nextVersion == 0 ) // old object read
{
oldVersionRead(newObj);
return;
}
if ( nextVersion != subInfo.getVersion() ) {
throw new RuntimeException("read version tag "+nextVersion+" fieldInfo has "+subInfo.getVersion());
}
readObjectFields(referencee,serializationInfo,fieldInfo,newObj,i,nextVersion);
return;
}
if (subInfo.isPrimitive()) {
int integralType = subInfo.getIntegralType();
if (integralType == FSTClazzInfo.FSTFieldInfo.BOOL) {
if (boolcount == 8) {
booleanMask = ((int) getCodec().readFByte() + 256) &0xff;
boolcount = 0;
}
boolean val = (booleanMask & 128) != 0;
booleanMask = booleanMask << 1;
boolcount++;
subInfo.setBooleanValue(newObj, val);
} else {
switch (integralType) {
case FSTClazzInfo.FSTFieldInfo.BYTE: subInfo.setByteValue(newObj, getCodec().readFByte()); break;
case FSTClazzInfo.FSTFieldInfo.CHAR: subInfo.setCharValue(newObj, getCodec().readFChar()); break;
case FSTClazzInfo.FSTFieldInfo.SHORT: subInfo.setShortValue(newObj, getCodec().readFShort()); break;
case FSTClazzInfo.FSTFieldInfo.INT: subInfo.setIntValue(newObj, getCodec().readFInt()); break;
case FSTClazzInfo.FSTFieldInfo.LONG: subInfo.setLongValue(newObj, getCodec().readFLong()); break;
case FSTClazzInfo.FSTFieldInfo.FLOAT: subInfo.setFloatValue(newObj, getCodec().readFFloat()); break;
case FSTClazzInfo.FSTFieldInfo.DOUBLE: subInfo.setDoubleValue(newObj, getCodec().readFDouble()); break;
}
}
} else {
if ( subInfo.isConditional() ) {
if ( conditional == 0 ) {
conditional = getCodec().readPlainInt();
if ( skipConditional(newObj, conditional, subInfo) ) {
getCodec().moveTo(conditional);
continue;
}
}
}
// object
Object subObject = readObjectWithHeader(subInfo);
subInfo.setObjectValue(newObj, subObject);
}
} catch (IllegalAccessException ex) {
throw new IOException(ex);
}
}
int debug = getCodec().readVersionTag();// just consume '0'
}
public VersionConflictListener getVersionConflictListener() {
return versionConflictListener;
}
/**
* see @Version annotation
* @param versionConflictListener
*/
public void setVersionConflictListener(VersionConflictListener versionConflictListener) {
this.versionConflictListener = versionConflictListener;
}
protected void oldVersionRead(Object newObj) {
if ( versionConflictListener != null )
versionConflictListener.onOldVersionRead(newObj);
}
protected void readFieldsMapBased(FSTClazzInfo.FSTFieldInfo referencee, FSTClazzInfo serializationInfo, Object newObj) throws Exception {
String name;
int len = getCodec().getObjectHeaderLen(); // check if len is known in advance
if ( len < 0 )
len = Integer.MAX_VALUE;
int count = 0;
boolean isUnknown = newObj.getClass() == Unknown.class; // json
boolean inArray = isUnknown && getCodec().inArray(); // json externalized/custom serialized
getCodec().startFieldReading(newObj);
// fixme: break up this loop into separate impls.
while( count < len ) {
if ( inArray ) {
// unknwon json object written by externalize or custom serializer
Object o = readObjectWithHeader(null);
if ( o != null && getCodec().isEndMarker(o.toString()) )
return;
((Unknown)newObj).add(o);
continue;
}
name= getCodec().readStringUTF();
//int debug = getCodec().getInputPos();
if ( len == Integer.MAX_VALUE && getCodec().isEndMarker(name) )
return;
count++;
if (isUnknown) {
FSTClazzInfo.FSTFieldInfo fakeField = new FSTClazzInfo.FSTFieldInfo(null, null, true);
fakeField.fakeName = name;
Object toSet = readObjectWithHeader(fakeField);
((Unknown)newObj).set(name, toSet);
} else
if ( newObj.getClass() == MBObject.class ) {
Object toSet = readObjectWithHeader(null);
((MBObject)newObj).put(name,toSet);
} else {
FSTClazzInfo.FSTFieldInfo fieldInfo = serializationInfo.getFieldInfo(name, null);
if (fieldInfo == null) {
System.out.println("warning: unknown field: " + name + " on class " + serializationInfo.getClazz().getName());
} else {
if (fieldInfo.isPrimitive()) {
// direct primitive field
switch (fieldInfo.getIntegralType()) {
case FSTClazzInfo.FSTFieldInfo.BOOL:
fieldInfo.setBooleanValue(newObj, getCodec().readFByte() == 0 ? false : true);
break;
case FSTClazzInfo.FSTFieldInfo.BYTE:
fieldInfo.setByteValue(newObj, getCodec().readFByte());
break;
case FSTClazzInfo.FSTFieldInfo.CHAR:
fieldInfo.setCharValue(newObj, getCodec().readFChar());
break;
case FSTClazzInfo.FSTFieldInfo.SHORT:
fieldInfo.setShortValue(newObj, getCodec().readFShort());
break;
case FSTClazzInfo.FSTFieldInfo.INT:
fieldInfo.setIntValue(newObj, getCodec().readFInt());
break;
case FSTClazzInfo.FSTFieldInfo.LONG:
fieldInfo.setLongValue(newObj, getCodec().readFLong());
break;
case FSTClazzInfo.FSTFieldInfo.FLOAT:
fieldInfo.setFloatValue(newObj, getCodec().readFFloat());
break;
case FSTClazzInfo.FSTFieldInfo.DOUBLE:
fieldInfo.setDoubleValue(newObj, getCodec().readFDouble());
break;
default:
throw new RuntimeException("unkown primitive type " + fieldInfo);
}
} else {
Object toSet = readObjectWithHeader(fieldInfo);
toSet = getCodec().coerceElement(fieldInfo.getType(), toSet);
fieldInfo.setObjectValue(newObj, toSet);
}
}
}
}
}
protected boolean skipConditional(Object newObj, int conditional, FSTClazzInfo.FSTFieldInfo subInfo) {
if ( conditionalCallback != null ) {
return conditionalCallback.shouldSkip(newObj,conditional,subInfo.getField());
}
return false;
}
protected void readCompatibleObjectFields(FSTClazzInfo.FSTFieldInfo referencee, FSTClazzInfo serializationInfo, FSTClazzInfo.FSTFieldInfo[] fieldInfo, Map res) throws Exception {
int booleanMask = 0;
int boolcount = 8;
for (int i = 0; i < fieldInfo.length; i++) {
try {
FSTClazzInfo.FSTFieldInfo subInfo = fieldInfo[i];
if (subInfo.isIntegral() && !subInfo.isArray()) {
final Class subInfoType = subInfo.getType();
if (subInfoType == boolean.class) {
if (boolcount == 8) {
booleanMask = ((int) getCodec().readFByte() + 256) &0xff;
boolcount = 0;
}
boolean val = (booleanMask & 128) != 0;
booleanMask = booleanMask << 1;
boolcount++;
res.put(subInfo.getName(), val);
}
if (subInfoType == byte.class) {
res.put(subInfo.getName(), getCodec().readFByte());
} else if (subInfoType == char.class) {
res.put(subInfo.getName(), getCodec().readFChar());
} else if (subInfoType == short.class) {
res.put(subInfo.getName(), getCodec().readFShort());
} else if (subInfoType == int.class) {
res.put(subInfo.getName(), getCodec().readFInt());
} else if (subInfoType == double.class) {
res.put(subInfo.getName(), getCodec().readFDouble());
} else if (subInfoType == float.class) {
res.put(subInfo.getName(), getCodec().readFFloat());
} else if (subInfoType == long.class) {
res.put(subInfo.getName(), getCodec().readFLong());
}
} else {
// object
Object subObject = readObjectWithHeader(subInfo);
res.put(subInfo.getName(), subObject);
}
} catch (IllegalAccessException ex) {
throw new IOException(ex);
}
}
}
public String readStringUTF() throws IOException {
return getCodec().readStringUTF();
}
/**
* len < 127 !!!!!
* @return
* @throws IOException
*/
public String readStringAsc() throws IOException {
return getCodec().readStringAsc();
}
protected Object readArray(FSTClazzInfo.FSTFieldInfo referencee, int pos) throws Exception {
Object classOrArray = getCodec().readArrayHeader();
if ( classOrArray instanceof Class == false )
return classOrArray;
if ( classOrArray == null )
return null;
Object o = readArrayNoHeader(referencee, pos, (Class) classOrArray);
getCodec().readArrayEnd(null);
return o;
}
protected Object readArrayNoHeader(FSTClazzInfo.FSTFieldInfo referencee, int pos, Class arrCl) throws Exception {
final int len = getCodec().readFInt();
if (len == -1) {
return null;
}
Class arrType = arrCl.getComponentType();
if (!arrCl.getComponentType().isArray()) {
Object array = Array.newInstance(arrType, len);
if ( ! referencee.isFlat() )
objects.registerObjectForRead(array, pos );
if (arrCl.getComponentType().isPrimitive()) {
return getCodec().readFPrimitiveArray(array, arrType, len);
} else { // Object Array
Object arr[] = (Object[]) array;
for (int i = 0; i < len; i++) {
Object value = readObjectWithHeader(referencee);
value = getCodec().coerceElement(arrType, value);
arr[i] = value;
}
getCodec().readObjectEnd();
}
return array;
} else { // multidim array
Object array[] = (Object[]) Array.newInstance(arrType, len);
if ( ! referencee.isFlat() ) {
objects.registerObjectForRead(array, pos);
}
FSTClazzInfo.FSTFieldInfo ref1 = new FSTClazzInfo.FSTFieldInfo(referencee.getPossibleClasses(), null, clInfoRegistry.isIgnoreAnnotations());
for (int i = 0; i < len; i++) {
Object subArray = readArray(ref1, pos); // PLEASE REVIEW / BE SURE THIS CASE IS PASSING THE RIGHT POS FOR THE ARRAY, MY USE CASES DIDN'T HIT THIS LINE/CASE
array[i] = subArray;
}
return array;
}
}
public void registerObject(Object o, int streamPosition, FSTClazzInfo info, FSTClazzInfo.FSTFieldInfo referencee) {
if ( ! objects.disabled && !referencee.isFlat() && (info == null || ! info.isFlat() ) ) {
objects.registerObjectForRead(o, streamPosition);
}
}
public FSTClazzInfo readClass() throws IOException, ClassNotFoundException {
return getCodec().readClass();
}
protected void resetAndClearRefs() {
try {
reset();
objects.clearForRead(conf);
} catch (IOException e) {
FSTUtil.<RuntimeException>rethrow(e);
}
}
public void reset() throws IOException {
getCodec().reset();
}
public void resetForReuse(InputStream in) throws IOException {
if ( closed ) {
throw new RuntimeException("can't reuse closed stream");
}
getCodec().reset();
getCodec().setInputStream(in);
objects.clearForRead(conf);
}
public void resetForReuseCopyArray(byte bytes[], int off, int len) throws IOException {
if ( closed ) {
throw new RuntimeException("can't reuse closed stream");
}
getCodec().reset();
objects.clearForRead(conf);
getCodec().resetToCopyOf(bytes, off, len);
}
public void resetForReuseUseArray(byte bytes[]) throws IOException {
resetForReuseUseArray(bytes, bytes.length);
}
public void resetForReuseUseArray(byte bytes[], int len) throws IOException {
if ( closed ) {
throw new RuntimeException("can't reuse closed stream");
}
objects.clearForRead(conf);
getCodec().resetWith(bytes, len);
}
public final int readFInt() throws IOException {
return getCodec().readFInt();
}
protected boolean closed = false;
@Override
public void close() throws IOException {
closed = true;
resetAndClearRefs();
conf.returnObject(objects);
getCodec().close();
}
////////////////////////////////////////////////////// epic compatibility hack /////////////////////////////////////////////////////////
protected MyObjectStream fakeWrapper; // some jdk classes hash for ObjectStream, so provide the same instance always
protected ObjectInputStream getObjectInputStream(final Class cl, final FSTClazzInfo clInfo, final FSTClazzInfo.FSTFieldInfo referencee, final Object toRead) throws IOException {
ObjectInputStream wrapped = new ObjectInputStream() {
@Override
public Object readObjectOverride() throws IOException, ClassNotFoundException {
try {
byte b = FSTObjectInput.this.readByte();
if ( b != FSTObjectOutput.SPECIAL_COMPATIBILITY_OBJECT_TAG ) {
Constructor<?>[] constructors = OptionalDataException.class.getDeclaredConstructors();
FSTObjectInput.this.pushBack(1);
for (int i = 0; i < constructors.length; i++) {
Constructor constructor = constructors[i];
Class[] typeParameters = constructor.getParameterTypes();
if ( typeParameters != null && typeParameters.length == 1 && typeParameters[0] == int.class) {
constructor.setAccessible(true);
OptionalDataException ode;
try {
ode = (OptionalDataException) constructor.newInstance(0);
throw ode;
} catch (InvocationTargetException e) {
break;
}
}
}
throw new EOFException("if your code relies on this, think");
}
return FSTObjectInput.this.readObjectInternal(referencee.getPossibleClasses());
} catch (IllegalAccessException e) {
throw new IOException(e);
} catch (InstantiationException e) {
throw new IOException(e);
}
}
@Override
public Object readUnshared() throws IOException, ClassNotFoundException {
try {
return FSTObjectInput.this.readObjectInternal(referencee.getPossibleClasses()); // fixme
} catch (IllegalAccessException e) {
throw new IOException(e);
} catch (InstantiationException e) {
throw new IOException(e);
}
}
@Override
public void defaultReadObject() throws IOException, ClassNotFoundException {
try {
int tag = readByte();
if ( tag == 77 ) // came from writeFields
{
fieldMap = (HashMap<String, Object>) FSTObjectInput.this.readObjectInternal(HashMap.class);
// object has been written with writeFields, is no read with defaultReadObjects,
// need to autoapply map to object vars.
// this might be redundant in case readObject() pulls a getFields() .. (see bitset testcase)
for (Iterator<String> iterator = fieldMap.keySet().iterator(); iterator.hasNext(); ) {
String key = iterator.next();
FSTClazzInfo.FSTFieldInfo fieldInfo = clInfo.getFieldInfo(key, null);// in case fieldName is not unique => cannot recover/fix
if ( fieldInfo != null ) {
fieldInfo.setObjectValue(toRead,fieldMap.get(key));
}
}
} else {
FSTObjectInput.this.readObjectFields(
referencee,
clInfo,
clInfo.getCompInfo().get(cl).getFieldArray(),
toRead,
0,
0
); // FIXME: only fields of current class
}
} catch (Exception e) {
throw new IOException(e);
}
}
HashMap<String, Object> fieldMap;
@Override
public GetField readFields() throws IOException, ClassNotFoundException {
int tag = readByte();
try {
FSTClazzInfo.FSTCompatibilityInfo fstCompatibilityInfo = clInfo.getCompInfo().get(cl);
if (tag==99) { // came from defaultwriteobject
// Note: in case number and names of instance fields of reader/writer are different,
// this fails as code below implicitely assumes, fields of writer == fields of reader
// unfortunately one can use defaultWriteObject at writer side but use getFields at reader side
// in readObject(). if then fields differ, code below reads BS and fails.
// Its impossible to fix that except by always using putField + getField for
// JDK compatibility classes, however this will waste lots of performance. As
// it would be necessary to *always* write full metainformation (a map of fieldName => value pairs)
// see #53
fieldMap = new HashMap<String, Object>();
FSTObjectInput.this.readCompatibleObjectFields(referencee, clInfo, fstCompatibilityInfo.getFieldArray(), fieldMap);
getCodec().readVersionTag(); // consume dummy version tag as created by defaultWriteObject
} else if (tag == 66) { // has been written from writeObjectCompatible without writeMethod
fieldMap = new HashMap<String, Object>();
FSTObjectInput.this.readCompatibleObjectFields(referencee, clInfo, fstCompatibilityInfo.getFieldArray(), fieldMap);
getCodec().readVersionTag(); // consume dummy version tag as created by defaultWriteObject
} else {
fieldMap = (HashMap<String, Object>) FSTObjectInput.this.readObjectInternal(HashMap.class);
}
} catch (Exception e) {
FSTUtil.<RuntimeException>rethrow(e);
}
return new GetField() {
@Override
public ObjectStreamClass getObjectStreamClass() {
return ObjectStreamClass.lookup(cl);
}
@Override
public boolean defaulted(String name) throws IOException {
return fieldMap.get(name) == null;
}
@Override
public boolean get(String name, boolean val) throws IOException {
if (fieldMap.get(name) == null) {
return val;
}
return ((Boolean) fieldMap.get(name)).booleanValue();
}
@Override
public byte get(String name, byte val) throws IOException {
if (fieldMap.get(name) == null) {
return val;
}
return ((Byte) fieldMap.get(name)).byteValue();
}
@Override
public char get(String name, char val) throws IOException {
if (fieldMap.get(name) == null) {
return val;
}
return ((Character) fieldMap.get(name)).charValue();
}
@Override
public short get(String name, short val) throws IOException {
if (fieldMap.get(name) == null) {
return val;
}
return ((Short) fieldMap.get(name)).shortValue();
}
@Override
public int get(String name, int val) throws IOException {
if (fieldMap.get(name) == null) {
return val;
}
return ((Integer) fieldMap.get(name)).intValue();
}
@Override
public long get(String name, long val) throws IOException {
if (fieldMap.get(name) == null) {
return val;
}
return ((Long) fieldMap.get(name)).longValue();
}
@Override
public float get(String name, float val) throws IOException {
if (fieldMap.get(name) == null) {
return val;
}
return ((Float) fieldMap.get(name)).floatValue();
}
@Override
public double get(String name, double val) throws IOException {
if (fieldMap.get(name) == null) {
return val;
}
return ((Double) fieldMap.get(name)).doubleValue();
}
@Override
public Object get(String name, Object val) throws IOException {
Object res = fieldMap.get(name);
if (res == null) {
return val;
}
return res;
}
};
}
@Override
public void registerValidation(ObjectInputValidation obj, int prio) throws NotActiveException, InvalidObjectException {
if (callbacks == null) {
callbacks = new ArrayList<CallbackEntry>();
}
callbacks.add(new CallbackEntry(obj, prio));
}
@Override
public int read() throws IOException {
return getCodec().readFByte();
}
@Override
public int read(byte[] buf, int off, int len) throws IOException {
return FSTObjectInput.this.read(buf, off, len);
}
@Override
public int available() throws IOException {
return FSTObjectInput.this.available();
}
@Override
public void close() throws IOException {
}
@Override
public boolean readBoolean() throws IOException {
return FSTObjectInput.this.readBoolean();
}
@Override
public byte readByte() throws IOException {
return getCodec().readFByte();
}
@Override
public int readUnsignedByte() throws IOException {
return FSTObjectInput.this.readUnsignedByte();
}
@Override
public char readChar() throws IOException {
return getCodec().readFChar();
}
@Override
public short readShort() throws IOException {
return getCodec().readFShort();
}
@Override
public int readUnsignedShort() throws IOException {
return FSTObjectInput.this.readUnsignedShort();
}
@Override
public int readInt() throws IOException {
return getCodec().readFInt();
}
@Override
public long readLong() throws IOException {
return getCodec().readFLong();
}
@Override
public float readFloat() throws IOException {
return getCodec().readFFloat();
}
@Override
public double readDouble() throws IOException {
return getCodec().readFDouble();
}
@Override
public void readFully(byte[] buf) throws IOException {
FSTObjectInput.this.readFully(buf);
}
@Override
public void readFully(byte[] buf, int off, int len) throws IOException {
FSTObjectInput.this.readFully(buf, off, len);
}
@Override
public int skipBytes(int len) throws IOException {
return FSTObjectInput.this.skipBytes(len);
}
@Override
public String readUTF() throws IOException {
return getCodec().readStringUTF();
}
@Override
public String readLine() throws IOException {
return FSTObjectInput.this.readLine();
}
@Override
public int read(byte[] b) throws IOException {
return FSTObjectInput.this.read(b);
}
@Override
public long skip(long n) throws IOException {
return FSTObjectInput.this.skip(n);
}
@Override
public void mark(int readlimit) {
throw new RuntimeException("not implemented");
}
@Override
public void reset() throws IOException {
FSTObjectInput.this.reset();
}
@Override
public boolean markSupported() {
return false;
}
};
if ( fakeWrapper == null ) {
fakeWrapper = new MyObjectStream();
}
fakeWrapper.push(wrapped);
return fakeWrapper;
}
protected void pushBack(int i) {
getCodec().pushBack(i);
}
protected static class MyObjectStream extends ObjectInputStream {
ObjectInputStream wrapped;
ArrayDeque<ObjectInputStream> wrappedStack = new ArrayDeque<ObjectInputStream>();
public void push( ObjectInputStream in ) {
wrappedStack.push(in);
wrapped = in;
}
public void pop() {
wrapped = wrappedStack.pop();
}
MyObjectStream() throws IOException, SecurityException {
}
@Override
public Object readObjectOverride() throws IOException, ClassNotFoundException {
return wrapped.readObject();
}
@Override
public Object readUnshared() throws IOException, ClassNotFoundException {
return wrapped.readUnshared();
}
@Override
public void defaultReadObject() throws IOException, ClassNotFoundException {
wrapped.defaultReadObject();
}
@Override
public ObjectInputStream.GetField readFields() throws IOException, ClassNotFoundException {
return wrapped.readFields();
}
@Override
public void registerValidation(ObjectInputValidation obj, int prio) throws NotActiveException, InvalidObjectException {
wrapped.registerValidation(obj,prio);
}
@Override
public int read() throws IOException {
return wrapped.read();
}
@Override
public int read(byte[] buf, int off, int len) throws IOException {
return wrapped.read(buf, off, len);
}
@Override
public int available() throws IOException {
return wrapped.available();
}
@Override
public void close() throws IOException {
wrapped.close();
}
@Override
public boolean readBoolean() throws IOException {
return wrapped.readBoolean();
}
@Override
public byte readByte() throws IOException {
return wrapped.readByte();
}
@Override
public int readUnsignedByte() throws IOException {
return wrapped.readUnsignedByte();
}
@Override
public char readChar() throws IOException {
return wrapped.readChar();
}
@Override
public short readShort() throws IOException {
return wrapped.readShort();
}
@Override
public int readUnsignedShort() throws IOException {
return wrapped.readUnsignedShort();
}
@Override
public int readInt() throws IOException {
return wrapped.readInt();
}
@Override
public long readLong() throws IOException {
return wrapped.readLong();
}
@Override
public float readFloat() throws IOException {
return wrapped.readFloat();
}
@Override
public double readDouble() throws IOException {
return wrapped.readDouble();
}
@Override
public void readFully(byte[] buf) throws IOException {
wrapped.readFully(buf);
}
@Override
public void readFully(byte[] buf, int off, int len) throws IOException {
wrapped.readFully(buf, off, len);
}
@Override
public int skipBytes(int len) throws IOException {
return wrapped.skipBytes(len);
}
@Override
public String readUTF() throws IOException {
return wrapped.readUTF();
}
@Override
public String readLine() throws IOException {
return wrapped.readLine();
}
@Override
public int read(byte[] b) throws IOException {
return wrapped.read(b);
}
@Override
public long skip(long n) throws IOException {
return wrapped.skip(n);
}
@Override
public void mark(int readlimit) {
wrapped.mark(readlimit);
}
@Override
public void reset() throws IOException {
wrapped.reset();
}
@Override
public boolean markSupported() {
return wrapped.markSupported();
}
}
}
| src/main/java/org/nustaq/serialization/FSTObjectInput.java | /*
* Copyright 2014 Ruediger Moeller.
*
* 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 org.nustaq.serialization;
import org.nustaq.serialization.coders.Unknown;
import org.nustaq.serialization.minbin.MBObject;
import org.nustaq.serialization.util.FSTUtil;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
/**
* Created with IntelliJ IDEA.
* User: Möller
* Date: 04.11.12
* Time: 11:53
*/
/**
* replacement of ObjectInputStream
*/
public class FSTObjectInput implements ObjectInput {
public static boolean REGISTER_ENUMS_READ = false; // do not register enums on read. Flag is saver in case things brake somewhere
public static ByteArrayInputStream emptyStream = new ByteArrayInputStream(new byte[0]);
protected FSTDecoder codec;
protected FSTObjectRegistry objects;
protected Stack<String> debugStack;
protected int curDepth;
protected ArrayList<CallbackEntry> callbacks;
// FSTConfiguration conf;
// mirrored from conf
protected boolean ignoreAnnotations;
protected FSTClazzInfoRegistry clInfoRegistry;
// done
protected ConditionalCallback conditionalCallback;
protected int readExternalReadAHead = 8000;
protected VersionConflictListener versionConflictListener;
protected FSTConfiguration conf;
// copied values from conf
protected boolean isCrossPlatform;
public FSTConfiguration getConf() {
return conf;
}
@Override
public void readFully(byte[] b) throws IOException {
readFully(b, 0, b.length);
}
@Override
public void readFully(byte[] b, int off, int len) throws IOException {
getCodec().readPlainBytes(b, off, len);
}
@Override
public int skipBytes(int n) throws IOException {
getCodec().skip(n);
return n;
}
@Override
public boolean readBoolean() throws IOException {
return getCodec().readFByte() == 0 ? false : true;
}
@Override
public byte readByte() throws IOException {
return getCodec().readFByte();
}
@Override
public int readUnsignedByte() throws IOException {
return ((int) getCodec().readFByte()+256) & 0xff;
}
@Override
public short readShort() throws IOException {
return getCodec().readFShort();
}
@Override
public int readUnsignedShort() throws IOException {
return ((int)readShort()+65536) & 0xffff;
}
@Override
public char readChar() throws IOException {
return getCodec().readFChar();
}
@Override
public int readInt() throws IOException {
return getCodec().readFInt();
}
@Override
public long readLong() throws IOException {
return getCodec().readFLong();
}
@Override
public float readFloat() throws IOException {
return getCodec().readFFloat();
}
@Override
public double readDouble() throws IOException {
return getCodec().readFDouble();
}
@Override
public String readLine() throws IOException {
throw new RuntimeException("not implemented");
}
@Override
public String readUTF() throws IOException {
return getCodec().readStringUTF();
}
public FSTDecoder getCodec() {
return codec;
}
protected void setCodec(FSTDecoder codec) {
this.codec = codec;
}
protected static class CallbackEntry {
ObjectInputValidation cb;
int prio;
CallbackEntry(ObjectInputValidation cb, int prio) {
this.cb = cb;
this.prio = prio;
}
}
public static interface ConditionalCallback {
public boolean shouldSkip(Object halfDecoded, int streamPosition, Field field);
}
public FSTObjectInput() throws IOException {
this(emptyStream, FSTConfiguration.getDefaultConfiguration());
}
public FSTObjectInput(FSTConfiguration conf) {
this(emptyStream, conf);
}
/**
* Creates a FSTObjectInput that uses the specified
* underlying InputStream.
*
* @param in the specified input stream
*/
public FSTObjectInput(InputStream in) throws IOException {
this(in, FSTConfiguration.getDefaultConfiguration());
}
/**
* Creates a FSTObjectInput that uses the specified
* underlying InputStream.
*
* Don't create a FSTConfiguration with each stream, just create one global static configuration and reuseit.
* FSTConfiguration is threadsafe.
*
* @param in the specified input stream
*/
public FSTObjectInput(InputStream in, FSTConfiguration conf) {
setCodec(conf.createStreamDecoder());
getCodec().setInputStream(in);
isCrossPlatform = conf.isCrossPlatform();
initRegistries(conf);
this.conf = conf;
}
public Class getClassForName(String name) throws ClassNotFoundException {
return getCodec().classForName(name);
}
protected void initRegistries(FSTConfiguration conf) {
ignoreAnnotations = conf.getCLInfoRegistry().isIgnoreAnnotations();
clInfoRegistry = conf.getCLInfoRegistry();
objects = (FSTObjectRegistry) conf.getCachedObject(FSTObjectRegistry.class);
if (objects == null) {
objects = new FSTObjectRegistry(conf);
} else {
objects.clearForRead(conf);
}
}
public ConditionalCallback getConditionalCallback() {
return conditionalCallback;
}
public void setConditionalCallback(ConditionalCallback conditionalCallback) {
this.conditionalCallback = conditionalCallback;
}
public int getReadExternalReadAHead() {
return readExternalReadAHead;
}
/**
* since the stock readXX methods on InputStream are final, i can't ensure sufficient readAhead on the inputStream
* before calling readExternal. Default value is 16000 bytes. If you make use of the externalizable interfac
* and write larger Objects a) cast the ObjectInput in readExternal to FSTObjectInput and call ensureReadAhead on this
* in your readExternal method b) set a sufficient maximum using this method before serializing.
* @param readExternalReadAHead
*/
public void setReadExternalReadAHead(int readExternalReadAHead) {
this.readExternalReadAHead = readExternalReadAHead;
}
@Override
public Object readObject() throws ClassNotFoundException, IOException {
try {
return readObject((Class[]) null);
} catch (Exception e) {
throw new IOException(e);
}
}
@Override
public int read() throws IOException {
return getCodec().readIntByte();
}
@Override
public int read(byte[] b) throws IOException {
getCodec().readPlainBytes(b, 0, b.length);
return b.length;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
getCodec().readPlainBytes(b, off, len);
return b.length;
}
@Override
public long skip(long n) throws IOException {
getCodec().skip((int) n);
return n;
}
@Override
public int available() throws IOException {
return getCodec().available();
}
protected void processValidation() throws InvalidObjectException {
if (callbacks == null) {
return;
}
Collections.sort(callbacks, new Comparator<CallbackEntry>() {
@Override
public int compare(CallbackEntry o1, CallbackEntry o2) {
return o2.prio - o1.prio;
}
});
for (int i = 0; i < callbacks.size(); i++) {
CallbackEntry callbackEntry = callbacks.get(i);
try {
callbackEntry.cb.validateObject();
} catch (Exception ex) {
FSTUtil.<RuntimeException>rethrow(ex);
}
}
}
public Object readObject(Class... possibles) throws Exception {
curDepth++;
if ( isCrossPlatform ) {
return readObjectInternal(null); // not supported cross platform
}
try {
if (possibles != null && possibles.length > 1 ) {
for (int i = 0; i < possibles.length; i++) {
Class possible = possibles[i];
getCodec().registerClass(possible);
}
}
Object res = readObjectInternal(possibles);
processValidation();
return res;
} catch (Throwable th) {
FSTUtil.<RuntimeException>rethrow(th);
} finally {
curDepth--;
}
return null;
}
protected FSTClazzInfo.FSTFieldInfo infoCache;
public Object readObjectInternal(Class... expected) throws ClassNotFoundException, IOException, IllegalAccessException, InstantiationException {
try {
FSTClazzInfo.FSTFieldInfo info = infoCache;
infoCache = null;
if (info == null )
info = new FSTClazzInfo.FSTFieldInfo(expected, null, ignoreAnnotations);
else
info.possibleClasses = expected;
Object res = readObjectWithHeader(info);
infoCache = info;
return res;
} catch (Throwable t) {
FSTUtil.<RuntimeException>rethrow(t);
}
return null;
}
public Object readObjectWithHeader(FSTClazzInfo.FSTFieldInfo referencee) throws Exception {
FSTClazzInfo clzSerInfo;
Class c;
final int readPos = getCodec().getInputPos();
byte code = getCodec().readObjectHeaderTag();
if (code == FSTObjectOutput.OBJECT ) {
// class name
clzSerInfo = readClass();
c = clzSerInfo.getClazz();
if ( c.isArray() )
return readArrayNoHeader(referencee,readPos,c);
// fall through
} else if ( code == FSTObjectOutput.TYPED ) {
c = referencee.getType();
clzSerInfo = getClazzInfo(c, referencee);
} else if ( code >= 1 ) {
try {
c = referencee.getPossibleClasses()[code - 1];
clzSerInfo = getClazzInfo(c, referencee);
} catch (Throwable th) {
clzSerInfo = null; c = null;
FSTUtil.<RuntimeException>rethrow(th);
}
} else {
Object res = instantiateSpecialTag(referencee, readPos, code);
return res;
}
try {
FSTObjectSerializer ser = clzSerInfo.getSer();
if (ser != null) {
Object res = instantiateAndReadWithSer(c, ser, clzSerInfo, referencee, readPos);
getCodec().readArrayEnd(clzSerInfo);
return res;
} else {
Object res = instantiateAndReadNoSer(c, clzSerInfo, referencee, readPos);
return res;
}
} catch (Exception e) {
FSTUtil.<RuntimeException>rethrow(e);
}
return null;
}
protected Object instantiateSpecialTag(FSTClazzInfo.FSTFieldInfo referencee, int readPos, byte code) throws Exception {
if ( code == FSTObjectOutput.STRING ) { // faster than switch, note: currently string tag not used by all codecs ..
String res = getCodec().readStringUTF();
objects.registerObjectForRead(res, readPos);
return res;
} else if ( code == FSTObjectOutput.BIG_INT ) {
return instantiateBigInt();
} else if ( code == FSTObjectOutput.NULL ) {
return null;
} else
{
switch (code) {
// case FSTObjectOutput.BIG_INT: { return instantiateBigInt(); }
case FSTObjectOutput.BIG_LONG: { return Long.valueOf(getCodec().readFLong()); }
case FSTObjectOutput.BIG_BOOLEAN_FALSE: { return Boolean.FALSE; }
case FSTObjectOutput.BIG_BOOLEAN_TRUE: { return Boolean.TRUE; }
case FSTObjectOutput.ONE_OF: { return referencee.getOneOf()[getCodec().readFByte()]; }
// case FSTObjectOutput.NULL: { return null; }
case FSTObjectOutput.DIRECT_ARRAY_OBJECT: {
Object directObject = getCodec().getDirectObject();
objects.registerObjectForRead(directObject,readPos);
return directObject;
}
case FSTObjectOutput.DIRECT_OBJECT: {
Object directObject = getCodec().getDirectObject();
if (directObject.getClass() == byte[].class) { // fixme. special for minibin, move it there
if ( referencee != null && referencee.getType() == boolean[].class )
{
byte[] ba = (byte[]) directObject;
boolean res[] = new boolean[ba.length];
for (int i = 0; i < res.length; i++) {
res[i] = ba[i] != 0;
}
directObject = res;
}
}
objects.registerObjectForRead(directObject,readPos);
return directObject;
}
// case FSTObjectOutput.STRING: return getCodec().readStringUTF();
case FSTObjectOutput.HANDLE: {
Object res = instantiateHandle(referencee);
getCodec().readObjectEnd();
return res;
}
case FSTObjectOutput.ARRAY: {
Object res = instantiateArray(referencee, readPos);
return res;
}
case FSTObjectOutput.ENUM: { return instantiateEnum(referencee, readPos); }
}
throw new RuntimeException("unknown object tag "+code);
}
}
protected FSTClazzInfo getClazzInfo(Class c, FSTClazzInfo.FSTFieldInfo referencee) {
FSTClazzInfo clzSerInfo;
FSTClazzInfo lastInfo = referencee.lastInfo;
if ( lastInfo != null && lastInfo.clazz == c && lastInfo.conf == conf) {
clzSerInfo = lastInfo;
} else {
clzSerInfo = clInfoRegistry.getCLInfo(c, conf);
referencee.lastInfo = clzSerInfo;
}
return clzSerInfo;
}
protected Object instantiateHandle(FSTClazzInfo.FSTFieldInfo referencee) throws IOException {
int handle = getCodec().readFInt();
Object res = objects.getReadRegisteredObject(handle);
if (res == null) {
throw new IOException("unable to ressolve handle " + handle + " " + referencee.getDesc() + " " + getCodec().getInputPos() );
}
return res;
}
protected Object instantiateArray(FSTClazzInfo.FSTFieldInfo referencee, int readPos) throws Exception {
Object res = readArray(referencee);
if ( ! referencee.isFlat() ) {
objects.registerObjectForRead(res, readPos);
}
return res;
}
protected Object instantiateEnum(FSTClazzInfo.FSTFieldInfo referencee, int readPos) throws IOException, ClassNotFoundException {
FSTClazzInfo clzSerInfo;
Class c;
clzSerInfo = readClass();
c = clzSerInfo.getClazz();
int ordinal = getCodec().readFInt();
Object[] enumConstants = clzSerInfo.getEnumConstants();
if ( enumConstants == null ) {
// pseudo enum of anonymous classes tom style ?
return null;
}
Object res = enumConstants[ordinal];
if ( REGISTER_ENUMS_READ ) {
if ( ! referencee.isFlat() ) { // should be unnecessary
objects.registerObjectForRead(res, readPos);
}
}
return res;
}
protected Object instantiateBigInt() throws IOException {
int val = getCodec().readFInt();
return Integer.valueOf(val);
}
protected Object instantiateAndReadWithSer(Class c, FSTObjectSerializer ser, FSTClazzInfo clzSerInfo, FSTClazzInfo.FSTFieldInfo referencee, int readPos) throws Exception {
boolean serInstance = false;
Object newObj = ser.instantiate(c, this, clzSerInfo, referencee, readPos);
if (newObj == null) {
newObj = clzSerInfo.newInstance(getCodec().isMapBased());
} else
serInstance = true;
if (newObj == null) {
throw new IOException(referencee.getDesc() + ":Failed to instantiate '" + c.getName() + "'. Register a custom serializer implementing instantiate or define empty constructor..");
}
if ( newObj == FSTObjectSerializer.REALLY_NULL ) {
newObj = null;
} else {
if (newObj.getClass() != c && ser == null ) {
// for advanced trickery (e.g. returning non-serializable from FSTSerializer)
// this hurts. so in case of FSTSerializers incoming clzInfo will refer to the
// original class, not the one actually instantiated
c = newObj.getClass();
clzSerInfo = clInfoRegistry.getCLInfo(c, conf);
}
if ( ! referencee.isFlat() && ! clzSerInfo.isFlat() && !ser.alwaysCopy()) {
objects.registerObjectForRead(newObj, readPos);
}
if ( !serInstance )
ser.readObject(this, newObj, clzSerInfo, referencee);
}
getCodec().consumeEndMarker(); //=> bug when writing objects unlimited
return newObj;
}
protected Object instantiateAndReadNoSer(Class c, FSTClazzInfo clzSerInfo, FSTClazzInfo.FSTFieldInfo referencee, int readPos) throws Exception {
Object newObj;
newObj = clzSerInfo.newInstance(getCodec().isMapBased());
if (newObj == null) {
throw new IOException(referencee.getDesc() + ":Failed to instantiate '" + c.getName() + "'. Register a custom serializer implementing instantiate or define empty constructor.");
}
//fixme: code below improves unshared decoding perf, however disables to run mixed mode (clients can decide)
//actually would need 2 flags for encode/decode
//tested with json mixed mode does not work anyway ...
final boolean needsRefLookup = conf.shareReferences && !referencee.isFlat() && !clzSerInfo.isFlat();
// previously :
// final boolean needsRefLookup = !referencee.isFlat() && !clzSerInfo.isFlat();
if (needsRefLookup) {
objects.registerObjectForRead(newObj, readPos);
}
if ( clzSerInfo.isExternalizable() )
{
int tmp = readPos;
getCodec().ensureReadAhead(readExternalReadAHead);
((Externalizable)newObj).readExternal(this);
getCodec().readExternalEnd();
if ( clzSerInfo.getReadResolveMethod() != null ) {
final Object prevNew = newObj;
newObj = handleReadRessolve(clzSerInfo, newObj);
if ( newObj != prevNew && needsRefLookup ) {
objects.replace(prevNew, newObj, tmp);
}
}
} else if (clzSerInfo.useCompatibleMode())
{
Object replaced = readObjectCompatible(referencee, clzSerInfo, newObj);
if (replaced != null && replaced != newObj) {
objects.replace(newObj, replaced, readPos);
newObj = replaced;
}
} else {
FSTClazzInfo.FSTFieldInfo[] fieldInfo = clzSerInfo.getFieldInfo();
readObjectFields(referencee, clzSerInfo, fieldInfo, newObj,0,0);
}
return newObj;
}
protected Object readObjectCompatible(FSTClazzInfo.FSTFieldInfo referencee, FSTClazzInfo serializationInfo, Object newObj) throws Exception {
Class cl = serializationInfo.getClazz();
readObjectCompatibleRecursive(referencee, newObj, serializationInfo, cl);
if (newObj != null &&
serializationInfo.getReadResolveMethod() != null) {
newObj = handleReadRessolve(serializationInfo, newObj);
}
return newObj;
}
protected Object handleReadRessolve(FSTClazzInfo serializationInfo, Object newObj) throws IllegalAccessException {
Object rep = null;
try {
rep = serializationInfo.getReadResolveMethod().invoke(newObj);
} catch (InvocationTargetException e) {
FSTUtil.<RuntimeException>rethrow(e);
}
newObj = rep;//FIXME: support this in call
return newObj;
}
protected void readObjectCompatibleRecursive(FSTClazzInfo.FSTFieldInfo referencee, Object toRead, FSTClazzInfo serializationInfo, Class cl) throws Exception {
FSTClazzInfo.FSTCompatibilityInfo fstCompatibilityInfo = serializationInfo.getCompInfo().get(cl);
if (!Serializable.class.isAssignableFrom(cl)) {
return; // ok here, as compatible mode will never be triggered for "forceSerializable"
}
readObjectCompatibleRecursive(referencee, toRead, serializationInfo, cl.getSuperclass());
if (fstCompatibilityInfo != null && fstCompatibilityInfo.getReadMethod() != null) {
try {
int tag = readByte(); // expect 55
if ( tag == 66 ) {
// no write method defined, but read method defined ...
// expect defaultReadObject
getCodec().moveTo(getCodec().getInputPos() - 1); // need to push back tag, cause defaultWriteObject on writer side does not write tag
// input.pos--;
}
ObjectInputStream objectInputStream = getObjectInputStream(cl, serializationInfo, referencee, toRead);
fstCompatibilityInfo.getReadMethod().invoke(toRead, objectInputStream);
fakeWrapper.pop();
} catch (Exception e) {
FSTUtil.<RuntimeException>rethrow(e);
}
} else {
if (fstCompatibilityInfo != null) {
int tag = readByte();
if ( tag == 55 )
{
// came from writeMethod, but no readMethod defined => assume defaultWriteObject
tag = readByte(); // consume tag of defaultwriteobject (99)
if ( tag == 77 ) // came from putfield
{
HashMap<String, Object> fieldMap = (HashMap<String, Object>) FSTObjectInput.this.readObjectInternal(HashMap.class);
final FSTClazzInfo.FSTFieldInfo[] fieldArray = fstCompatibilityInfo.getFieldArray();
for (int i = 0; i < fieldArray.length; i++) {
FSTClazzInfo.FSTFieldInfo fstFieldInfo = fieldArray[i];
final Object val = fieldMap.get(fstFieldInfo.getName());
if ( val != null ) {
fstFieldInfo.setObjectValue(toRead,val);
}
}
return;
}
}
readObjectFields(referencee, serializationInfo, fstCompatibilityInfo.getFieldArray(), toRead,0,0);
}
}
}
public void defaultReadObject(FSTClazzInfo.FSTFieldInfo referencee, FSTClazzInfo serializationInfo, Object newObj)
{
try {
readObjectFields(referencee,serializationInfo,serializationInfo.getFieldInfo(),newObj,0,-1); // -1 flag to indicate no object end should be called
} catch (Exception e) {
FSTUtil.<RuntimeException>rethrow(e);
}
}
protected void readObjectFields(FSTClazzInfo.FSTFieldInfo referencee, FSTClazzInfo serializationInfo, FSTClazzInfo.FSTFieldInfo[] fieldInfo, Object newObj, int startIndex, int version) throws Exception {
if ( getCodec().isMapBased() ) {
readFieldsMapBased(referencee, serializationInfo, newObj);
if ( version >= 0 && newObj instanceof Unknown == false)
getCodec().readObjectEnd();
return;
}
if ( version < 0 )
version = 0;
int booleanMask = 0;
int boolcount = 8;
final int length = fieldInfo.length;
int conditional = 0;
for (int i = startIndex; i < length; i++) {
try {
FSTClazzInfo.FSTFieldInfo subInfo = fieldInfo[i];
if (subInfo.getVersion() > version ) {
int nextVersion = getCodec().readVersionTag();
if ( nextVersion == 0 ) // old object read
{
oldVersionRead(newObj);
return;
}
if ( nextVersion != subInfo.getVersion() ) {
throw new RuntimeException("read version tag "+nextVersion+" fieldInfo has "+subInfo.getVersion());
}
readObjectFields(referencee,serializationInfo,fieldInfo,newObj,i,nextVersion);
return;
}
if (subInfo.isPrimitive()) {
int integralType = subInfo.getIntegralType();
if (integralType == FSTClazzInfo.FSTFieldInfo.BOOL) {
if (boolcount == 8) {
booleanMask = ((int) getCodec().readFByte() + 256) &0xff;
boolcount = 0;
}
boolean val = (booleanMask & 128) != 0;
booleanMask = booleanMask << 1;
boolcount++;
subInfo.setBooleanValue(newObj, val);
} else {
switch (integralType) {
case FSTClazzInfo.FSTFieldInfo.BYTE: subInfo.setByteValue(newObj, getCodec().readFByte()); break;
case FSTClazzInfo.FSTFieldInfo.CHAR: subInfo.setCharValue(newObj, getCodec().readFChar()); break;
case FSTClazzInfo.FSTFieldInfo.SHORT: subInfo.setShortValue(newObj, getCodec().readFShort()); break;
case FSTClazzInfo.FSTFieldInfo.INT: subInfo.setIntValue(newObj, getCodec().readFInt()); break;
case FSTClazzInfo.FSTFieldInfo.LONG: subInfo.setLongValue(newObj, getCodec().readFLong()); break;
case FSTClazzInfo.FSTFieldInfo.FLOAT: subInfo.setFloatValue(newObj, getCodec().readFFloat()); break;
case FSTClazzInfo.FSTFieldInfo.DOUBLE: subInfo.setDoubleValue(newObj, getCodec().readFDouble()); break;
}
}
} else {
if ( subInfo.isConditional() ) {
if ( conditional == 0 ) {
conditional = getCodec().readPlainInt();
if ( skipConditional(newObj, conditional, subInfo) ) {
getCodec().moveTo(conditional);
continue;
}
}
}
// object
Object subObject = readObjectWithHeader(subInfo);
subInfo.setObjectValue(newObj, subObject);
}
} catch (IllegalAccessException ex) {
throw new IOException(ex);
}
}
int debug = getCodec().readVersionTag();// just consume '0'
}
public VersionConflictListener getVersionConflictListener() {
return versionConflictListener;
}
/**
* see @Version annotation
* @param versionConflictListener
*/
public void setVersionConflictListener(VersionConflictListener versionConflictListener) {
this.versionConflictListener = versionConflictListener;
}
protected void oldVersionRead(Object newObj) {
if ( versionConflictListener != null )
versionConflictListener.onOldVersionRead(newObj);
}
protected void readFieldsMapBased(FSTClazzInfo.FSTFieldInfo referencee, FSTClazzInfo serializationInfo, Object newObj) throws Exception {
String name;
int len = getCodec().getObjectHeaderLen(); // check if len is known in advance
if ( len < 0 )
len = Integer.MAX_VALUE;
int count = 0;
boolean isUnknown = newObj.getClass() == Unknown.class; // json
boolean inArray = isUnknown && getCodec().inArray(); // json externalized/custom serialized
getCodec().startFieldReading(newObj);
// fixme: break up this loop into separate impls.
while( count < len ) {
if ( inArray ) {
// unknwon json object written by externalize or custom serializer
Object o = readObjectWithHeader(null);
if ( o != null && getCodec().isEndMarker(o.toString()) )
return;
((Unknown)newObj).add(o);
continue;
}
name= getCodec().readStringUTF();
//int debug = getCodec().getInputPos();
if ( len == Integer.MAX_VALUE && getCodec().isEndMarker(name) )
return;
count++;
if (isUnknown) {
FSTClazzInfo.FSTFieldInfo fakeField = new FSTClazzInfo.FSTFieldInfo(null, null, true);
fakeField.fakeName = name;
Object toSet = readObjectWithHeader(fakeField);
((Unknown)newObj).set(name, toSet);
} else
if ( newObj.getClass() == MBObject.class ) {
Object toSet = readObjectWithHeader(null);
((MBObject)newObj).put(name,toSet);
} else {
FSTClazzInfo.FSTFieldInfo fieldInfo = serializationInfo.getFieldInfo(name, null);
if (fieldInfo == null) {
System.out.println("warning: unknown field: " + name + " on class " + serializationInfo.getClazz().getName());
} else {
if (fieldInfo.isPrimitive()) {
// direct primitive field
switch (fieldInfo.getIntegralType()) {
case FSTClazzInfo.FSTFieldInfo.BOOL:
fieldInfo.setBooleanValue(newObj, getCodec().readFByte() == 0 ? false : true);
break;
case FSTClazzInfo.FSTFieldInfo.BYTE:
fieldInfo.setByteValue(newObj, getCodec().readFByte());
break;
case FSTClazzInfo.FSTFieldInfo.CHAR:
fieldInfo.setCharValue(newObj, getCodec().readFChar());
break;
case FSTClazzInfo.FSTFieldInfo.SHORT:
fieldInfo.setShortValue(newObj, getCodec().readFShort());
break;
case FSTClazzInfo.FSTFieldInfo.INT:
fieldInfo.setIntValue(newObj, getCodec().readFInt());
break;
case FSTClazzInfo.FSTFieldInfo.LONG:
fieldInfo.setLongValue(newObj, getCodec().readFLong());
break;
case FSTClazzInfo.FSTFieldInfo.FLOAT:
fieldInfo.setFloatValue(newObj, getCodec().readFFloat());
break;
case FSTClazzInfo.FSTFieldInfo.DOUBLE:
fieldInfo.setDoubleValue(newObj, getCodec().readFDouble());
break;
default:
throw new RuntimeException("unkown primitive type " + fieldInfo);
}
} else {
Object toSet = readObjectWithHeader(fieldInfo);
toSet = getCodec().coerceElement(fieldInfo.getType(), toSet);
fieldInfo.setObjectValue(newObj, toSet);
}
}
}
}
}
protected boolean skipConditional(Object newObj, int conditional, FSTClazzInfo.FSTFieldInfo subInfo) {
if ( conditionalCallback != null ) {
return conditionalCallback.shouldSkip(newObj,conditional,subInfo.getField());
}
return false;
}
protected void readCompatibleObjectFields(FSTClazzInfo.FSTFieldInfo referencee, FSTClazzInfo serializationInfo, FSTClazzInfo.FSTFieldInfo[] fieldInfo, Map res) throws Exception {
int booleanMask = 0;
int boolcount = 8;
for (int i = 0; i < fieldInfo.length; i++) {
try {
FSTClazzInfo.FSTFieldInfo subInfo = fieldInfo[i];
if (subInfo.isIntegral() && !subInfo.isArray()) {
final Class subInfoType = subInfo.getType();
if (subInfoType == boolean.class) {
if (boolcount == 8) {
booleanMask = ((int) getCodec().readFByte() + 256) &0xff;
boolcount = 0;
}
boolean val = (booleanMask & 128) != 0;
booleanMask = booleanMask << 1;
boolcount++;
res.put(subInfo.getName(), val);
}
if (subInfoType == byte.class) {
res.put(subInfo.getName(), getCodec().readFByte());
} else if (subInfoType == char.class) {
res.put(subInfo.getName(), getCodec().readFChar());
} else if (subInfoType == short.class) {
res.put(subInfo.getName(), getCodec().readFShort());
} else if (subInfoType == int.class) {
res.put(subInfo.getName(), getCodec().readFInt());
} else if (subInfoType == double.class) {
res.put(subInfo.getName(), getCodec().readFDouble());
} else if (subInfoType == float.class) {
res.put(subInfo.getName(), getCodec().readFFloat());
} else if (subInfoType == long.class) {
res.put(subInfo.getName(), getCodec().readFLong());
}
} else {
// object
Object subObject = readObjectWithHeader(subInfo);
res.put(subInfo.getName(), subObject);
}
} catch (IllegalAccessException ex) {
throw new IOException(ex);
}
}
}
public String readStringUTF() throws IOException {
return getCodec().readStringUTF();
}
/**
* len < 127 !!!!!
* @return
* @throws IOException
*/
public String readStringAsc() throws IOException {
return getCodec().readStringAsc();
}
protected Object readArray(FSTClazzInfo.FSTFieldInfo referencee) throws Exception {
int pos = getCodec().getInputPos();
Object classOrArray = getCodec().readArrayHeader();
if ( classOrArray instanceof Class == false )
return classOrArray;
if ( classOrArray == null )
return null;
Object o = readArrayNoHeader(referencee, pos, (Class) classOrArray);
getCodec().readArrayEnd(null);
return o;
}
protected Object readArrayNoHeader(FSTClazzInfo.FSTFieldInfo referencee, int pos, Class arrCl) throws Exception {
final int len = getCodec().readFInt();
if (len == -1) {
return null;
}
Class arrType = arrCl.getComponentType();
if (!arrCl.getComponentType().isArray()) {
Object array = Array.newInstance(arrType, len);
if ( ! referencee.isFlat() )
objects.registerObjectForRead(array, pos );
if (arrCl.getComponentType().isPrimitive()) {
return getCodec().readFPrimitiveArray(array, arrType, len);
} else { // Object Array
Object arr[] = (Object[]) array;
for (int i = 0; i < len; i++) {
Object value = readObjectWithHeader(referencee);
value = getCodec().coerceElement(arrType, value);
arr[i] = value;
}
getCodec().readObjectEnd();
}
return array;
} else { // multidim array
Object array[] = (Object[]) Array.newInstance(arrType, len);
if ( ! referencee.isFlat() ) {
objects.registerObjectForRead(array, pos);
}
FSTClazzInfo.FSTFieldInfo ref1 = new FSTClazzInfo.FSTFieldInfo(referencee.getPossibleClasses(), null, clInfoRegistry.isIgnoreAnnotations());
for (int i = 0; i < len; i++) {
Object subArray = readArray(ref1);
array[i] = subArray;
}
return array;
}
}
public void registerObject(Object o, int streamPosition, FSTClazzInfo info, FSTClazzInfo.FSTFieldInfo referencee) {
if ( ! objects.disabled && !referencee.isFlat() && (info == null || ! info.isFlat() ) ) {
objects.registerObjectForRead(o, streamPosition);
}
}
public FSTClazzInfo readClass() throws IOException, ClassNotFoundException {
return getCodec().readClass();
}
protected void resetAndClearRefs() {
try {
reset();
objects.clearForRead(conf);
} catch (IOException e) {
FSTUtil.<RuntimeException>rethrow(e);
}
}
public void reset() throws IOException {
getCodec().reset();
}
public void resetForReuse(InputStream in) throws IOException {
if ( closed ) {
throw new RuntimeException("can't reuse closed stream");
}
getCodec().reset();
getCodec().setInputStream(in);
objects.clearForRead(conf);
}
public void resetForReuseCopyArray(byte bytes[], int off, int len) throws IOException {
if ( closed ) {
throw new RuntimeException("can't reuse closed stream");
}
getCodec().reset();
objects.clearForRead(conf);
getCodec().resetToCopyOf(bytes, off, len);
}
public void resetForReuseUseArray(byte bytes[]) throws IOException {
resetForReuseUseArray(bytes, bytes.length);
}
public void resetForReuseUseArray(byte bytes[], int len) throws IOException {
if ( closed ) {
throw new RuntimeException("can't reuse closed stream");
}
objects.clearForRead(conf);
getCodec().resetWith(bytes, len);
}
public final int readFInt() throws IOException {
return getCodec().readFInt();
}
protected boolean closed = false;
@Override
public void close() throws IOException {
closed = true;
resetAndClearRefs();
conf.returnObject(objects);
getCodec().close();
}
////////////////////////////////////////////////////// epic compatibility hack /////////////////////////////////////////////////////////
protected MyObjectStream fakeWrapper; // some jdk classes hash for ObjectStream, so provide the same instance always
protected ObjectInputStream getObjectInputStream(final Class cl, final FSTClazzInfo clInfo, final FSTClazzInfo.FSTFieldInfo referencee, final Object toRead) throws IOException {
ObjectInputStream wrapped = new ObjectInputStream() {
@Override
public Object readObjectOverride() throws IOException, ClassNotFoundException {
try {
byte b = FSTObjectInput.this.readByte();
if ( b != FSTObjectOutput.SPECIAL_COMPATIBILITY_OBJECT_TAG ) {
Constructor<?>[] constructors = OptionalDataException.class.getDeclaredConstructors();
FSTObjectInput.this.pushBack(1);
for (int i = 0; i < constructors.length; i++) {
Constructor constructor = constructors[i];
Class[] typeParameters = constructor.getParameterTypes();
if ( typeParameters != null && typeParameters.length == 1 && typeParameters[0] == int.class) {
constructor.setAccessible(true);
OptionalDataException ode;
try {
ode = (OptionalDataException) constructor.newInstance(0);
throw ode;
} catch (InvocationTargetException e) {
break;
}
}
}
throw new EOFException("if your code relies on this, think");
}
return FSTObjectInput.this.readObjectInternal(referencee.getPossibleClasses());
} catch (IllegalAccessException e) {
throw new IOException(e);
} catch (InstantiationException e) {
throw new IOException(e);
}
}
@Override
public Object readUnshared() throws IOException, ClassNotFoundException {
try {
return FSTObjectInput.this.readObjectInternal(referencee.getPossibleClasses()); // fixme
} catch (IllegalAccessException e) {
throw new IOException(e);
} catch (InstantiationException e) {
throw new IOException(e);
}
}
@Override
public void defaultReadObject() throws IOException, ClassNotFoundException {
try {
int tag = readByte();
if ( tag == 77 ) // came from writeFields
{
fieldMap = (HashMap<String, Object>) FSTObjectInput.this.readObjectInternal(HashMap.class);
// object has been written with writeFields, is no read with defaultReadObjects,
// need to autoapply map to object vars.
// this might be redundant in case readObject() pulls a getFields() .. (see bitset testcase)
for (Iterator<String> iterator = fieldMap.keySet().iterator(); iterator.hasNext(); ) {
String key = iterator.next();
FSTClazzInfo.FSTFieldInfo fieldInfo = clInfo.getFieldInfo(key, null);// in case fieldName is not unique => cannot recover/fix
if ( fieldInfo != null ) {
fieldInfo.setObjectValue(toRead,fieldMap.get(key));
}
}
} else {
FSTObjectInput.this.readObjectFields(
referencee,
clInfo,
clInfo.getCompInfo().get(cl).getFieldArray(),
toRead,
0,
0
); // FIXME: only fields of current class
}
} catch (Exception e) {
throw new IOException(e);
}
}
HashMap<String, Object> fieldMap;
@Override
public GetField readFields() throws IOException, ClassNotFoundException {
int tag = readByte();
try {
FSTClazzInfo.FSTCompatibilityInfo fstCompatibilityInfo = clInfo.getCompInfo().get(cl);
if (tag==99) { // came from defaultwriteobject
// Note: in case number and names of instance fields of reader/writer are different,
// this fails as code below implicitely assumes, fields of writer == fields of reader
// unfortunately one can use defaultWriteObject at writer side but use getFields at reader side
// in readObject(). if then fields differ, code below reads BS and fails.
// Its impossible to fix that except by always using putField + getField for
// JDK compatibility classes, however this will waste lots of performance. As
// it would be necessary to *always* write full metainformation (a map of fieldName => value pairs)
// see #53
fieldMap = new HashMap<String, Object>();
FSTObjectInput.this.readCompatibleObjectFields(referencee, clInfo, fstCompatibilityInfo.getFieldArray(), fieldMap);
getCodec().readVersionTag(); // consume dummy version tag as created by defaultWriteObject
} else if (tag == 66) { // has been written from writeObjectCompatible without writeMethod
fieldMap = new HashMap<String, Object>();
FSTObjectInput.this.readCompatibleObjectFields(referencee, clInfo, fstCompatibilityInfo.getFieldArray(), fieldMap);
getCodec().readVersionTag(); // consume dummy version tag as created by defaultWriteObject
} else {
fieldMap = (HashMap<String, Object>) FSTObjectInput.this.readObjectInternal(HashMap.class);
}
} catch (Exception e) {
FSTUtil.<RuntimeException>rethrow(e);
}
return new GetField() {
@Override
public ObjectStreamClass getObjectStreamClass() {
return ObjectStreamClass.lookup(cl);
}
@Override
public boolean defaulted(String name) throws IOException {
return fieldMap.get(name) == null;
}
@Override
public boolean get(String name, boolean val) throws IOException {
if (fieldMap.get(name) == null) {
return val;
}
return ((Boolean) fieldMap.get(name)).booleanValue();
}
@Override
public byte get(String name, byte val) throws IOException {
if (fieldMap.get(name) == null) {
return val;
}
return ((Byte) fieldMap.get(name)).byteValue();
}
@Override
public char get(String name, char val) throws IOException {
if (fieldMap.get(name) == null) {
return val;
}
return ((Character) fieldMap.get(name)).charValue();
}
@Override
public short get(String name, short val) throws IOException {
if (fieldMap.get(name) == null) {
return val;
}
return ((Short) fieldMap.get(name)).shortValue();
}
@Override
public int get(String name, int val) throws IOException {
if (fieldMap.get(name) == null) {
return val;
}
return ((Integer) fieldMap.get(name)).intValue();
}
@Override
public long get(String name, long val) throws IOException {
if (fieldMap.get(name) == null) {
return val;
}
return ((Long) fieldMap.get(name)).longValue();
}
@Override
public float get(String name, float val) throws IOException {
if (fieldMap.get(name) == null) {
return val;
}
return ((Float) fieldMap.get(name)).floatValue();
}
@Override
public double get(String name, double val) throws IOException {
if (fieldMap.get(name) == null) {
return val;
}
return ((Double) fieldMap.get(name)).doubleValue();
}
@Override
public Object get(String name, Object val) throws IOException {
Object res = fieldMap.get(name);
if (res == null) {
return val;
}
return res;
}
};
}
@Override
public void registerValidation(ObjectInputValidation obj, int prio) throws NotActiveException, InvalidObjectException {
if (callbacks == null) {
callbacks = new ArrayList<CallbackEntry>();
}
callbacks.add(new CallbackEntry(obj, prio));
}
@Override
public int read() throws IOException {
return getCodec().readFByte();
}
@Override
public int read(byte[] buf, int off, int len) throws IOException {
return FSTObjectInput.this.read(buf, off, len);
}
@Override
public int available() throws IOException {
return FSTObjectInput.this.available();
}
@Override
public void close() throws IOException {
}
@Override
public boolean readBoolean() throws IOException {
return FSTObjectInput.this.readBoolean();
}
@Override
public byte readByte() throws IOException {
return getCodec().readFByte();
}
@Override
public int readUnsignedByte() throws IOException {
return FSTObjectInput.this.readUnsignedByte();
}
@Override
public char readChar() throws IOException {
return getCodec().readFChar();
}
@Override
public short readShort() throws IOException {
return getCodec().readFShort();
}
@Override
public int readUnsignedShort() throws IOException {
return FSTObjectInput.this.readUnsignedShort();
}
@Override
public int readInt() throws IOException {
return getCodec().readFInt();
}
@Override
public long readLong() throws IOException {
return getCodec().readFLong();
}
@Override
public float readFloat() throws IOException {
return getCodec().readFFloat();
}
@Override
public double readDouble() throws IOException {
return getCodec().readFDouble();
}
@Override
public void readFully(byte[] buf) throws IOException {
FSTObjectInput.this.readFully(buf);
}
@Override
public void readFully(byte[] buf, int off, int len) throws IOException {
FSTObjectInput.this.readFully(buf, off, len);
}
@Override
public int skipBytes(int len) throws IOException {
return FSTObjectInput.this.skipBytes(len);
}
@Override
public String readUTF() throws IOException {
return getCodec().readStringUTF();
}
@Override
public String readLine() throws IOException {
return FSTObjectInput.this.readLine();
}
@Override
public int read(byte[] b) throws IOException {
return FSTObjectInput.this.read(b);
}
@Override
public long skip(long n) throws IOException {
return FSTObjectInput.this.skip(n);
}
@Override
public void mark(int readlimit) {
throw new RuntimeException("not implemented");
}
@Override
public void reset() throws IOException {
FSTObjectInput.this.reset();
}
@Override
public boolean markSupported() {
return false;
}
};
if ( fakeWrapper == null ) {
fakeWrapper = new MyObjectStream();
}
fakeWrapper.push(wrapped);
return fakeWrapper;
}
protected void pushBack(int i) {
getCodec().pushBack(i);
}
protected static class MyObjectStream extends ObjectInputStream {
ObjectInputStream wrapped;
ArrayDeque<ObjectInputStream> wrappedStack = new ArrayDeque<ObjectInputStream>();
public void push( ObjectInputStream in ) {
wrappedStack.push(in);
wrapped = in;
}
public void pop() {
wrapped = wrappedStack.pop();
}
MyObjectStream() throws IOException, SecurityException {
}
@Override
public Object readObjectOverride() throws IOException, ClassNotFoundException {
return wrapped.readObject();
}
@Override
public Object readUnshared() throws IOException, ClassNotFoundException {
return wrapped.readUnshared();
}
@Override
public void defaultReadObject() throws IOException, ClassNotFoundException {
wrapped.defaultReadObject();
}
@Override
public ObjectInputStream.GetField readFields() throws IOException, ClassNotFoundException {
return wrapped.readFields();
}
@Override
public void registerValidation(ObjectInputValidation obj, int prio) throws NotActiveException, InvalidObjectException {
wrapped.registerValidation(obj,prio);
}
@Override
public int read() throws IOException {
return wrapped.read();
}
@Override
public int read(byte[] buf, int off, int len) throws IOException {
return wrapped.read(buf, off, len);
}
@Override
public int available() throws IOException {
return wrapped.available();
}
@Override
public void close() throws IOException {
wrapped.close();
}
@Override
public boolean readBoolean() throws IOException {
return wrapped.readBoolean();
}
@Override
public byte readByte() throws IOException {
return wrapped.readByte();
}
@Override
public int readUnsignedByte() throws IOException {
return wrapped.readUnsignedByte();
}
@Override
public char readChar() throws IOException {
return wrapped.readChar();
}
@Override
public short readShort() throws IOException {
return wrapped.readShort();
}
@Override
public int readUnsignedShort() throws IOException {
return wrapped.readUnsignedShort();
}
@Override
public int readInt() throws IOException {
return wrapped.readInt();
}
@Override
public long readLong() throws IOException {
return wrapped.readLong();
}
@Override
public float readFloat() throws IOException {
return wrapped.readFloat();
}
@Override
public double readDouble() throws IOException {
return wrapped.readDouble();
}
@Override
public void readFully(byte[] buf) throws IOException {
wrapped.readFully(buf);
}
@Override
public void readFully(byte[] buf, int off, int len) throws IOException {
wrapped.readFully(buf, off, len);
}
@Override
public int skipBytes(int len) throws IOException {
return wrapped.skipBytes(len);
}
@Override
public String readUTF() throws IOException {
return wrapped.readUTF();
}
@Override
public String readLine() throws IOException {
return wrapped.readLine();
}
@Override
public int read(byte[] b) throws IOException {
return wrapped.read(b);
}
@Override
public long skip(long n) throws IOException {
return wrapped.skip(n);
}
@Override
public void mark(int readlimit) {
wrapped.mark(readlimit);
}
@Override
public void reset() throws IOException {
wrapped.reset();
}
@Override
public boolean markSupported() {
return wrapped.markSupported();
}
}
}
| fix issue where an array didn't get registered at correct handle until AFTER it was fully read, which broke some cases of self-referential structures.
| src/main/java/org/nustaq/serialization/FSTObjectInput.java | fix issue where an array didn't get registered at correct handle until AFTER it was fully read, which broke some cases of self-referential structures. | |
Java | bsd-3-clause | e0232bde410d9474f480a8fc89a0a420abb0e62a | 0 | LukSkarDev/motech,kmadej/motech,smalecki/motech,adamkalmus/motech,shubhambeehyv/motech,frankhuster/motech,tstalka/motech,jefeweisen/motech,kmadej/motech,sebbrudzinski/motech,adamkalmus/motech,LukSkarDev/motech,shubhambeehyv/motech,jefeweisen/motech,bruceMacLeod/motech-server-pillreminder-0.18,ngraczewski/motech,koshalt/motech,justin-hayes/motech,sebbrudzinski/motech,pgesek/motech,LukSkarDev/motech,pgesek/motech,frankhuster/motech,ngraczewski/motech,tstalka/motech,shubhambeehyv/motech,kmadej/motech,wstrzelczyk/motech,shubhambeehyv/motech,ngraczewski/motech,frankhuster/motech,tectronics/motech,koshalt/motech,tstalka/motech,bruceMacLeod/motech-server-pillreminder-0.18,tectronics/motech,jefeweisen/motech,ngraczewski/motech,sebbrudzinski/motech,koshalt/motech,justin-hayes/motech,wstrzelczyk/motech,justin-hayes/motech,wstrzelczyk/motech,smalecki/motech,kmadej/motech,wstrzelczyk/motech,bruceMacLeod/motech-server-pillreminder-0.18,tstalka/motech,justin-hayes/motech,koshalt/motech,LukSkarDev/motech,sebbrudzinski/motech,pgesek/motech,smalecki/motech,smalecki/motech,bruceMacLeod/motech-server-pillreminder-0.18,frankhuster/motech,pgesek/motech,jefeweisen/motech,adamkalmus/motech,adamkalmus/motech,tectronics/motech,tectronics/motech | package org.motechproject.commcare.service.impl;
import org.motechproject.commcare.domain.CommcareForm;
import org.motechproject.commcare.parser.FormAdapter;
import org.motechproject.commcare.service.CommcareFormService;
import org.motechproject.commcare.util.CommCareAPIHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.google.gson.JsonParseException;
@Service
public class CommcareFormServiceImpl implements CommcareFormService {
private CommCareAPIHttpClient commcareHttpClient;
@Autowired
public CommcareFormServiceImpl(CommCareAPIHttpClient commcareHttpClient) {
this.commcareHttpClient = commcareHttpClient;
}
@Override
public CommcareForm retrieveForm(String id) {
String returnJson = commcareHttpClient.formRequest(id);
try {
return FormAdapter.readJson(returnJson);
} catch (JsonParseException e) {
return null;
}
}
@Override
public String retrieveFormJson(String id) {
return commcareHttpClient.formRequest(id);
}
}
| modules/commcare/api/src/main/java/org/motechproject/commcare/service/impl/CommcareFormServiceImpl.java | package org.motechproject.commcare.service.impl;
import org.motechproject.commcare.domain.CommcareForm;
import org.motechproject.commcare.parser.FormAdapter;
import org.motechproject.commcare.service.CommcareFormService;
import org.motechproject.commcare.util.CommCareAPIHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CommcareFormServiceImpl implements CommcareFormService {
private CommCareAPIHttpClient commcareHttpClient;
@Autowired
public CommcareFormServiceImpl(CommCareAPIHttpClient commcareHttpClient) {
this.commcareHttpClient = commcareHttpClient;
}
@Override
public CommcareForm retrieveForm(String id) {
String returnJson = commcareHttpClient.formRequest(id);
CommcareForm formObject = FormAdapter.readJson(returnJson);
return formObject;
}
@Override
public String retrieveFormJson(String id) {
return commcareHttpClient.formRequest(id);
}
}
| RGillen | #593 | Catch exception when receiving bad form response from form API
Change-Id: I34e72c494cf552ec1799b14d9933b2832eef9702
| modules/commcare/api/src/main/java/org/motechproject/commcare/service/impl/CommcareFormServiceImpl.java | RGillen | #593 | Catch exception when receiving bad form response from form API | |
Java | bsd-3-clause | 0274541eeab34cc9321cc864afb4ee74ff6e463e | 0 | hudson/xstream,8nevil8/xstream | package com.thoughtworks.xstream.core;
import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider;
import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
import java.security.AccessControlException;
public class JVM {
private ReflectionProvider reflectionProvider;
public static boolean is14() {
float majorJavaVersion = Float.parseFloat(System.getProperty("java.version").substring(0, 3));
return majorJavaVersion >= 1.4f;
}
public static boolean isSun() {
return System.getProperty("java.vm.vendor").indexOf("Sun") != -1;
}
public Class loadClass(String name) {
try {
return Class.forName(name, false, getClass().getClassLoader());
} catch (ClassNotFoundException e) {
return null;
}
}
public synchronized ReflectionProvider bestReflectionProvider() {
if (reflectionProvider == null) {
try {
if (isSun() && is14() && loadClass("sun.misc.Unsafe") != null) {
String cls = "com.thoughtworks.xstream.converters.reflection.Sun14ReflectionProvider";
reflectionProvider = (ReflectionProvider) loadClass(cls).newInstance();
} else {
reflectionProvider = new PureJavaReflectionProvider();
}
} catch (InstantiationException e) {
reflectionProvider = new PureJavaReflectionProvider();
} catch (IllegalAccessException e) {
reflectionProvider = new PureJavaReflectionProvider();
} catch (AccessControlException e) {
// thrown when trying to access sun.misc package in Applet context.
reflectionProvider = new PureJavaReflectionProvider();
}
}
return reflectionProvider;
}
}
| xstream/src/java/com/thoughtworks/xstream/core/JVM.java | package com.thoughtworks.xstream.core;
import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider;
import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
public class JVM {
private ReflectionProvider reflectionProvider;
public static boolean is14() {
float majorJavaVersion = Float.parseFloat(System.getProperty("java.version").substring(0, 3));
return majorJavaVersion >= 1.4f;
}
public static boolean isSun() {
return System.getProperty("java.vm.vendor").indexOf("Sun") != -1;
}
public Class loadClass(String name) {
try {
return Class.forName(name, false, getClass().getClassLoader());
} catch (ClassNotFoundException e) {
return null;
}
}
public synchronized ReflectionProvider bestReflectionProvider() {
if (reflectionProvider == null) {
try {
if (isSun() && is14() && loadClass("sun.misc.Unsafe") != null) {
String cls = "com.thoughtworks.xstream.converters.reflection.Sun14ReflectionProvider";
reflectionProvider = (ReflectionProvider) loadClass(cls).newInstance();
} else {
reflectionProvider = new PureJavaReflectionProvider();
}
} catch (InstantiationException e) {
reflectionProvider = new PureJavaReflectionProvider();
} catch (IllegalAccessException e) {
reflectionProvider = new PureJavaReflectionProvider();
}
}
return reflectionProvider;
}
}
| Bugfix: Default to using PureJavaReflectionProvider in Applet context.
| xstream/src/java/com/thoughtworks/xstream/core/JVM.java | Bugfix: Default to using PureJavaReflectionProvider in Applet context. | |
Java | mit | d2cb9cc961fdc5060e1ee28f6c23e00bd83a341a | 0 | arnaudroger/SimpleFlatMapper,arnaudroger/SimpleFlatMapper,arnaudroger/SimpleFlatMapper | package org.simpleflatmapper.jdbc.test.samples;
import org.junit.Test;
import org.simpleflatmapper.jdbc.JdbcColumnKey;
import org.simpleflatmapper.jdbc.JdbcMapper;
import org.simpleflatmapper.jdbc.JdbcMapperFactory;
import org.simpleflatmapper.util.ListCollector;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLType;
import java.sql.Types;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class JoinSample {
public void selectUsers() {
JdbcMapper<Object> jdbcMapper =
JdbcMapperFactory
.newInstance()
.addKeys("id", "roles_id", "phones_id")
.newMapper(Object.class);
}
/**
* Test for https://arnaudroger.github.io/blog/2017/02/24/jooq-one-to-many.html
*
* To avoid having to mock the result set metadata I used a static mapper here. In production code
* you can just call
* newMapper(Location.class)
* instead of newBuilder()...mapper()
*
* @throws SQLException
*/
@Test
public void stackOverFlowJoin() throws SQLException {
JdbcMapper<Location> mapper = JdbcMapperFactory
.newInstance()
.addKeys("player")
.newBuilder(Location.class)
.addMapping(new JdbcColumnKey("name", 1, Types.VARCHAR))
.addMapping(new JdbcColumnKey("player", 2, Types.VARCHAR))
.addMapping(new JdbcColumnKey("invited_players_player", 3, Types.VARCHAR))
.mapper();
UUID[] players = new UUID[] { UUID.randomUUID(), UUID.randomUUID()};
UUID[] invitedPlayers = new UUID[] { UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()};
String[] name = new String[] { "location1", "location2"};
ResultSet rs = mock(ResultSet.class);
when(rs.next()).thenReturn(true, true, true, false);
when(rs.getString(1)).thenReturn(name[0], name[1]);
when(rs.getString(2)).thenReturn(players[0].toString(), players[1].toString());
when(rs.getObject(2)).thenReturn(players[0].toString(),players[0].toString(),players[0].toString(), players[0].toString(), players[1].toString(), players[1].toString());
when(rs.getString(3)).thenReturn(invitedPlayers[0].toString(), invitedPlayers[1].toString(), invitedPlayers[2].toString());
List<Location> list = mapper.forEach(rs, new ListCollector<Location>()).getList();
assertEquals(2, list.size());
assertEquals("location1", list.get(0).getName());
assertEquals(players[0], list.get(0).getPlayer());
assertEquals(Arrays.asList(invitedPlayers[0], invitedPlayers[1]), list.get(0).getInvitedPlayers());
assertEquals("location2", list.get(1).getName());
assertEquals(players[1], list.get(1).getPlayer());
assertEquals(Arrays.asList(invitedPlayers[2]), list.get(1).getInvitedPlayers());
}
public static class Location {
private final String name;
private final UUID player;
private final List<UUID> invitedPlayers;
public Location(String name, UUID player, List<UUID> invitedPlayers) {
this.name = name;
this.player = player;
this.invitedPlayers = invitedPlayers;
}
public String getName() {
return name;
}
public UUID getPlayer() {
return player;
}
public List<UUID> getInvitedPlayers() {
return invitedPlayers;
}
}
}
| sfm-jdbc/src/test/java/org/simpleflatmapper/jdbc/test/samples/JoinSample.java | package org.simpleflatmapper.jdbc.test.samples;
import org.junit.Test;
import org.simpleflatmapper.jdbc.JdbcColumnKey;
import org.simpleflatmapper.jdbc.JdbcMapper;
import org.simpleflatmapper.jdbc.JdbcMapperFactory;
import org.simpleflatmapper.util.ListCollector;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLType;
import java.sql.Types;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class JoinSample {
public void selectUsers() {
JdbcMapper<Object> jdbcMapper =
JdbcMapperFactory
.newInstance()
.addKeys("id", "roles_id", "phones_id")
.newMapper(Object.class);
}
@Test
public void stackOverFlowJoin() throws SQLException {
JdbcMapper<Location> mapper = JdbcMapperFactory
.newInstance()
.addKeys("player")
.newBuilder(Location.class)
.addMapping(new JdbcColumnKey("name", 1, Types.VARCHAR))
.addMapping(new JdbcColumnKey("player", 2, Types.VARCHAR))
.addMapping(new JdbcColumnKey("invited_players_player", 3, Types.VARCHAR))
.mapper();
UUID[] players = new UUID[] { UUID.randomUUID(), UUID.randomUUID()};
UUID[] invitedPlayers = new UUID[] { UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()};
String[] name = new String[] { "location1", "location2"};
ResultSet rs = mock(ResultSet.class);
when(rs.next()).thenReturn(true, true, true, false);
when(rs.getString(1)).thenReturn(name[0], name[1]);
when(rs.getString(2)).thenReturn(players[0].toString(), players[1].toString());
when(rs.getObject(2)).thenReturn(players[0].toString(),players[0].toString(),players[0].toString(), players[0].toString(), players[1].toString(), players[1].toString());
when(rs.getString(3)).thenReturn(invitedPlayers[0].toString(), invitedPlayers[1].toString(), invitedPlayers[2].toString());
List<Location> list = mapper.forEach(rs, new ListCollector<Location>()).getList();
assertEquals(2, list.size());
assertEquals("location1", list.get(0).getName());
assertEquals(players[0], list.get(0).getPlayer());
assertEquals(Arrays.asList(invitedPlayers[0], invitedPlayers[1]), list.get(0).getInvitedPlayers());
assertEquals("location2", list.get(1).getName());
assertEquals(players[1], list.get(1).getPlayer());
assertEquals(Arrays.asList(invitedPlayers[2]), list.get(1).getInvitedPlayers());
}
public static class Location {
private final String name;
private final UUID player;
private final List<UUID> invitedPlayers;
public Location(String name, UUID player, List<UUID> invitedPlayers) {
this.name = name;
this.player = player;
this.invitedPlayers = invitedPlayers;
}
public String getName() {
return name;
}
public UUID getPlayer() {
return player;
}
public List<UUID> getInvitedPlayers() {
return invitedPlayers;
}
}
}
| change column name
| sfm-jdbc/src/test/java/org/simpleflatmapper/jdbc/test/samples/JoinSample.java | change column name | |
Java | mit | 75b8e4c40f3880fb8fddddbc54879592ba155b2a | 0 | amwenger/igv,igvteam/igv,igvteam/igv,itenente/igv,igvteam/igv,godotgildor/igv,itenente/igv,itenente/igv,godotgildor/igv,amwenger/igv,godotgildor/igv,amwenger/igv,amwenger/igv,igvteam/igv,godotgildor/igv,itenente/igv,itenente/igv,igvteam/igv,godotgildor/igv,amwenger/igv | /*
* Copyright (c) 2007-2011 by The Broad Institute of MIT and Harvard. All Rights Reserved.
*
* This software is licensed under the terms of the GNU Lesser General Public License (LGPL),
* Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php.
*
* THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR
* WARRANTES OF ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER
* OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR RESPECTIVE
* TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES
* OF ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
* ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER
* THE BROAD OR MIT SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT
* SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING.
*/
package org.broad.igv.feature.tribble;
import org.apache.log4j.Logger;
import org.broad.igv.exceptions.DataLoadException;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.peaks.PeakCodec;
import org.broad.igv.util.ParsingUtils;
import org.broad.tribble.FeatureCodec;
import org.broad.tribble.util.BlockCompressedInputStream;
import org.broad.tribble.util.SeekableStreamFactory;
import org.broadinstitute.sting.utils.codecs.vcf.VCF3Codec;
import org.broadinstitute.sting.utils.codecs.vcf.VCFCodec;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* A factory class for Tribble codecs. implements a single, static, public method to return a codec given a
* path to a feature file (bed, gff, vcf, etc).
*/
public class CodecFactory {
private static Logger log = Logger.getLogger(CodecFactory.class);
/**
* Return a tribble codec to decode the supplied file.
*
* @param path the path (file or URL) to the feature rile.
*/
public static FeatureCodec getCodec(String path) {
return getCodec(path, null);
}
public static FeatureCodec getCodec(String path, Genome genome) {
String fn = path.toLowerCase();
if (fn.endsWith(".gz")) {
int l = fn.length() - 3;
fn = fn.substring(0, l);
}
if (fn.endsWith(".vcf4")) {
return new VCFWrapperCodec(new VCFCodec());
} else if (fn.endsWith(".vcf")) {
return new VCFWrapperCodec(getVCFCodec(path));
} else if (fn.endsWith(".bed")) {
return new IGVBEDCodec();
} else if (fn.contains("refflat")) {
return new UCSCGeneTableCodec(genome, UCSCGeneTableCodec.Type.REFFLAT);
} else if (fn.contains("genepred") || fn.contains("ensgene") || fn.contains("refgene")) {
return new UCSCGeneTableCodec(genome, UCSCGeneTableCodec.Type.GENEPRED);
} else if (fn.contains("ucscgene")) {
return new UCSCGeneTableCodec(genome, UCSCGeneTableCodec.Type.UCSCGENE);
} else if (fn.endsWith(".repmask")) {
return new REPMaskCodec();
} else if (fn.endsWith(".gff3") || fn.endsWith(".gvf")) {
return new GFFCodec(GFFCodec.Version.GFF3);
} else if (fn.endsWith(".gff") || fn.endsWith(".gtf")) {
return new GFFCodec();
//} else if (fn.endsWith(".sam")) {
//return new SAMCodec();
} else if (fn.endsWith(".psl") || fn.endsWith(".pslx")) {
return new PSLCodec();
} else if (fn.endsWith(".peak")) {
return new PeakCodec();
} else {
return null;
}
}
/**
* Return the appropriate VCFCodec based on the version tag.
* <p/>
* e.g. ##fileformat=VCFv4.1
*
* @param path Path to the VCF file. Can be a file path, or URL
* @return
*/
private static FeatureCodec getVCFCodec(String path) {
BufferedReader reader = null;
try {
// If the file ends with ".gz" assume it is a tabix indexed file
if (path.toLowerCase().endsWith(".gz")) {
reader = new BufferedReader(new InputStreamReader(new BlockCompressedInputStream(
ParsingUtils.openInputStream(path))));
} else {
reader = ParsingUtils.openBufferedReader(path);
}
// Look for fileformat directive. This should be the first line, but just in case check the first 20
int lineCount = 0;
String formatLine;
while ((formatLine = reader.readLine()) != null && lineCount < 20) {
if (formatLine.toLowerCase().startsWith("##fileformat")) {
String[] tmp = formatLine.split("=");
if (tmp.length > 1) {
String version = tmp[1].toLowerCase();
if (version.startsWith("vcfv3")) {
return new VCF3Codec();
} else {
return new VCFCodec();
}
}
}
lineCount++;
}
} catch (IOException e) {
log.error("Error checking VCF Version");
} finally {
if (reader != null) try {
reader.close();
} catch (IOException e) {
}
}
// Should never get here, but as a last resort assume this is a VCF 4.x file.
return new VCFCodec();
}
}
| src/org/broad/igv/feature/tribble/CodecFactory.java | /*
* Copyright (c) 2007-2011 by The Broad Institute of MIT and Harvard. All Rights Reserved.
*
* This software is licensed under the terms of the GNU Lesser General Public License (LGPL),
* Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php.
*
* THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR
* WARRANTES OF ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER
* OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR RESPECTIVE
* TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES
* OF ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
* ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER
* THE BROAD OR MIT SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT
* SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING.
*/
package org.broad.igv.feature.tribble;
import org.apache.log4j.Logger;
import org.broad.igv.exceptions.DataLoadException;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.peaks.PeakCodec;
import org.broad.igv.util.ParsingUtils;
import org.broad.tribble.FeatureCodec;
import org.broad.tribble.util.BlockCompressedInputStream;
import org.broad.tribble.util.SeekableStreamFactory;
import org.broadinstitute.sting.utils.codecs.vcf.VCF3Codec;
import org.broadinstitute.sting.utils.codecs.vcf.VCFCodec;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* A factory class for Tribble codecs. implements a single, static, public method to return a codec given a
* path to a feature file (bed, gff, vcf, etc).
*/
public class CodecFactory {
private static Logger log = Logger.getLogger(CodecFactory.class);
/**
* Return a tribble codec to decode the supplied file.
*
* @param path the path (file or URL) to the feature rile.
*/
public static FeatureCodec getCodec(String path) {
return getCodec(path, null);
}
public static FeatureCodec getCodec(String path, Genome genome) {
String fn = path.toLowerCase();
if (fn.endsWith(".gz")) {
int l = fn.length() - 3;
fn = fn.substring(0, l);
}
if (fn.endsWith(".vcf4")) {
return new VCFWrapperCodec(new VCFCodec());
} else if (fn.endsWith(".vcf")) {
return new VCFWrapperCodec(getVCFCodec(path));
} else if (fn.endsWith(".bed")) {
return new IGVBEDCodec();
} else if (fn.contains("refflat")) {
return new UCSCGeneTableCodec(genome, UCSCGeneTableCodec.Type.REFFLAT);
} else if (fn.contains("genepred") || fn.contains("ensgene") || fn.contains("refgene")) {
return new UCSCGeneTableCodec(genome, UCSCGeneTableCodec.Type.GENEPRED);
} else if (fn.contains("ucscgene")) {
return new UCSCGeneTableCodec(genome, UCSCGeneTableCodec.Type.UCSCGENE);
} else if (fn.endsWith(".repmask")) {
return new REPMaskCodec();
} else if (fn.endsWith(".gff3") || fn.endsWith(".gvf")) {
return new GFFCodec(GFFCodec.Version.GFF3);
} else if (fn.endsWith(".gff") || fn.endsWith(".gtf")) {
return new GFFCodec();
//} else if (fn.endsWith(".sam")) {
//return new SAMCodec();
} else if (fn.endsWith(".psl") || fn.endsWith(".pslx")) {
return new PSLCodec();
} else if (fn.endsWith(".peak")) {
return new PeakCodec();
} else {
return null;
}
}
/**
* Return the appropriate VCFCodec based on the version tag.
* <p/>
* e.g. ##fileformat=VCFv4.1
*
* @param path Path to the VCF file. Can be a file path, or URL
* @return
*/
private static FeatureCodec getVCFCodec(String path) {
BufferedReader reader = null;
try {
// If the file ends with ".gz" assume it is a tabix indexed file
if (path.toLowerCase().endsWith(".gz")) {
reader = new BufferedReader(new InputStreamReader(new BlockCompressedInputStream(
SeekableStreamFactory.getStreamFor(path))));
} else {
reader = ParsingUtils.openBufferedReader(path);
}
// Look for fileformat directive. This should be the first line, but just in case check the first 20
int lineCount = 0;
String formatLine;
while ((formatLine = reader.readLine()) != null && lineCount < 20) {
if (formatLine.toLowerCase().startsWith("##fileformat")) {
String[] tmp = formatLine.split("=");
if (tmp.length > 1) {
String version = tmp[1].toLowerCase();
if (version.startsWith("vcfv3")) {
return new VCF3Codec();
} else {
return new VCFCodec();
}
}
}
lineCount++;
}
} catch (IOException e) {
log.error("Error checking VCF Version");
} finally {
if (reader != null) try {
reader.close();
} catch (IOException e) {
}
}
// Should never get here, but as a last resort assume this is a VCF 4.x file.
return new VCFCodec();
}
}
| Replaced unneccessary users of SeekableStream with InputStream
git-svn-id: b5cf87c434d9ee7c8f18865e4378c9faabe04646@1812 17392f64-ead8-4cea-ae29-09b3ab513800
| src/org/broad/igv/feature/tribble/CodecFactory.java | Replaced unneccessary users of SeekableStream with InputStream | |
Java | mit | fd613aa8e162005a3f33846e8d63e825dbeb20f1 | 0 | Innovimax-SARL/mix-them | package innovimax.mixthem.operation;
import java.util.EnumSet;
/**
* <p>Describes the result of an line operation on two files.</p>
* @author Innovimax
* @version 1.0
*/
public class LineResult {
private final EnumSet<ResultType> types;
private String result;
private String readLine1;
private String readLine2;
private String keptLine1;
private String keptLine2;
/**
* Creates a line result.
*/
public LineResult() {
this.types = EnumSet.noneOf(ResultType.class);
this.result = null;
this.readLine1 = null;
this.readLine2 = null;
this.keptLine1 = null;
this.keptLine2 = null;
}
/**
* Reset the result.
*/
void reset() {
this.types.clear();
this.result = null;
}
/**
* Set the result (maybe null).
*/
void setResult(String result) {
this.result = result;
if (result != null) {
this.types.add(ResultType.HAS_RESULT);
}
}
/**
* Returns the result (maybe null).
*/
String getResult() {
return this.result;
}
/**
* Has a result ?
*/
boolean hasResult() {
return this.types.contains(ResultType.HAS_RESULT);
}
/**
* Get the first line.
*/
String getFirstLine() {
return this.keptLine1 != null ? this.keptLine1 : this.readLine1;
}
/**
* Has first line?
*/
boolean hasFirstLine() {
return getFirstLine() != null;
}
/**
* Set the first line.
*/
void setFirstLine(String line) {
this.readLine1 = line;
this.keptLine1 = null;
}
/**
* Keep previous first line and set next first line.
*/
void keepFirstLine(String line) {
this.keptLine1 = this.readLine1;
this.readLine1 = line;
}
/**
* Get the second line.
*/
String getSecondLine() {
return this.keptLine2 != null ? this.keptLine2 : this.readLine2;
}
/**
* Has second line?
*/
boolean hasSecondLine() {
return getSecondLine() != null;
}
/**
* Set the second line.
*/
void setSecondLine(String line) {
this.readLine2 = line;
this.keptLine2 = null;
}
/**
* Keep previous second line and set next second line.
*/
void keepSecondLine(String line) {
this.keptLine2 = this.readLine2;
this.readLine2 = line;
}
/**
* Preserves first file from reading (keep line)
*/
void preserveFirstLine() {
this.types.add(ResultType.PRESERVE_FIRST_LINE);
}
/**
* First line preserved ?
*/
boolean firstLinePreserved() {
return this.types.contains(ResultType.PRESERVE_FIRST_LINE);
}
/**
* Has to read first file ?
*/
boolean readingFirstFile() {
return !this.types.contains(ResultType.PRESERVE_FIRST_LINE);
}
/**
* Preserves second file from reading (keep line)
*/
void preserveSecondLine() {
this.types.add(ResultType.PRESERVE_SECOND_LINE);
}
/**
* Second line preserved ?
*/
boolean secondLinePreserved() {
return this.types.contains(ResultType.PRESERVE_SECOND_LINE);
}
/**
* Has to read second file ?
*/
boolean readingSecondFile() {
return !this.types.contains(ResultType.PRESERVE_SECOND_LINE);
}
}
| src/main/java/innovimax/mixthem/operation/LineResult.java | package innovimax.mixthem.operation;
import java.util.EnumSet;
/**
* <p>Describes the result of an line operation on two files.</p>
* @author Innovimax
* @version 1.0
*/
public class LineResult {
private final EnumSet<ResultType> types;
private String result;
private String readLine1;
private String readLine2;
private String keptLine1;
private String keptLine2;
/**
* Creates a line result.
*/
public LineResult() {
this.types = EnumSet.noneOf(ResultType.class);
this.result = null;
this.readLine1 = null;
this.readLine2 = null;
this.keptLine1 = null;
this.keptLine2 = null;
}
/**
* Reset the result.
*/
void reset() {
this.types.clear();
this.result = null;
}
/**
* Set the result (maybe null).
*/
void setResult(String result) {
this.result = result;
if (result != null) {
this.types.add(ResultType.HAS_RESULT);
}
}
/**
* Returns the result (maybe null).
*/
String getResult() {
return this.result;
}
/**
* Has a result ?
*/
boolean hasResult() {
return this.types.contains(ResultType.HAS_RESULT);
}
/**
* Get the first line.
*/
String getFirstLine() {
return this.keptLine1 != null ? this.keptLine1 : this.readLine1;
}
/**
* Has first line?
*/
boolean hasFirstLine() {
return getFirstLine() != null;
}
/**
* Set the first line.
*/
void setFirstLine(String line) {
this.readLine1 = line;
}
/**
* Keep previous first line and set next first line.
*/
void keepFirstLine(String line) {
this.keptLine1 = this.readLine1;
setFirstLine(line);
}
/**
* Get the second line.
*/
String getSecondLine() {
return this.keptLine2 != null ? this.keptLine2 : this.readLine2;
}
/**
* Has second line?
*/
boolean hasSecondLine() {
return getSecondLine() != null;
}
/**
* Set the second line.
*/
void setSecondLine(String line) {
this.readLine2 = line;
}
/**
* Keep previous second line and set next second line.
*/
void keepSecondLine(String line) {
this.keptLine2 = this.readLine2;
setSecondLine(line);
}
/**
* Preserves first file from reading (keep line)
*/
void preserveFirstLine() {
this.types.add(ResultType.PRESERVE_FIRST_LINE);
}
/**
* First line preserved ?
*/
boolean firstLinePreserved() {
return this.types.contains(ResultType.PRESERVE_FIRST_LINE);
}
/**
* Has to read first file ?
*/
boolean readingFirstFile() {
return !this.types.contains(ResultType.PRESERVE_FIRST_LINE);
}
/**
* Preserves second file from reading (keep line)
*/
void preserveSecondLine() {
this.types.add(ResultType.PRESERVE_SECOND_LINE);
}
/**
* Second line preserved ?
*/
boolean secondLinePreserved() {
return this.types.contains(ResultType.PRESERVE_SECOND_LINE);
}
/**
* Has to read second file ?
*/
boolean readingSecondFile() {
return !this.types.contains(ResultType.PRESERVE_SECOND_LINE);
}
}
| Update LineResult.java | src/main/java/innovimax/mixthem/operation/LineResult.java | Update LineResult.java | |
Java | mit | 5596c8ec813a350df49470e4bd2cd5bcb6b2a610 | 0 | codistmonk/IMJ | package imj2.tools;
import static java.awt.Color.BLUE;
import static java.awt.Color.CYAN;
import static java.awt.Color.GREEN;
import static java.awt.Color.RED;
import static java.awt.Color.YELLOW;
import static net.sourceforge.aprog.swing.SwingTools.show;
import static net.sourceforge.aprog.tools.Tools.debugPrint;
import static org.junit.Assert.*;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseWheelEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import imj2.tools.Image2DComponent.Painter;
import imj2.tools.RegionShrinkingTest.AutoMouseAdapter;
import imj2.tools.RegionShrinkingTest.SimpleImageView;
import net.sourceforge.aprog.tools.Tools;
import org.junit.Test;
/**
* @author codistmonk (creation 2014-02-07)
*/
public final class MultiresolutionSegmentationTest {
@Test
public final void test() {
final SimpleImageView imageView = new SimpleImageView();
new AutoMouseAdapter(imageView.getImageHolder()) {
private BufferedImage[] pyramid;
private int cellSize = 16;
private final Painter<SimpleImageView> painter = new Painter<SimpleImageView>() {
private Point[] particles;
{
imageView.getPainters().add(this);
}
@Override
public final void paint(final Graphics2D g, final SimpleImageView component,
final int width, final int height) {
refreshLODs();
final BufferedImage[] pyramid = getPyramid();
final int s0 = getCellSize();
final int widthLOD0 = pyramid[0].getWidth();
final int heightLOD0 = pyramid[0].getHeight();
final int horizontalParticleCount = widthLOD0 / s0;
final int verticalParticleCount = heightLOD0 / s0;
debugPrint(horizontalParticleCount, verticalParticleCount);
this.particles = new Point[horizontalParticleCount * verticalParticleCount];
final Color[] particleColors = new Color[this.particles.length];
final Color colors[] = { RED, GREEN, BLUE, YELLOW, CYAN };
for (int i = 0; i < verticalParticleCount; ++i) {
for (int j = 0; j < horizontalParticleCount; ++j) {
this.particles[i * horizontalParticleCount + j] = new Point(j * s0, i * s0);
}
}
for (int lod = pyramid.length - 1; 0 <= lod; --lod) {
final int s = s0 << lod;
final BufferedImage image = pyramid[lod];
final int w = image.getWidth();
final int h = image.getHeight();
if (s < w && s < h) {
final int d = 1 << lod;
for (int i = d; i < verticalParticleCount; i += d) {
for (int j = d; j < horizontalParticleCount; j += d) {
if (((i / d) & 1) == 1 || ((j / d) & 1) == 1) {
final int particleIndex = i * horizontalParticleCount + j;
final Point particle = this.particles[particleIndex];
particleColors[particleIndex] = colors[lod];
}
}
}
}
}
if (true) {
for (int particleIndex = 0; particleIndex < this.particles.length; ++particleIndex) {
final Point particle = this.particles[particleIndex];
g.setColor(particleColors[particleIndex]);
g.drawOval(particle.x - 1, particle.y - 1, 3, 3);
}
} else {
g.setColor(RED);
for (final Point particle : this.particles) {
g.drawOval(particle.x - 1, particle.y - 1, 3, 3);
}
}
}
/**
* {@value}.
*/
private static final long serialVersionUID = -8692596860025480748L;
};
@Override
public final void mouseWheelMoved(final MouseWheelEvent event) {
imageView.refreshBuffer();
}
public final boolean refreshLODs() {
if (this.getPyramid() == null || this.getPyramid().length == 0 || this.getPyramid()[0] != imageView.getImage()) {
this.pyramid = makePyramid(imageView.getImage());
return true;
}
return false;
}
public final BufferedImage[] getPyramid() {
return this.pyramid;
}
public final int getCellSize() {
return this.cellSize;
}
@Override
protected final void cleanup() {
imageView.getPainters().remove(this.painter);
}
/**
* {@value}.
*/
private static final long serialVersionUID = 3954986726959359787L;
};
show(imageView, "Simple Image View", true);
}
public static final BufferedImage[] makePyramid(final BufferedImage lod0) {
final List<BufferedImage> lods = new ArrayList<BufferedImage>();
BufferedImage lod = lod0;
int w = lod.getWidth();
int h = lod.getHeight();
do {
lods.add(lod);
final BufferedImage nextLOD = new BufferedImage(w /= 2, h /= 2, lod.getType());
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
final int c00 = lod.getRGB(2 * x + 0, 2 * y + 0);
final int c10 = lod.getRGB(2 * x + 1, 2 * y + 0);
final int c01 = lod.getRGB(2 * x + 0, 2 * y + 1);
final int c11 = lod.getRGB(2 * x + 1, 2 * y + 1);
nextLOD.setRGB(x, y,
mean(red(c00), red(c10), red(c01), red(c11)) |
mean(green(c00), green(c10), green(c01), green(c11)) |
mean(blue(c00), blue(c10), blue(c01), blue(c11)));
}
}
lod = nextLOD;
} while (1 < w && 1 < h);
return lods.toArray(new BufferedImage[0]);
}
public static final int red(final int rgb) {
return rgb & 0x00FF0000;
}
public static final int green(final int rgb) {
return rgb & 0x0000FF00;
}
public static final int blue(final int rgb) {
return rgb & 0x000000FF;
}
public static final int mean(final int... values) {
int sum = 0;
for (final int value : values) {
sum += value;
}
return 0 < values.length ? sum / values.length : 0;
}
}
| IMJ/test/imj2/tools/MultiresolutionSegmentationTest.java | package imj2.tools;
import static java.awt.Color.RED;
import static net.sourceforge.aprog.swing.SwingTools.show;
import static net.sourceforge.aprog.tools.Tools.debugPrint;
import static org.junit.Assert.*;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseWheelEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import imj2.tools.Image2DComponent.Painter;
import imj2.tools.RegionShrinkingTest.AutoMouseAdapter;
import imj2.tools.RegionShrinkingTest.SimpleImageView;
import net.sourceforge.aprog.tools.Tools;
import org.junit.Test;
/**
* @author codistmonk (creation 2014-02-07)
*/
public final class MultiresolutionSegmentationTest {
@Test
public final void test() {
final SimpleImageView imageView = new SimpleImageView();
new AutoMouseAdapter(imageView.getImageHolder()) {
private BufferedImage[] pyramid;
private int cellSize = 32;
private final Painter<SimpleImageView> painter = new Painter<SimpleImageView>() {
private final List<Point> particles = new ArrayList<Point>();
{
imageView.getPainters().add(this);
}
@Override
public final void paint(final Graphics2D g, final SimpleImageView component,
final int width, final int height) {
refreshLODs();
this.particles.clear();
final BufferedImage[] pyramid = getPyramid();
final int s = getCellSize();
int w = 0;
int h = 0;
for (int lod = pyramid.length - 1; 0 <= lod; --lod) {
for (final Point particle : this.particles) {
particle.x *= 2;
particle.y *= 2;
}
final BufferedImage image = pyramid[lod];
if (w == 0) {
w = image.getWidth();
h = image.getHeight();
} else {
w *= 2;
h *= 2;
}
if (s < w && s < h) {
debugPrint(lod, w, h);
for (int y = s, ky = 1; y < h; y += s, ++ky) {
for (int x = s, kx = 1; x < w; x += s, ++kx) {
if ((kx & 1) != 0 || (ky & 1) != 0) {
this.particles.add(new Point(x, y));
}
}
}
}
}
debugPrint(this.particles.size());
g.setColor(RED);
for (final Point particle : this.particles) {
g.drawOval(particle.x - 1, particle.y - 1, 3, 3);
}
}
/**
* {@value}.
*/
private static final long serialVersionUID = -8692596860025480748L;
};
@Override
public final void mouseWheelMoved(final MouseWheelEvent event) {
imageView.refreshBuffer();
}
public final boolean refreshLODs() {
if (this.getPyramid() == null || this.getPyramid().length == 0 || this.getPyramid()[0] != imageView.getImage()) {
this.pyramid = makePyramid(imageView.getImage());
return true;
}
return false;
}
public final BufferedImage[] getPyramid() {
return this.pyramid;
}
public final int getCellSize() {
return this.cellSize;
}
@Override
protected final void cleanup() {
imageView.getPainters().remove(this.painter);
}
/**
* {@value}.
*/
private static final long serialVersionUID = 3954986726959359787L;
};
show(imageView, "Simple Image View", true);
}
public static final BufferedImage[] makePyramid(final BufferedImage lod0) {
final List<BufferedImage> lods = new ArrayList<BufferedImage>();
BufferedImage lod = lod0;
int w = lod.getWidth();
int h = lod.getHeight();
do {
lods.add(lod);
final BufferedImage nextLOD = new BufferedImage(w /= 2, h /= 2, lod.getType());
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
final int c00 = lod.getRGB(2 * x + 0, 2 * y + 0);
final int c10 = lod.getRGB(2 * x + 1, 2 * y + 0);
final int c01 = lod.getRGB(2 * x + 0, 2 * y + 1);
final int c11 = lod.getRGB(2 * x + 1, 2 * y + 1);
nextLOD.setRGB(x, y,
mean(red(c00), red(c10), red(c01), red(c11)) |
mean(green(c00), green(c10), green(c01), green(c11)) |
mean(blue(c00), blue(c10), blue(c01), blue(c11)));
}
}
lod = nextLOD;
} while (1 < w && 1 < h);
return lods.toArray(new BufferedImage[0]);
}
public static final int red(final int rgb) {
return rgb & 0x00FF0000;
}
public static final int green(final int rgb) {
return rgb & 0x0000FF00;
}
public static final int blue(final int rgb) {
return rgb & 0x000000FF;
}
public static final int mean(final int... values) {
int sum = 0;
for (final int value : values) {
sum += value;
}
return 0 < values.length ? sum / values.length : 0;
}
}
| [IMJ][imj2] Updated MultiresolutionSegmentationTest.
| IMJ/test/imj2/tools/MultiresolutionSegmentationTest.java | [IMJ][imj2] Updated MultiresolutionSegmentationTest. | |
Java | mit | 9038ec2bfe86e74ed635f65f7a2bce4c199ab77c | 0 | rsandell/docker-workflow-plugin,jenkinsci/docker-workflow-plugin,rsandell/docker-workflow-plugin,jenkinsci/docker-workflow-plugin | /*
* The MIT License
*
* Copyright (c) 2017, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.docker.workflow.declarative;
import com.cloudbees.hudson.plugins.folder.Folder;
import com.cloudbees.hudson.plugins.folder.properties.FolderCredentialsProvider;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.CredentialsScope;
import com.cloudbees.plugins.credentials.CredentialsStore;
import com.cloudbees.plugins.credentials.domains.Domain;
import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl;
import hudson.ExtensionList;
import hudson.model.Slave;
import org.jenkinsci.plugins.docker.commons.credentials.DockerRegistryEndpoint;
import org.jenkinsci.plugins.docker.workflow.DockerTestUtil;
import org.jenkinsci.plugins.pipeline.modeldefinition.AbstractModelDefTest;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.junit.Assert.assertThat;
/**
* Tests {@link DeclarativeDockerUtils}.
*
* And related configurations like {@link DockerPropertiesProvider}.
*/
public class DeclarativeDockerUtilsTest extends AbstractModelDefTest {
private static final UsernamePasswordCredentialsImpl globalCred = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
"globalCreds", "sample", "bobby", "s3cr37");
private static final UsernamePasswordCredentialsImpl folderCred = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
"folderCreds", "other sample", "andrew", "s0mething");
private static final UsernamePasswordCredentialsImpl grandParentCred = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
"grandParentCreds", "yet another sample", "leopold", "idunno");
@BeforeClass
public static void setup() throws Exception {
CredentialsStore store = CredentialsProvider.lookupStores(j.jenkins).iterator().next();
store.addCredentials(Domain.global(), globalCred);
}
@Test
public void plainSystemConfig() throws Exception {
GlobalConfig.get().setDockerLabel("config_docker");
GlobalConfig.get().setRegistry(new DockerRegistryEndpoint("https://docker.registry", globalCred.getId()));
expect("org/jenkinsci/plugins/docker/workflow/declarative/declarativeDockerConfig")
.logContains("Docker Label is: config_docker",
"Registry URL is: https://docker.registry",
"Registry Creds ID is: " + globalCred.getId()).go();
}
@Test
public void testExtensionOrdinal() {
ExtensionList<DockerPropertiesProvider> all = DockerPropertiesProvider.all();
assertThat(all, hasSize(2));
assertThat(all.get(0), instanceOf(FolderConfig.FolderDockerPropertiesProvider.class));
assertThat(all.get(1), instanceOf(GlobalConfig.GlobalConfigDockerPropertiesProvider.class));
}
@Test
public void directParent() throws Exception {
Folder folder = j.createProject(Folder.class);
getFolderStore(folder).addCredentials(Domain.global(), folderCred);
folder.addProperty(new FolderConfig("folder_docker", "https://folder.registry", folderCred.getId()));
expect("org/jenkinsci/plugins/docker/workflow/declarative/declarativeDockerConfig")
.inFolder(folder)
.runFromRepo(false)
.logContains("Docker Label is: folder_docker",
"Registry URL is: https://folder.registry",
"Registry Creds ID is: " + folderCred.getId()).go();
}
@Test
public void withDefaults() throws Exception {
Folder folder = j.createProject(Folder.class);
getFolderStore(folder).addCredentials(Domain.global(), folderCred);
getFolderStore(folder).addCredentials(Domain.global(), grandParentCred);
folder.addProperty(new FolderConfig("folder_docker", "https://folder.registry", folderCred.getId()));
expect("org/jenkinsci/plugins/docker/workflow/declarative/declarativeDockerConfigWithOverride")
.inFolder(folder)
.runFromRepo(false)
.logContains("Docker Label is: other-label",
"Registry URL is: https://other.registry",
"Registry Creds ID is: " + grandParentCred.getId()).go();
}
@Test
public void directParentNotSystem() throws Exception {
GlobalConfig.get().setDockerLabel("config_docker");
GlobalConfig.get().setRegistry(new DockerRegistryEndpoint("https://docker.registry", globalCred.getId()));
Folder folder = j.createProject(Folder.class);
getFolderStore(folder).addCredentials(Domain.global(), folderCred);
folder.addProperty(new FolderConfig("folder_docker", "https://folder.registry", folderCred.getId()));
expect("org/jenkinsci/plugins/docker/workflow/declarative/declarativeDockerConfig")
.inFolder(folder)
.runFromRepo(false)
.logContains("Docker Label is: folder_docker",
"Registry URL is: https://folder.registry",
"Registry Creds ID is: " + folderCred.getId())
.logNotContains("Docker Label is: config_docker",
"Registry URL is: https://docker.registry",
"Registry Creds ID is: " + globalCred.getId()).go();
}
@Test
public void grandParent() throws Exception {
Folder grandParent = j.createProject(Folder.class);
getFolderStore(grandParent).addCredentials(Domain.global(), grandParentCred);
grandParent.addProperty(new FolderConfig("parent_docker", "https://parent.registry", grandParentCred.getId()));
Folder parent = grandParent.createProject(Folder.class, "testParent"); //Can be static since grandParent should be unique
expect("org/jenkinsci/plugins/docker/workflow/declarative/declarativeDockerConfig")
.inFolder(parent)
.runFromRepo(false)
.logContains("Docker Label is: parent_docker",
"Registry URL is: https://parent.registry",
"Registry Creds ID is: " + grandParentCred.getId()).go();
}
@Test
public void grandParentOverride() throws Exception {
Folder grandParent = j.createProject(Folder.class);
getFolderStore(grandParent).addCredentials(Domain.global(), grandParentCred);
grandParent.addProperty(new FolderConfig("parent_docker", "https://parent.registry", grandParentCred.getId()));
Folder parent = grandParent.createProject(Folder.class, "testParent"); //Can be static since grandParent should be unique
getFolderStore(parent).addCredentials(Domain.global(), folderCred);
parent.addProperty(new FolderConfig("folder_docker", "https://folder.registry", folderCred.getId()));
expect("org/jenkinsci/plugins/docker/workflow/declarative/declarativeDockerConfig")
.inFolder(parent)
.runFromRepo(false)
.logContains("Docker Label is: folder_docker",
"Registry URL is: https://folder.registry",
"Registry Creds ID is: " + folderCred.getId())
.logNotContains("Docker Label is: parent_docker",
"Registry URL is: https://parent.registry",
"Registry Creds ID is: " + grandParentCred.getId()).go();
}
@Test
public void runsOnCorrectSlave() throws Exception {
DockerTestUtil.assumeDocker();
Slave s = j.createOnlineSlave();
s.setLabelString("notthis");
env(s).put("DOCKER_INDICATOR", "WRONG").set();
s = j.createOnlineSlave();
s.setLabelString("thisone");
env(s).put("DOCKER_INDICATOR", "CORRECT").set();
GlobalConfig.get().setDockerLabel("thisone");
GlobalConfig.get().setRegistry(null);
expect("org/jenkinsci/plugins/docker/workflow/declarative/agentDockerEnvTest").runFromRepo(false).logContains("Running on assumed Docker agent").go();
}
@Test
public void runsOnSpecifiedSlave() throws Exception {
DockerTestUtil.assumeDocker();
Slave s = j.createOnlineSlave();
s.setLabelString("thisspec");
env(s).put("DOCKER_INDICATOR", "SPECIFIED").set();
s = j.createOnlineSlave();
s.setLabelString("thisone");
env(s).put("DOCKER_INDICATOR", "CORRECT").set();
GlobalConfig.get().setDockerLabel("thisone");
GlobalConfig.get().setRegistry(null);
expect("org/jenkinsci/plugins/docker/workflow/declarative/agentDockerEnvSpecLabel").runFromRepo(false).logContains("Running on assumed Docker agent").go();
}
private CredentialsStore getFolderStore(Folder f) {
Iterable<CredentialsStore> stores = CredentialsProvider.lookupStores(f);
CredentialsStore folderStore = null;
for (CredentialsStore s : stores) {
if (s.getProvider() instanceof FolderCredentialsProvider && s.getContext() == f) {
folderStore = s;
break;
}
}
return folderStore;
}
}
| src/test/java/org/jenkinsci/plugins/docker/workflow/declarative/DeclarativeDockerUtilsTest.java | /*
* The MIT License
*
* Copyright (c) 2017, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.docker.workflow.declarative;
import com.cloudbees.hudson.plugins.folder.Folder;
import com.cloudbees.hudson.plugins.folder.properties.FolderCredentialsProvider;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.CredentialsScope;
import com.cloudbees.plugins.credentials.CredentialsStore;
import com.cloudbees.plugins.credentials.domains.Domain;
import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl;
import hudson.ExtensionList;
import hudson.model.Slave;
import org.jenkinsci.plugins.docker.commons.credentials.DockerRegistryEndpoint;
import org.jenkinsci.plugins.pipeline.modeldefinition.AbstractModelDefTest;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.jenkinsci.plugins.docker.workflow.DockerTestUtil.assumeDocker;
import static org.junit.Assert.assertThat;
/**
* Tests {@link DeclarativeDockerUtils}.
*
* And related configurations like {@link DockerPropertiesProvider}.
*/
public class DeclarativeDockerUtilsTest extends AbstractModelDefTest {
private static final UsernamePasswordCredentialsImpl globalCred = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
"globalCreds", "sample", "bobby", "s3cr37");
private static final UsernamePasswordCredentialsImpl folderCred = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
"folderCreds", "other sample", "andrew", "s0mething");
private static final UsernamePasswordCredentialsImpl grandParentCred = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
"grandParentCreds", "yet another sample", "leopold", "idunno");
@BeforeClass
public static void setup() throws Exception {
CredentialsStore store = CredentialsProvider.lookupStores(j.jenkins).iterator().next();
store.addCredentials(Domain.global(), globalCred);
}
@Test
public void plainSystemConfig() throws Exception {
GlobalConfig.get().setDockerLabel("config_docker");
GlobalConfig.get().setRegistry(new DockerRegistryEndpoint("https://docker.registry", globalCred.getId()));
expect("org/jenkinsci/plugins/docker/workflow/declarative/declarativeDockerConfig")
.logContains("Docker Label is: config_docker",
"Registry URL is: https://docker.registry",
"Registry Creds ID is: " + globalCred.getId()).go();
}
@Test
public void testExtensionOrdinal() {
ExtensionList<DockerPropertiesProvider> all = DockerPropertiesProvider.all();
assertThat(all, hasSize(2));
assertThat(all.get(0), instanceOf(FolderConfig.FolderDockerPropertiesProvider.class));
assertThat(all.get(1), instanceOf(GlobalConfig.GlobalConfigDockerPropertiesProvider.class));
}
@Test
public void directParent() throws Exception {
Folder folder = j.createProject(Folder.class);
getFolderStore(folder).addCredentials(Domain.global(), folderCred);
folder.addProperty(new FolderConfig("folder_docker", "https://folder.registry", folderCred.getId()));
expect("org/jenkinsci/plugins/docker/workflow/declarative/declarativeDockerConfig")
.inFolder(folder)
.runFromRepo(false)
.logContains("Docker Label is: folder_docker",
"Registry URL is: https://folder.registry",
"Registry Creds ID is: " + folderCred.getId()).go();
}
@Test
public void withDefaults() throws Exception {
Folder folder = j.createProject(Folder.class);
getFolderStore(folder).addCredentials(Domain.global(), folderCred);
getFolderStore(folder).addCredentials(Domain.global(), grandParentCred);
folder.addProperty(new FolderConfig("folder_docker", "https://folder.registry", folderCred.getId()));
expect("org/jenkinsci/plugins/docker/workflow/declarative/declarativeDockerConfigWithOverride")
.inFolder(folder)
.runFromRepo(false)
.logContains("Docker Label is: other-label",
"Registry URL is: https://other.registry",
"Registry Creds ID is: " + grandParentCred.getId()).go();
}
@Test
public void directParentNotSystem() throws Exception {
GlobalConfig.get().setDockerLabel("config_docker");
GlobalConfig.get().setRegistry(new DockerRegistryEndpoint("https://docker.registry", globalCred.getId()));
Folder folder = j.createProject(Folder.class);
getFolderStore(folder).addCredentials(Domain.global(), folderCred);
folder.addProperty(new FolderConfig("folder_docker", "https://folder.registry", folderCred.getId()));
expect("org/jenkinsci/plugins/docker/workflow/declarative/declarativeDockerConfig")
.inFolder(folder)
.runFromRepo(false)
.logContains("Docker Label is: folder_docker",
"Registry URL is: https://folder.registry",
"Registry Creds ID is: " + folderCred.getId())
.logNotContains("Docker Label is: config_docker",
"Registry URL is: https://docker.registry",
"Registry Creds ID is: " + globalCred.getId()).go();
}
@Test
public void grandParent() throws Exception {
Folder grandParent = j.createProject(Folder.class);
getFolderStore(grandParent).addCredentials(Domain.global(), grandParentCred);
grandParent.addProperty(new FolderConfig("parent_docker", "https://parent.registry", grandParentCred.getId()));
Folder parent = grandParent.createProject(Folder.class, "testParent"); //Can be static since grandParent should be unique
expect("org/jenkinsci/plugins/docker/workflow/declarative/declarativeDockerConfig")
.inFolder(parent)
.runFromRepo(false)
.logContains("Docker Label is: parent_docker",
"Registry URL is: https://parent.registry",
"Registry Creds ID is: " + grandParentCred.getId()).go();
}
@Test
public void grandParentOverride() throws Exception {
Folder grandParent = j.createProject(Folder.class);
getFolderStore(grandParent).addCredentials(Domain.global(), grandParentCred);
grandParent.addProperty(new FolderConfig("parent_docker", "https://parent.registry", grandParentCred.getId()));
Folder parent = grandParent.createProject(Folder.class, "testParent"); //Can be static since grandParent should be unique
getFolderStore(parent).addCredentials(Domain.global(), folderCred);
parent.addProperty(new FolderConfig("folder_docker", "https://folder.registry", folderCred.getId()));
expect("org/jenkinsci/plugins/docker/workflow/declarative/declarativeDockerConfig")
.inFolder(parent)
.runFromRepo(false)
.logContains("Docker Label is: folder_docker",
"Registry URL is: https://folder.registry",
"Registry Creds ID is: " + folderCred.getId())
.logNotContains("Docker Label is: parent_docker",
"Registry URL is: https://parent.registry",
"Registry Creds ID is: " + grandParentCred.getId()).go();
}
@Test
public void runsOnCorrectSlave() throws Exception {
assumeDocker();
Slave s = j.createOnlineSlave();
s.setLabelString("notthis");
env(s).put("DOCKER_INDICATOR", "WRONG").set();
s = j.createOnlineSlave();
s.setLabelString("thisone");
env(s).put("DOCKER_INDICATOR", "CORRECT").set();
GlobalConfig.get().setDockerLabel("thisone");
GlobalConfig.get().setRegistry(null);
expect("org/jenkinsci/plugins/docker/workflow/declarative/agentDockerEnvTest").runFromRepo(false).logContains("Running on assumed Docker agent").go();
}
@Test
public void runsOnSpecifiedSlave() throws Exception {
assumeDocker();
Slave s = j.createOnlineSlave();
s.setLabelString("thisspec");
env(s).put("DOCKER_INDICATOR", "SPECIFIED").set();
s = j.createOnlineSlave();
s.setLabelString("thisone");
env(s).put("DOCKER_INDICATOR", "CORRECT").set();
GlobalConfig.get().setDockerLabel("thisone");
GlobalConfig.get().setRegistry(null);
expect("org/jenkinsci/plugins/docker/workflow/declarative/agentDockerEnvSpecLabel").runFromRepo(false).logContains("Running on assumed Docker agent").go();
}
private CredentialsStore getFolderStore(Folder f) {
Iterable<CredentialsStore> stores = CredentialsProvider.lookupStores(f);
CredentialsStore folderStore = null;
for (CredentialsStore s : stores) {
if (s.getProvider() instanceof FolderCredentialsProvider && s.getContext() == f) {
folderStore = s;
break;
}
}
return folderStore;
}
}
| Use the right assumeDocker
| src/test/java/org/jenkinsci/plugins/docker/workflow/declarative/DeclarativeDockerUtilsTest.java | Use the right assumeDocker | |
Java | mit | b678b816f4e0ea9f288cff2af528c88a48c17410 | 0 | codehaus-plexus/modello | package org.codehaus.modello.plugin.xdoc;
/*
* Copyright (c) 2004, Codehaus.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import org.codehaus.modello.ModelloException;
import org.codehaus.modello.ModelloRuntimeException;
import org.codehaus.modello.model.Model;
import org.codehaus.modello.model.ModelAssociation;
import org.codehaus.modello.model.ModelClass;
import org.codehaus.modello.model.ModelField;
import org.codehaus.modello.plugin.AbstractModelloGenerator;
import org.codehaus.modello.plugin.model.ModelClassMetadata;
import org.codehaus.modello.plugins.xml.XmlFieldMetadata;
import org.codehaus.plexus.util.xml.PrettyPrintXMLWriter;
import org.codehaus.plexus.util.xml.XMLWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;
/**
* @author <a href="mailto:jason@modello.org">Jason van Zyl</a>
* @author <a href="mailto:emmanuel@venisse.net">Emmanuel Venisse</a>
* @version $Id$
*/
public class XdocGenerator
extends AbstractModelloGenerator
{
public void generate( Model model, Properties parameters )
throws ModelloException
{
initialize( model, parameters );
try
{
generateXdoc();
}
catch ( IOException ex )
{
throw new ModelloException( "Exception while generating XDoc.", ex );
}
}
private void generateXdoc()
throws IOException
{
Model objectModel = getModel();
String directory = getOutputDirectory().getAbsolutePath();
if ( isPackageWithVersion() )
{
directory += "/" + getGeneratedVersion();
}
File f = new File( directory, objectModel.getId() + ".xml" );
if ( !f.getParentFile().exists() )
{
f.getParentFile().mkdirs();
}
FileWriter writer = new FileWriter( f );
XMLWriter w = new PrettyPrintXMLWriter( writer );
writer.write( "<?xml version=\"1.0\"?>\n" );
w.startElement( "document" );
w.startElement( "properties" );
w.startElement( "title" );
w.writeText( objectModel.getName() );
w.endElement();
w.endElement();
// Body
w.startElement( "body" );
// Descriptor with links
w.startElement( "section" );
w.addAttribute( "name", objectModel.getName() );
w.startElement( "p" );
if ( objectModel.getDescription() != null )
{
w.writeMarkup( objectModel.getDescription() );
}
else
{
w.writeText( "No description." );
}
w.endElement();
w.startElement( "source" );
StringBuffer sb = new StringBuffer();
ModelClass root = objectModel.getClass( objectModel.getRoot( getGeneratedVersion() ), getGeneratedVersion() );
sb.append( getModelClassDescriptor( objectModel, root, null, 0 ) );
w.writeMarkup( "\n" + sb );
w.endElement();
// Element descriptors
// Traverse from root so "abstract" models aren't included
writeElementDescriptor( w, objectModel, root, null, new HashSet() );
w.endElement();
w.endElement();
w.endElement();
writer.flush();
writer.close();
}
private void writeElementDescriptor( XMLWriter w, Model objectModel, ModelClass modelClass, ModelField field,
Set written )
{
written.add( modelClass );
ModelClassMetadata metadata = (ModelClassMetadata) modelClass.getMetadata( ModelClassMetadata.ID );
String tagName;
if ( metadata == null || metadata.getTagName() == null )
{
if ( field == null )
{
tagName = uncapitalise( modelClass.getName() );
}
else
{
tagName = field.getName();
if ( field instanceof ModelAssociation )
{
ModelAssociation a = (ModelAssociation) field;
if ( ModelAssociation.MANY_MULTIPLICITY.equals( a.getMultiplicity() ) )
{
tagName = singular( tagName );
}
}
}
}
else
{
tagName = metadata.getTagName();
}
if ( field != null )
{
XmlFieldMetadata fieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID );
if ( fieldMetadata != null )
{
if ( fieldMetadata.getAssociationTagName() != null )
{
tagName = fieldMetadata.getAssociationTagName();
}
else
{
if ( fieldMetadata.getTagName() != null )
{
tagName = fieldMetadata.getTagName();
}
}
}
}
w.startElement( "a" );
w.addAttribute( "name", "class_" + tagName );
w.endElement();
w.startElement( "subsection" );
w.addAttribute( "name", tagName );
w.startElement( "p" );
if ( modelClass.getDescription() != null )
{
w.writeMarkup( modelClass.getDescription() );
}
else
{
w.writeMarkup( "No description." );
}
w.endElement();
w.startElement( "table" );
w.startElement( "tr" );
w.startElement( "th" );
w.writeText( "Element" );
w.endElement();
w.startElement( "th" );
w.writeText( "Description" );
w.endElement();
w.endElement();
List fields = getFieldsForClass( objectModel, modelClass );
for ( Iterator j = fields.iterator(); j.hasNext(); )
{
ModelField f = (ModelField) j.next();
XmlFieldMetadata fieldMetadata = (XmlFieldMetadata) f.getMetadata( XmlFieldMetadata.ID );
w.startElement( "tr" );
w.startElement( "td" );
w.startElement( "code" );
boolean flatAssociation = f instanceof ModelAssociation
&& isClassInModel( ( (ModelAssociation) f ).getTo(), objectModel )
&& XmlFieldMetadata.LIST_STYLE_FLAT.equals( fieldMetadata.getListStyle() );
if ( flatAssociation )
{
ModelAssociation association = (ModelAssociation) f;
ModelClass associationModelClass = objectModel.getClass( association.getTo(), getGeneratedVersion() );
w.writeText( uncapitalise( associationModelClass.getName() ) );
}
else
{
w.writeText( f.getName() );
}
w.endElement();
w.endElement();
w.startElement( "td" );
if ( flatAssociation )
{
w.writeMarkup( "<b>List</b> " );
}
if ( f.getDescription() != null )
{
w.writeMarkup( f.getDescription() );
}
else
{
w.writeText( "No description." );
}
w.endElement();
w.endElement();
}
w.endElement();
w.endElement();
for ( Iterator iter = fields.iterator(); iter.hasNext(); )
{
ModelField f = (ModelField) iter.next();
if ( f instanceof ModelAssociation && isClassInModel( ( (ModelAssociation) f ).getTo(), objectModel ) )
{
ModelAssociation association = (ModelAssociation) f;
ModelClass fieldModelClass = objectModel.getClass( association.getTo(), getGeneratedVersion() );
if ( !written.contains( f.getName() ) )
{
writeElementDescriptor( w, objectModel, fieldModelClass, f, written );
}
}
}
}
private List getFieldsForClass( Model objectModel, ModelClass modelClass )
{
List fields = new ArrayList();
while ( modelClass != null )
{
fields.addAll( modelClass.getFields( getGeneratedVersion() ) );
String superClass = modelClass.getSuperClass();
if ( superClass != null )
{
modelClass = objectModel.getClass( superClass, getGeneratedVersion() );
}
else
{
modelClass = null;
}
}
return fields;
}
/**
* Return the child attribute fields of this class.
* @param objectModel global object model
* @param modelClass current class
* @return the list of attribute fields of this class
*/
private List getAttributeFieldsForClass( Model objectModel, ModelClass modelClass )
{
List attributeFields = new ArrayList();
while ( modelClass != null )
{
List allFields = modelClass.getFields( getGeneratedVersion() );
Iterator allFieldsIt = allFields.iterator();
while ( allFieldsIt.hasNext() )
{
ModelField field = (ModelField) allFieldsIt.next();
XmlFieldMetadata fieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID );
if ( fieldMetadata.isAttribute() )
{
attributeFields.add( field );
}
}
String superClass = modelClass.getSuperClass();
if ( superClass != null )
{
modelClass = objectModel.getClass( superClass, getGeneratedVersion() );
}
else
{
modelClass = null;
}
}
return attributeFields;
}
private String getModelClassDescriptor( Model objectModel, ModelClass modelClass, ModelField field, int depth )
throws ModelloRuntimeException
{
StringBuffer sb = new StringBuffer();
for ( int i = 0; i < depth; i++ )
{
sb.append( " " );
}
ModelClassMetadata metadata = (ModelClassMetadata) modelClass.getMetadata( ModelClassMetadata.ID );
String tagName;
if ( metadata == null || metadata.getTagName() == null )
{
if ( field == null )
{
tagName = uncapitalise( modelClass.getName() );
}
else
{
tagName = field.getName();
if ( field instanceof ModelAssociation )
{
ModelAssociation a = (ModelAssociation) field;
if ( ModelAssociation.MANY_MULTIPLICITY.equals( a.getMultiplicity() ) )
{
tagName = singular( tagName );
}
}
}
}
else
{
tagName = metadata.getTagName();
}
if ( field != null )
{
XmlFieldMetadata fieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID );
if ( fieldMetadata != null )
{
if ( fieldMetadata.getAssociationTagName() != null )
{
tagName = fieldMetadata.getAssociationTagName();
}
else
{
if ( fieldMetadata.getTagName() != null )
{
tagName = fieldMetadata.getTagName();
}
}
}
}
sb.append( "<<a href=\"#class_" ).append( tagName ).append( "\">" ).append( tagName );
sb.append( "</a>" );
List fields = getFieldsForClass( objectModel, modelClass );
List attributeFields = getAttributeFieldsForClass( objectModel, modelClass );
if ( attributeFields.size() > 0 )
{
for ( Iterator iter = attributeFields.iterator(); iter.hasNext(); )
{
ModelField f = (ModelField) iter.next();
sb.append( " " );
sb.append( uncapitalise( f.getName() ) ).append( "=.." );
}
sb.append( " " );
fields.removeAll( attributeFields );
}
if ( fields.size() > 0 )
{
sb.append( ">\n" );
for ( Iterator iter = fields.iterator(); iter.hasNext(); )
{
ModelField f = (ModelField) iter.next();
XmlFieldMetadata fieldMetadata = (XmlFieldMetadata) f.getMetadata( XmlFieldMetadata.ID );
ModelClass fieldModelClass;
if ( f instanceof ModelAssociation && isClassInModel( ( (ModelAssociation) f ).getTo(), objectModel ) )
{
ModelAssociation association = (ModelAssociation) f;
if ( XmlFieldMetadata.LIST_STYLE_FLAT.equals( fieldMetadata.getListStyle() ) )
{
fieldModelClass = objectModel.getClass( association.getTo(), getGeneratedVersion() );
sb.append( getModelClassDescriptor( objectModel, fieldModelClass, f, depth + 1 ) );
}
else
{
if ( ModelAssociation.MANY_MULTIPLICITY.equals( association.getMultiplicity() ) )
{
depth++;
for ( int i = 0; i < depth; i++ )
{
sb.append( " " );
}
sb.append( "<" ).append( uncapitalise( association.getName() ) ).append( ">\n" );
}
fieldModelClass = objectModel.getClass( association.getTo(), getGeneratedVersion() );
sb.append( getModelClassDescriptor( objectModel, fieldModelClass, f, depth + 1 ) );
if ( ModelAssociation.MANY_MULTIPLICITY.equals( association.getMultiplicity() ) )
{
for ( int i = 0; i < depth; i++ )
{
sb.append( " " );
}
sb.append( "</" ).append( uncapitalise( association.getName() ) ).append( ">\n" );
depth--;
}
}
}
else
{
for ( int i = 0; i < depth + 1; i++ )
{
sb.append( " " );
}
sb.append( "<" ).append( uncapitalise( f.getName() ) ).append( "/>\n" );
}
}
for ( int i = 0; i < depth; i++ )
{
sb.append( " " );
}
sb.append( "</" ).append( tagName ).append( ">\n" );
}
else
{
sb.append( "/>\n" );
}
return sb.toString();
}
}
| modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/XdocGenerator.java | package org.codehaus.modello.plugin.xdoc;
/*
* Copyright (c) 2004, Codehaus.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import org.codehaus.modello.ModelloException;
import org.codehaus.modello.ModelloRuntimeException;
import org.codehaus.modello.model.Model;
import org.codehaus.modello.model.ModelAssociation;
import org.codehaus.modello.model.ModelClass;
import org.codehaus.modello.model.ModelField;
import org.codehaus.modello.plugin.AbstractModelloGenerator;
import org.codehaus.modello.plugin.model.ModelClassMetadata;
import org.codehaus.modello.plugins.xml.XmlFieldMetadata;
import org.codehaus.plexus.util.xml.PrettyPrintXMLWriter;
import org.codehaus.plexus.util.xml.XMLWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;
/**
* @author <a href="mailto:jason@modello.org">Jason van Zyl</a>
* @author <a href="mailto:emmanuel@venisse.net">Emmanuel Venisse</a>
* @version $Id$
*/
public class XdocGenerator
extends AbstractModelloGenerator
{
public void generate( Model model, Properties parameters )
throws ModelloException
{
initialize( model, parameters );
try
{
generateXdoc();
}
catch ( IOException ex )
{
throw new ModelloException( "Exception while generating XDoc.", ex );
}
}
private void generateXdoc()
throws IOException
{
Model objectModel = getModel();
String directory = getOutputDirectory().getAbsolutePath();
if ( isPackageWithVersion() )
{
directory += "/" + getGeneratedVersion();
}
File f = new File( directory, objectModel.getId() + ".xml" );
if ( !f.getParentFile().exists() )
{
f.getParentFile().mkdirs();
}
FileWriter writer = new FileWriter( f );
XMLWriter w = new PrettyPrintXMLWriter( writer );
writer.write( "<?xml version=\"1.0\"?>\n" );
w.startElement( "document" );
w.startElement( "properties" );
w.startElement( "title" );
w.writeText( objectModel.getName() );
w.endElement();
w.endElement();
// Body
w.startElement( "body" );
// Descriptor with links
w.startElement( "section" );
w.addAttribute( "name", objectModel.getName() );
w.startElement( "p" );
if ( objectModel.getDescription() != null )
{
w.writeMarkup( objectModel.getDescription() );
}
else
{
w.writeText( "No description." );
}
w.endElement();
w.startElement( "source" );
StringBuffer sb = new StringBuffer();
ModelClass root = objectModel.getClass( objectModel.getRoot( getGeneratedVersion() ), getGeneratedVersion() );
sb.append( getModelClassDescriptor( objectModel, root, null, 0 ) );
w.writeMarkup( "\n" + sb );
w.endElement();
// Element descriptors
// Traverse from root so "abstract" models aren't included
writeElementDescriptor( w, objectModel, root, null, new HashSet() );
w.endElement();
w.endElement();
w.endElement();
writer.flush();
writer.close();
}
private void writeElementDescriptor( XMLWriter w, Model objectModel, ModelClass modelClass, ModelField field,
Set written )
{
written.add( modelClass );
ModelClassMetadata metadata = (ModelClassMetadata) modelClass.getMetadata( ModelClassMetadata.ID );
String tagName;
if ( metadata == null || metadata.getTagName() == null )
{
if ( field == null )
{
tagName = uncapitalise( modelClass.getName() );
}
else
{
tagName = field.getName();
if ( field instanceof ModelAssociation )
{
ModelAssociation a = (ModelAssociation) field;
if ( ModelAssociation.MANY_MULTIPLICITY.equals( a.getMultiplicity() ) )
{
tagName = singular( tagName );
}
}
}
}
else
{
tagName = metadata.getTagName();
}
if ( field != null )
{
XmlFieldMetadata fieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID );
if ( fieldMetadata != null && fieldMetadata.getTagName() != null )
{
tagName = fieldMetadata.getTagName();
}
}
w.startElement( "a" );
w.addAttribute( "name", "class_" + tagName );
w.endElement();
w.startElement( "subsection" );
w.addAttribute( "name", tagName );
w.startElement( "p" );
if ( modelClass.getDescription() != null )
{
w.writeMarkup( modelClass.getDescription() );
}
else
{
w.writeMarkup( "No description." );
}
w.endElement();
w.startElement( "table" );
w.startElement( "tr" );
w.startElement( "th" );
w.writeText( "Element" );
w.endElement();
w.startElement( "th" );
w.writeText( "Description" );
w.endElement();
w.endElement();
List fields = getFieldsForClass( objectModel, modelClass );
for ( Iterator j = fields.iterator(); j.hasNext(); )
{
ModelField f = (ModelField) j.next();
XmlFieldMetadata fieldMetadata = (XmlFieldMetadata) f.getMetadata( XmlFieldMetadata.ID );
w.startElement( "tr" );
w.startElement( "td" );
w.startElement( "code" );
boolean flatAssociation = f instanceof ModelAssociation
&& isClassInModel( ( (ModelAssociation) f ).getTo(), objectModel )
&& XmlFieldMetadata.LIST_STYLE_FLAT.equals( fieldMetadata.getListStyle() );
if ( flatAssociation )
{
ModelAssociation association = (ModelAssociation) f;
ModelClass associationModelClass = objectModel.getClass( association.getTo(), getGeneratedVersion() );
w.writeText( uncapitalise( associationModelClass.getName() ) );
}
else
{
w.writeText( f.getName() );
}
w.endElement();
w.endElement();
w.startElement( "td" );
if ( flatAssociation )
{
w.writeMarkup( "<b>List</b> " );
}
if ( f.getDescription() != null )
{
w.writeMarkup( f.getDescription() );
}
else
{
w.writeText( "No description." );
}
w.endElement();
w.endElement();
}
w.endElement();
w.endElement();
for ( Iterator iter = fields.iterator(); iter.hasNext(); )
{
ModelField f = (ModelField) iter.next();
if ( f instanceof ModelAssociation && isClassInModel( ( (ModelAssociation) f ).getTo(), objectModel ) )
{
ModelAssociation association = (ModelAssociation) f;
ModelClass fieldModelClass = objectModel.getClass( association.getTo(), getGeneratedVersion() );
if ( !written.contains( f.getName() ) )
{
writeElementDescriptor( w, objectModel, fieldModelClass, f, written );
}
}
}
}
private List getFieldsForClass( Model objectModel, ModelClass modelClass )
{
List fields = new ArrayList();
while ( modelClass != null )
{
fields.addAll( modelClass.getFields( getGeneratedVersion() ) );
String superClass = modelClass.getSuperClass();
if ( superClass != null )
{
modelClass = objectModel.getClass( superClass, getGeneratedVersion() );
}
else
{
modelClass = null;
}
}
return fields;
}
/**
* Return the child attribute fields of this class.
* @param objectModel global object model
* @param modelClass current class
* @return the list of attribute fields of this class
*/
private List getAttributeFieldsForClass( Model objectModel, ModelClass modelClass )
{
List attributeFields = new ArrayList();
while ( modelClass != null )
{
List allFields = modelClass.getFields( getGeneratedVersion() );
Iterator allFieldsIt = allFields.iterator();
while ( allFieldsIt.hasNext() )
{
ModelField field = (ModelField) allFieldsIt.next();
XmlFieldMetadata fieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID );
if ( fieldMetadata.isAttribute() )
{
attributeFields.add( field );
}
}
String superClass = modelClass.getSuperClass();
if ( superClass != null )
{
modelClass = objectModel.getClass( superClass, getGeneratedVersion() );
}
else
{
modelClass = null;
}
}
return attributeFields;
}
private String getModelClassDescriptor( Model objectModel, ModelClass modelClass, ModelField field, int depth )
throws ModelloRuntimeException
{
StringBuffer sb = new StringBuffer();
for ( int i = 0; i < depth; i++ )
{
sb.append( " " );
}
ModelClassMetadata metadata = (ModelClassMetadata) modelClass.getMetadata( ModelClassMetadata.ID );
String tagName;
if ( metadata == null || metadata.getTagName() == null )
{
if ( field == null )
{
tagName = uncapitalise( modelClass.getName() );
}
else
{
tagName = field.getName();
if ( field instanceof ModelAssociation )
{
ModelAssociation a = (ModelAssociation) field;
if ( ModelAssociation.MANY_MULTIPLICITY.equals( a.getMultiplicity() ) )
{
tagName = singular( tagName );
}
}
}
}
else
{
tagName = metadata.getTagName();
}
if ( field != null )
{
XmlFieldMetadata fieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID );
if ( fieldMetadata != null && fieldMetadata.getTagName() != null )
{
tagName = fieldMetadata.getTagName();
}
}
sb.append( "<<a href=\"#class_" ).append( tagName ).append( "\">" ).append( tagName );
sb.append( "</a>" );
List fields = getFieldsForClass( objectModel, modelClass );
List attributeFields = getAttributeFieldsForClass( objectModel, modelClass );
if ( attributeFields.size() > 0 )
{
for ( Iterator iter = attributeFields.iterator(); iter.hasNext(); )
{
ModelField f = (ModelField) iter.next();
sb.append( " " );
sb.append( uncapitalise( f.getName() ) ).append( "=.." );
}
sb.append( " " );
fields.removeAll( attributeFields );
}
if ( fields.size() > 0 )
{
sb.append( ">\n" );
for ( Iterator iter = fields.iterator(); iter.hasNext(); )
{
ModelField f = (ModelField) iter.next();
XmlFieldMetadata fieldMetadata = (XmlFieldMetadata) f.getMetadata( XmlFieldMetadata.ID );
ModelClass fieldModelClass;
if ( f instanceof ModelAssociation && isClassInModel( ( (ModelAssociation) f ).getTo(), objectModel ) )
{
ModelAssociation association = (ModelAssociation) f;
if ( XmlFieldMetadata.LIST_STYLE_FLAT.equals( fieldMetadata.getListStyle() ) )
{
fieldModelClass = objectModel.getClass( association.getTo(), getGeneratedVersion() );
sb.append( getModelClassDescriptor( objectModel, fieldModelClass, f, depth + 1 ) );
}
else
{
if ( ModelAssociation.MANY_MULTIPLICITY.equals( association.getMultiplicity() ) )
{
depth++;
for ( int i = 0; i < depth; i++ )
{
sb.append( " " );
}
sb.append( "<" ).append( uncapitalise( association.getName() ) ).append( ">\n" );
}
fieldModelClass = objectModel.getClass( association.getTo(), getGeneratedVersion() );
sb.append( getModelClassDescriptor( objectModel, fieldModelClass, f, depth + 1 ) );
if ( ModelAssociation.MANY_MULTIPLICITY.equals( association.getMultiplicity() ) )
{
for ( int i = 0; i < depth; i++ )
{
sb.append( " " );
}
sb.append( "</" ).append( uncapitalise( association.getName() ) ).append( ">\n" );
depth--;
}
}
}
else
{
for ( int i = 0; i < depth + 1; i++ )
{
sb.append( " " );
}
sb.append( "<" ).append( uncapitalise( f.getName() ) ).append( "/>\n" );
}
}
for ( int i = 0; i < depth; i++ )
{
sb.append( " " );
}
sb.append( "</" ).append( tagName ).append( ">\n" );
}
else
{
sb.append( "/>\n" );
}
return sb.toString();
}
}
| [MODELLO-54] Generate tag name instead of association tag name
Submitted by: Vincent Siveton
| modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/XdocGenerator.java | [MODELLO-54] Generate tag name instead of association tag name Submitted by: Vincent Siveton | |
Java | epl-1.0 | bdde23e35fcda692609614ac5a3dd1ed56a05e39 | 0 | opendaylight/neutron | /*
* Copyright (C) 2015 IBM, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.neutron.e2etest;
import java.io.OutputStreamWriter;
import java.lang.Thread;
import java.net.HttpURLConnection;
import java.net.URL;
import org.junit.Assert;
public class NeutronSecurityRuleTests {
String base;
public NeutronSecurityRuleTests(String base) {
this.base = base;
}
public void securityRule_collection_get_test() {
String url = base + "/security-group-rules";
ITNeutronE2E.test_fetch(url, "Security Rule Collection GET failed");
}
public void singleton_sr_create_test() {
String url = base + "/security-group-rules";
String content = " {\"security_group_rule\": " +
"{\"remote_group_id\": null, \"direction\": \"ingress\", " +
"\"remote_ip_prefix\": null, \"protocol\": \"tcp\", " +
"\"ethertype\": \"IPv6\", \"tenant_id\": " +
"\"00f340c7c3b34ab7be1fc690c05a0275\", \"port_range_max\": 77, " +
"\"port_range_min\": 77, " +
"\"id\": \"9b4be7fa-e56e-40fb-9516-1f0fa9185669\", " +
"\"security_group_id\": " +
"\"b60490fe-60a5-40be-af63-1d641381b784\"}}";
ITNeutronE2E.test_create(url, content, "Security Rule Singleton Post Failed");
}
public void sr_element_get_test() {
String url = base + "/security-group-rules/9b4be7fa-e56e-40fb-9516-1f0fa9185669";
ITNeutronE2E.test_fetch(url, true, "Security Rule Element Get Failed");
}
public void sr_delete_test() {
String url = base + "/security-group-rules/9b4be7fa-e56e-40fb-9516-1f0fa9185669";
ITNeutronE2E.test_delete(url, "Security Rule Delete Failed");
}
public void sr_element_negative_get_test() {
String url = base + "/security-group-rules/9b4be7fa-e56e-40fb-9516-1f0fa9185669";
ITNeutronE2E.test_fetch(url, false, "Security Rule Element Negative Get Failed");
}
public static void runTests(String base) {
NeutronSecurityRuleTests securityRule_tester = new NeutronSecurityRuleTests(base);
securityRule_tester.securityRule_collection_get_test();
securityRule_tester.singleton_sr_create_test();
securityRule_tester.sr_element_get_test();
securityRule_tester.sr_delete_test();
securityRule_tester.sr_element_negative_get_test();
}
}
| integration/test/src/test/java/org/opendaylight/neutron/e2etest/NeutronSecurityRuleTests.java | /*
* Copyright (C) 2015 IBM, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.neutron.e2etest;
import java.io.OutputStreamWriter;
import java.lang.Thread;
import java.net.HttpURLConnection;
import java.net.URL;
import org.junit.Assert;
public class NeutronSecurityRuleTests {
String base;
public NeutronSecurityRuleTests(String base) {
this.base = base;
}
public void securityRule_collection_get_test() {
String url = base + "/security-group-rules";
ITNeutronE2E.test_fetch(url, "Security Rule Collection GET failed");
}
public static void runTests(String base) {
NeutronSecurityRuleTests securityRule_tester = new NeutronSecurityRuleTests(base);
securityRule_tester.securityRule_collection_get_test();
}
}
| Add IT cases for Security Rules
Add missing CRUD operations to IT for Security Rules
Change-Id: I564e9cc1c4dc86c5cfaa3ce9c8addb69278f1803
Signed-off-by: Ryan Moats <7ac70bcc48c94124ee1b01a4779bf5a8a6faebbd@us.ibm.com>
| integration/test/src/test/java/org/opendaylight/neutron/e2etest/NeutronSecurityRuleTests.java | Add IT cases for Security Rules | |
Java | agpl-3.0 | 2e0d09be44608592ad1a041435bf8e0adf8993b5 | 0 | quikkian-ua-devops/will-financials,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,ua-eas/kfs,kuali/kfs,ua-eas/kfs,kuali/kfs,bhutchinson/kfs,quikkian-ua-devops/will-financials,bhutchinson/kfs,kuali/kfs,ua-eas/kfs,quikkian-ua-devops/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,smith750/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,ua-eas/kfs,quikkian-ua-devops/will-financials,smith750/kfs,UniversityOfHawaii/kfs,ua-eas/kfs,quikkian-ua-devops/kfs,bhutchinson/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,bhutchinson/kfs,UniversityOfHawaii/kfs,smith750/kfs,kkronenb/kfs,UniversityOfHawaii/kfs,ua-eas/kfs-devops-automation-fork,kkronenb/kfs,quikkian-ua-devops/will-financials,smith750/kfs,ua-eas/kfs-devops-automation-fork,kuali/kfs,kuali/kfs,UniversityOfHawaii/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,kkronenb/kfs,kkronenb/kfs | /*
* Copyright 2008 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* 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 org.kuali.kfs.sys.document.service.impl;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Stack;
import org.kuali.kfs.sys.document.service.WorkflowAttributePropertyResolutionService;
import org.kuali.rice.kew.docsearch.SearchableAttributeDateTimeValue;
import org.kuali.rice.kew.docsearch.SearchableAttributeFloatValue;
import org.kuali.rice.kew.docsearch.SearchableAttributeLongValue;
import org.kuali.rice.kew.docsearch.SearchableAttributeStringValue;
import org.kuali.rice.kew.docsearch.SearchableAttributeValue;
import org.kuali.rice.kim.bo.types.dto.AttributeSet;
import org.kuali.rice.kns.bo.BusinessObject;
import org.kuali.rice.kns.bo.PersistableBusinessObject;
import org.kuali.rice.kns.datadictionary.DocumentCollectionPath;
import org.kuali.rice.kns.datadictionary.DocumentValuePathGroup;
import org.kuali.rice.kns.datadictionary.RoutingAttribute;
import org.kuali.rice.kns.datadictionary.RoutingTypeDefinition;
import org.kuali.rice.kns.datadictionary.SearchingTypeDefinition;
import org.kuali.rice.kns.datadictionary.WorkflowAttributes;
import org.kuali.rice.kns.document.Document;
import org.kuali.rice.kns.service.PersistenceStructureService;
import org.kuali.rice.kns.util.KualiDecimal;
import org.kuali.rice.kns.util.ObjectUtils;
/**
* The default implementation of the WorkflowAttributePropertyResolutionServiceImpl
*/
public class WorkflowAttributePropertyResolutionServiceImpl implements WorkflowAttributePropertyResolutionService {
private PersistenceStructureService persistenceStructureService;
/**
* Using the proper RoutingTypeDefinition for the current routing node of the document, aardvarks out the proper routing type qualifiers
* @see org.kuali.kfs.sys.document.service.WorkflowAttributePropertyResolutionService#resolveRoutingTypeQualifiers(Document, RoutingTypeDefinition)
*/
public List<AttributeSet> resolveRoutingTypeQualifiers(Document document, RoutingTypeDefinition routingTypeDefinition) {
List<AttributeSet> qualifiers = new ArrayList<AttributeSet>();
if (routingTypeDefinition != null) {
document.populateDocumentForRouting();
RoutingAttributeTracker routingAttributeTracker = new RoutingAttributeTracker(routingTypeDefinition.getRoutingAttributes());
for (DocumentValuePathGroup documentValuePathGroup : routingTypeDefinition.getDocumentValuePathGroups()) {
qualifiers.addAll(resolveDocumentValuePath(document, documentValuePathGroup, routingAttributeTracker));
routingAttributeTracker.reset();
}
}
return qualifiers;
}
/**
* Resolves all of the values in the given DocumentValuePathGroup from the given BusinessObject
* @param businessObject the business object which is the source of values
* @param group the DocumentValuePathGroup which tells us which values we want
* @return a List of AttributeSets
*/
protected List<AttributeSet> resolveDocumentValuePath(BusinessObject businessObject, DocumentValuePathGroup group, RoutingAttributeTracker routingAttributeTracker) {
List<AttributeSet> qualifiers;
AttributeSet qualifier = new AttributeSet();
if (group.getDocumentValues() == null && group.getDocumentCollectionPath() == null) {
throw new IllegalStateException("A document value path group must have the documentValues property set, the documentCollectionPath property set, or both.");
}
if (group.getDocumentValues() != null) {
addPathValuesToQualifier(businessObject, group.getDocumentValues(), routingAttributeTracker, qualifier);
}
if (group.getDocumentCollectionPath() != null) {
qualifiers = resolveDocumentCollectionPath(businessObject, group.getDocumentCollectionPath(), routingAttributeTracker);
qualifiers = cleanCollectionQualifiers(qualifiers);
for (AttributeSet collectionElementQualifier : qualifiers) {
copyQualifications(qualifier, collectionElementQualifier);
}
} else {
qualifiers = new ArrayList<AttributeSet>();
qualifiers.add(qualifier);
}
return qualifiers;
}
/**
* Resolves document values from a collection path on a given business object
* @param businessObject the business object which has a collection, each element of which is a source of values
* @param collectionPath the information about what values to pull from each element of the collection
* @return a List of AttributeSets
*/
protected List<AttributeSet> resolveDocumentCollectionPath(BusinessObject businessObject, DocumentCollectionPath collectionPath, RoutingAttributeTracker routingAttributeTracker) {
List<AttributeSet> qualifiers = new ArrayList<AttributeSet>();
final Collection collectionByPath = getCollectionByPath(businessObject, collectionPath.getCollectionPath());
if (!ObjectUtils.isNull(collectionByPath)) {
if (collectionPath.getNestedCollection() != null) {
// we need to go through the collection...
for (Object collectionElement : collectionByPath) {
// for each element, we need to get the child qualifiers
if (collectionElement instanceof BusinessObject) {
List<AttributeSet> childQualifiers = resolveDocumentCollectionPath((BusinessObject)collectionElement, collectionPath.getNestedCollection(), routingAttributeTracker);
for (AttributeSet childQualifier : childQualifiers) {
AttributeSet qualifier = new AttributeSet();
routingAttributeTracker.checkPoint();
// now we need to get the values for the current element of the collection
addPathValuesToQualifier(collectionElement, collectionPath.getDocumentValues(), routingAttributeTracker, qualifier);
// and move all the child keys to the qualifier
copyQualifications(childQualifier, qualifier);
qualifiers.add(qualifier);
routingAttributeTracker.backUpToCheckPoint();
}
}
}
} else {
// go through each element in the collection
for (Object collectionElement : collectionByPath) {
AttributeSet qualifier = new AttributeSet();
routingAttributeTracker.checkPoint();
addPathValuesToQualifier(collectionElement, collectionPath.getDocumentValues(), routingAttributeTracker, qualifier);
qualifiers.add(qualifier);
routingAttributeTracker.backUpToCheckPoint();
}
}
}
return qualifiers;
}
/**
* Returns a collection from a path on a business object
* @param businessObject the business object to get values from
* @param collectionPath the path to that collection
* @return hopefully, a collection of objects
*/
protected Collection getCollectionByPath(BusinessObject businessObject, String collectionPath) {
return (Collection)getPropertyByPath(businessObject, collectionPath.trim());
}
/**
* Aardvarks values out of a business object and puts them into an AttributeSet, based on a List of paths
* @param businessObject the business object to get values from
* @param paths the paths of values to get from the qualifier
* @param routingAttribute the RoutingAttribute associated with this qualifier's document value
* @param currentRoutingAttributeIndex - the current index of the routing attribute
* @param qualifier the qualifier to put values into
*/
protected void addPathValuesToQualifier(Object businessObject, List<String> paths, RoutingAttributeTracker routingAttributes, AttributeSet qualifier) {
if (ObjectUtils.isNotNull(paths)) {
for (String path : paths) {
// get the values for the paths of each element of the collection
final Object value = getPropertyByPath(businessObject, path.trim());
if (value != null) {
qualifier.put(routingAttributes.getCurrentRoutingAttribute().getQualificationAttributeName(), value.toString());
}
routingAttributes.moveToNext();
}
}
}
/**
* Copies all the values from one qualifier to another
* @param source the source of values
* @param target the place to write all the values to
*/
protected void copyQualifications(AttributeSet source, AttributeSet target) {
for (String key : source.keySet()) {
target.put(key, source.get(key));
}
}
/**
* Resolves all of the searching values to index for the given document, returning a list of SearchableAttributeValue implementations
* @see org.kuali.kfs.sys.document.service.WorkflowAttributePropertyResolutionService#resolveSearchableAttributeValues(org.kuali.rice.kns.document.Document, org.kuali.rice.kns.datadictionary.WorkflowAttributes)
*/
public List<SearchableAttributeValue> resolveSearchableAttributeValues(Document document, WorkflowAttributes workflowAttributes) {
List<SearchableAttributeValue> valuesToIndex = new ArrayList<SearchableAttributeValue>();
if (workflowAttributes != null && workflowAttributes.getSearchingTypeDefinitions() != null) {
for (SearchingTypeDefinition definition : workflowAttributes.getSearchingTypeDefinitions()) {
valuesToIndex.addAll(aardvarkValuesForSearchingTypeDefinition(document, definition));
}
}
return valuesToIndex;
}
/**
* Pulls SearchableAttributeValue values from the given document for the given searchingTypeDefinition
* @param document the document to get search values from
* @param searchingTypeDefinition the current SearchingTypeDefinition to find values for
* @return a List of SearchableAttributeValue implementations
*/
protected List<SearchableAttributeValue> aardvarkValuesForSearchingTypeDefinition(Document document, SearchingTypeDefinition searchingTypeDefinition) {
List<SearchableAttributeValue> searchAttributes = new ArrayList<SearchableAttributeValue>();
final List<Object> searchValues = aardvarkSearchValuesForPaths(document, searchingTypeDefinition.getDocumentValues());
for (Object value : searchValues) {
final SearchableAttributeValue searchableAttributeValue = buildSearchableAttribute(searchingTypeDefinition.getSearchingAttribute().getAttributeName(), value);
if (searchableAttributeValue != null) {
searchAttributes.add(searchableAttributeValue);
}
}
return searchAttributes;
}
/**
* Pulls values as objects from the document for the given paths
* @param document the document to pull values from
* @param paths the property paths to pull values
* @return a List of values as Objects
*/
protected List<Object> aardvarkSearchValuesForPaths(Document document, List<String> paths) {
List<Object> searchValues = new ArrayList<Object>();
for (String path : paths) {
flatAdd(searchValues, getPropertyByPath(document, path.trim()));
}
return searchValues;
}
/**
* Removes empty AttributeSets from the given List of qualifiers
* @param qualifiers a List of AttributeSets holding qualifiers for responsibilities
* @return a cleaned up list of qualifiers
*/
protected List<AttributeSet> cleanCollectionQualifiers(List<AttributeSet> qualifiers) {
List<AttributeSet> cleanedQualifiers = new ArrayList<AttributeSet>();
for (AttributeSet qualifier : qualifiers) {
if (qualifier.size() > 0) {
cleanedQualifiers.add(qualifier);
}
}
return cleanedQualifiers;
}
/**
* Using the type of the sent in value, determines what kind of SearchableAttributeValue implementation should be passed back
* @param attributeKey
* @param value
* @return
*/
protected SearchableAttributeValue buildSearchableAttribute(String attributeKey, Object value) {
if (value == null) return null;
if (isDateLike(value)) return buildSearchableDateTimeAttribute(attributeKey, value);
if (isDecimally(value)) return buildSearchableRealAttribute(attributeKey, value);
if (isIntable(value)) return buildSearchableFixnumAttribute(attributeKey, value);
return buildSearchableStringAttribute(attributeKey, value);
}
/**
* Determines if the given value is enough like a date to store it as a SearchableAttributeDateTimeValue
* @param value the value to determine the type of
* @return true if it is like a date, false otherwise
*/
protected boolean isDateLike(Object value) {
return value instanceof java.util.Date;
}
/**
* Determines if the given value is enough like a Float to store it as a SearchableAttributeFloatValue
* @param value the value to determine of the type of
* @return true if it is like a "float", false otherwise
*/
protected boolean isDecimally(Object value) {
return value instanceof Double || value instanceof Float || value.getClass().equals(Double.TYPE) || value.getClass().equals(Float.TYPE) || value instanceof BigDecimal || value instanceof KualiDecimal;
}
/**
* Determines if the given value is enough like a "long" to store it as a SearchableAttributeLongValue
* @param value the value to determine the type of
* @return true if it is like a "long", false otherwise
*/
protected boolean isIntable(Object value) {
return value instanceof Integer || value instanceof Long || value instanceof Short || value instanceof Byte || value instanceof BigInteger || value.getClass().equals(Integer.TYPE) || value.getClass().equals(Long.TYPE) || value.getClass().equals(Short.TYPE) || value.getClass().equals(Byte.TYPE);
}
/**
* Builds a date time SearchableAttributeValue for the given key and value
* @param attributeKey the key for the searchable attribute
* @param value the value that will be coerced to date/time data
* @return the generated SearchableAttributeDateTimeValue
*/
protected SearchableAttributeDateTimeValue buildSearchableDateTimeAttribute(String attributeKey, Object value) {
SearchableAttributeDateTimeValue attribute = new SearchableAttributeDateTimeValue();
attribute.setSearchableAttributeKey(attributeKey);
attribute.setSearchableAttributeValue(new Timestamp(((java.util.Date)value).getTime()));
return attribute;
}
/**
* Builds a "float" SearchableAttributeValue for the given key and value
* @param attributeKey the key for the searchable attribute
* @param value the value that will be coerced to "float" data
* @return the generated SearchableAttributeFloatValue
*/
protected SearchableAttributeFloatValue buildSearchableRealAttribute(String attributeKey, Object value) {
SearchableAttributeFloatValue attribute = new SearchableAttributeFloatValue();
attribute.setSearchableAttributeKey(attributeKey);
if (value instanceof BigDecimal) {
attribute.setSearchableAttributeValue((BigDecimal)value);
} else if (value instanceof KualiDecimal) {
attribute.setSearchableAttributeValue(((KualiDecimal)value).bigDecimalValue());
} else {
attribute.setSearchableAttributeValue(new BigDecimal(((Number)value).doubleValue()));
}
return attribute;
}
/**
* Builds a "integer" SearchableAttributeValue for the given key and value
* @param attributeKey the key for the searchable attribute
* @param value the value that will be coerced to "integer" type data
* @return the generated SearchableAttributeLongValue
*/
protected SearchableAttributeLongValue buildSearchableFixnumAttribute(String attributeKey, Object value) {
SearchableAttributeLongValue attribute = new SearchableAttributeLongValue();
attribute.setSearchableAttributeKey(attributeKey);
attribute.setSearchableAttributeValue(new Long(((Number)value).longValue()));
return attribute;
}
/**
* Our last ditch attempt, this builds a String SearchableAttributeValue for the given key and value
* @param attributeKey the key for the searchable attribute
* @param value the value that will be coerced to a String
* @return the generated SearchableAttributeStringValue
*/
protected SearchableAttributeStringValue buildSearchableStringAttribute(String attributeKey, Object value) {
SearchableAttributeStringValue attribute = new SearchableAttributeStringValue();
attribute.setSearchableAttributeKey(attributeKey);
attribute.setSearchableAttributeValue(value.toString());
return attribute;
}
/**
* @see org.kuali.kfs.sys.document.service.WorkflowAttributePropertyResolutionService#getPropertyByPath(java.lang.Object, java.lang.String)
*/
public Object getPropertyByPath(Object object, String path) {
if (object instanceof Collection) return getPropertyOfCollectionByPath((Collection)object, path);
final String[] splitPath = headAndTailPath(path);
final String head = splitPath[0];
final String tail = splitPath[1];
if (object instanceof PersistableBusinessObject && tail != null) {
if (persistenceStructureService.hasReference(object.getClass(), head)) {
((PersistableBusinessObject)object).refreshReferenceObject(head);
}
}
final Object headValue = ObjectUtils.getPropertyValue(object, head);
if (!ObjectUtils.isNull(headValue)) {
if (tail == null) {
return headValue;
} else {
// we've still got path left...
if (headValue instanceof Collection) {
// oh dear, a collection; we've got to loop through this
Collection values = makeNewCollectionOfSameType((Collection)headValue);
for (Object currentElement : (Collection)headValue) {
flatAdd(values, getPropertyByPath(currentElement, tail));
}
return values;
} else {
return getPropertyByPath(headValue, tail);
}
}
}
return null;
}
/**
* Finds a child object, specified by the given path, on each object of the given collection
* @param collection the collection of objects
* @param path the path of the property to retrieve
* @return a Collection of the values culled from each child
*/
public Collection getPropertyOfCollectionByPath(Collection collection, String path) {
Collection values = makeNewCollectionOfSameType(collection);
for (Object o : collection) {
flatAdd(values, getPropertyByPath(o, path));
}
return values;
}
/**
* Makes a new collection of exactly the same type of the collection that was handed to it
* @param collection the collection to make a new collection of the same type as
* @return a new collection. Of the same type.
*/
public Collection makeNewCollectionOfSameType(Collection collection) {
if (collection instanceof List) return new ArrayList();
if (collection instanceof Set) return new HashSet();
try {
return collection.getClass().newInstance();
}
catch (InstantiationException ie) {
throw new RuntimeException("Couldn't instantiate class of collection we'd already instantiated??", ie);
}
catch (IllegalAccessException iae) {
throw new RuntimeException("Illegal Access on class of collection we'd already accessed??", iae);
}
}
/**
* Splits the first property off from a path, leaving the tail
* @param path the path to split
* @return an array; if the path is nested, the first element will be the first part of the path up to a "." and second element is the rest of the path while if the path is simple, returns the path as the first element and a null as the second element
*/
protected String[] headAndTailPath(String path) {
final int firstDot = path.indexOf('.');
if (firstDot < 0) {
return new String[] { path, null };
}
return new String[] { path.substring(0, firstDot), path.substring(firstDot + 1) };
}
/**
* Convenience method which makes sure that if the given object is a collection, it is added to the given collection flatly
* @param c a collection, ready to be added to
* @param o an object of dubious type
*/
protected void flatAdd(Collection c, Object o) {
if (o instanceof Collection) {
c.addAll((Collection) o);
} else {
c.add(o);
}
}
/**
* Gets the persistenceStructureService attribute.
* @return Returns the persistenceStructureService.
*/
public PersistenceStructureService getPersistenceStructureService() {
return persistenceStructureService;
}
/**
* Sets the persistenceStructureService attribute value.
* @param persistenceStructureService The persistenceStructureService to set.
*/
public void setPersistenceStructureService(PersistenceStructureService persistenceStructureService) {
this.persistenceStructureService = persistenceStructureService;
}
/**
* Inner helper class which will track which routing attributes have been used
*/
class RoutingAttributeTracker {
private List<RoutingAttribute> routingAttributes;
private int currentRoutingAttributeIndex;
private Stack<Integer> checkPoints;
/**
* Constructs a WorkflowAttributePropertyResolutionServiceImpl
* @param routingAttributes the routing attributes to track
*/
public RoutingAttributeTracker(List<RoutingAttribute> routingAttributes) {
this.routingAttributes = routingAttributes;
checkPoints = new Stack<Integer>();
}
/**
* @return the routing attribute hopefully associated with the current qualifier
*/
public RoutingAttribute getCurrentRoutingAttribute() {
return routingAttributes.get(currentRoutingAttributeIndex);
}
/**
* Moves this routing attribute tracker to its next routing attribute
*/
public void moveToNext() {
currentRoutingAttributeIndex += 1;
}
/**
* Check points at the current routing attribute, so that this position is saved
*/
public void checkPoint() {
checkPoints.push(new Integer(currentRoutingAttributeIndex));
}
/**
* Returns to the point of the last check point
*/
public void backUpToCheckPoint() {
currentRoutingAttributeIndex = checkPoints.pop().intValue();
}
/**
* Resets this RoutingAttributeTracker, setting the current RoutingAttribute back to the top one and
* clearing the check point stack
*/
public void reset() {
currentRoutingAttributeIndex = 0;
checkPoints.clear();
}
}
}
| work/src/org/kuali/kfs/sys/document/service/impl/WorkflowAttributePropertyResolutionServiceImpl.java | /*
* Copyright 2008 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* 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 org.kuali.kfs.sys.document.service.impl;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Stack;
import org.kuali.kfs.sys.document.service.WorkflowAttributePropertyResolutionService;
import org.kuali.rice.kew.docsearch.SearchableAttributeDateTimeValue;
import org.kuali.rice.kew.docsearch.SearchableAttributeFloatValue;
import org.kuali.rice.kew.docsearch.SearchableAttributeLongValue;
import org.kuali.rice.kew.docsearch.SearchableAttributeStringValue;
import org.kuali.rice.kew.docsearch.SearchableAttributeValue;
import org.kuali.rice.kim.bo.types.dto.AttributeSet;
import org.kuali.rice.kns.bo.BusinessObject;
import org.kuali.rice.kns.bo.PersistableBusinessObject;
import org.kuali.rice.kns.datadictionary.DocumentCollectionPath;
import org.kuali.rice.kns.datadictionary.DocumentValuePathGroup;
import org.kuali.rice.kns.datadictionary.RoutingAttribute;
import org.kuali.rice.kns.datadictionary.RoutingTypeDefinition;
import org.kuali.rice.kns.datadictionary.SearchingTypeDefinition;
import org.kuali.rice.kns.datadictionary.WorkflowAttributes;
import org.kuali.rice.kns.document.Document;
import org.kuali.rice.kns.service.PersistenceStructureService;
import org.kuali.rice.kns.util.KualiDecimal;
import org.kuali.rice.kns.util.ObjectUtils;
/**
* The default implementation of the WorkflowAttributePropertyResolutionServiceImpl
*/
public class WorkflowAttributePropertyResolutionServiceImpl implements WorkflowAttributePropertyResolutionService {
private PersistenceStructureService persistenceStructureService;
/**
* Using the proper RoutingTypeDefinition for the current routing node of the document, aardvarks out the proper routing type qualifiers
* @see org.kuali.kfs.sys.document.service.WorkflowAttributePropertyResolutionService#resolveRoutingTypeQualifiers(Document, RoutingTypeDefinition)
*/
public List<AttributeSet> resolveRoutingTypeQualifiers(Document document, RoutingTypeDefinition routingTypeDefinition) {
List<AttributeSet> qualifiers = new ArrayList<AttributeSet>();
if (routingTypeDefinition != null) {
document.populateDocumentForRouting();
RoutingAttributeTracker routingAttributeTracker = new RoutingAttributeTracker(routingTypeDefinition.getRoutingAttributes());
for (DocumentValuePathGroup documentValuePathGroup : routingTypeDefinition.getDocumentValuePathGroups()) {
qualifiers.addAll(resolveDocumentValuePath(document, documentValuePathGroup, routingAttributeTracker));
routingAttributeTracker.reset();
}
}
return qualifiers;
}
/**
* Resolves all of the values in the given DocumentValuePathGroup from the given BusinessObject
* @param businessObject the business object which is the source of values
* @param group the DocumentValuePathGroup which tells us which values we want
* @return a List of AttributeSets
*/
protected List<AttributeSet> resolveDocumentValuePath(BusinessObject businessObject, DocumentValuePathGroup group, RoutingAttributeTracker routingAttributeTracker) {
List<AttributeSet> qualifiers;
AttributeSet qualifier = new AttributeSet();
if (group.getDocumentValues() == null && group.getDocumentCollectionPath() == null) {
throw new IllegalStateException("A document value path group must have the documentValues property set, the documentCollectionPath property set, or both.");
}
if (group.getDocumentValues() != null) {
addPathValuesToQualifier(businessObject, group.getDocumentValues(), routingAttributeTracker, qualifier);
}
if (group.getDocumentCollectionPath() != null) {
qualifiers = resolveDocumentCollectionPath(businessObject, group.getDocumentCollectionPath(), routingAttributeTracker);
qualifiers = cleanCollectionQualifiers(qualifiers);
for (AttributeSet collectionElementQualifier : qualifiers) {
copyQualifications(qualifier, collectionElementQualifier);
}
} else {
qualifiers = new ArrayList<AttributeSet>();
qualifiers.add(qualifier);
}
return qualifiers;
}
/**
* Resolves document values from a collection path on a given business object
* @param businessObject the business object which has a collection, each element of which is a source of values
* @param collectionPath the information about what values to pull from each element of the collection
* @return a List of AttributeSets
*/
protected List<AttributeSet> resolveDocumentCollectionPath(BusinessObject businessObject, DocumentCollectionPath collectionPath, RoutingAttributeTracker routingAttributeTracker) {
List<AttributeSet> qualifiers = new ArrayList<AttributeSet>();
final Collection collectionByPath = getCollectionByPath(businessObject, collectionPath.getCollectionPath());
if (!ObjectUtils.isNull(collectionByPath)) {
if (collectionPath.getNestedCollection() != null) {
// we need to go through the collection...
for (Object collectionElement : collectionByPath) {
// for each element, we need to get the child qualifiers
if (collectionElement instanceof BusinessObject) {
List<AttributeSet> childQualifiers = resolveDocumentCollectionPath((BusinessObject)collectionElement, collectionPath.getNestedCollection(), routingAttributeTracker);
for (AttributeSet childQualifier : childQualifiers) {
AttributeSet qualifier = new AttributeSet();
routingAttributeTracker.checkPoint();
// now we need to get the values for the current element of the collection
addPathValuesToQualifier(collectionElement, collectionPath.getDocumentValues(), routingAttributeTracker, qualifier);
// and move all the child keys to the qualifier
copyQualifications(childQualifier, qualifier);
qualifiers.add(qualifier);
routingAttributeTracker.backUpToCheckPoint();
}
}
}
} else {
// go through each element in the collection
for (Object collectionElement : collectionByPath) {
AttributeSet qualifier = new AttributeSet();
routingAttributeTracker.checkPoint();
addPathValuesToQualifier(collectionElement, collectionPath.getDocumentValues(), routingAttributeTracker, qualifier);
qualifiers.add(qualifier);
routingAttributeTracker.backUpToCheckPoint();
}
}
}
return qualifiers;
}
/**
* Returns a collection from a path on a business object
* @param businessObject the business object to get values from
* @param collectionPath the path to that collection
* @return hopefully, a collection of objects
*/
protected Collection getCollectionByPath(BusinessObject businessObject, String collectionPath) {
return (Collection)getPropertyByPath(businessObject, collectionPath);
}
/**
* Aardvarks values out of a business object and puts them into an AttributeSet, based on a List of paths
* @param businessObject the business object to get values from
* @param paths the paths of values to get from the qualifier
* @param routingAttribute the RoutingAttribute associated with this qualifier's document value
* @param currentRoutingAttributeIndex - the current index of the routing attribute
* @param qualifier the qualifier to put values into
*/
protected void addPathValuesToQualifier(Object businessObject, List<String> paths, RoutingAttributeTracker routingAttributes, AttributeSet qualifier) {
if (ObjectUtils.isNotNull(paths)) {
for (String path : paths) {
// get the values for the paths of each element of the collection
final Object value = getPropertyByPath(businessObject, path);
if (value != null) {
qualifier.put(routingAttributes.getCurrentRoutingAttribute().getQualificationAttributeName(), value.toString());
}
routingAttributes.moveToNext();
}
}
}
/**
* Copies all the values from one qualifier to another
* @param source the source of values
* @param target the place to write all the values to
*/
protected void copyQualifications(AttributeSet source, AttributeSet target) {
for (String key : source.keySet()) {
target.put(key, source.get(key));
}
}
/**
* Resolves all of the searching values to index for the given document, returning a list of SearchableAttributeValue implementations
* @see org.kuali.kfs.sys.document.service.WorkflowAttributePropertyResolutionService#resolveSearchableAttributeValues(org.kuali.rice.kns.document.Document, org.kuali.rice.kns.datadictionary.WorkflowAttributes)
*/
public List<SearchableAttributeValue> resolveSearchableAttributeValues(Document document, WorkflowAttributes workflowAttributes) {
List<SearchableAttributeValue> valuesToIndex = new ArrayList<SearchableAttributeValue>();
if (workflowAttributes != null && workflowAttributes.getSearchingTypeDefinitions() != null) {
for (SearchingTypeDefinition definition : workflowAttributes.getSearchingTypeDefinitions()) {
valuesToIndex.addAll(aardvarkValuesForSearchingTypeDefinition(document, definition));
}
}
return valuesToIndex;
}
/**
* Pulls SearchableAttributeValue values from the given document for the given searchingTypeDefinition
* @param document the document to get search values from
* @param searchingTypeDefinition the current SearchingTypeDefinition to find values for
* @return a List of SearchableAttributeValue implementations
*/
protected List<SearchableAttributeValue> aardvarkValuesForSearchingTypeDefinition(Document document, SearchingTypeDefinition searchingTypeDefinition) {
List<SearchableAttributeValue> searchAttributes = new ArrayList<SearchableAttributeValue>();
final List<Object> searchValues = aardvarkSearchValuesForPaths(document, searchingTypeDefinition.getDocumentValues());
for (Object value : searchValues) {
final SearchableAttributeValue searchableAttributeValue = buildSearchableAttribute(searchingTypeDefinition.getSearchingAttribute().getAttributeName(), value);
if (searchableAttributeValue != null) {
searchAttributes.add(searchableAttributeValue);
}
}
return searchAttributes;
}
/**
* Pulls values as objects from the document for the given paths
* @param document the document to pull values from
* @param paths the property paths to pull values
* @return a List of values as Objects
*/
protected List<Object> aardvarkSearchValuesForPaths(Document document, List<String> paths) {
List<Object> searchValues = new ArrayList<Object>();
for (String path : paths) {
flatAdd(searchValues, getPropertyByPath(document, path));
}
return searchValues;
}
/**
* Removes empty AttributeSets from the given List of qualifiers
* @param qualifiers a List of AttributeSets holding qualifiers for responsibilities
* @return a cleaned up list of qualifiers
*/
protected List<AttributeSet> cleanCollectionQualifiers(List<AttributeSet> qualifiers) {
List<AttributeSet> cleanedQualifiers = new ArrayList<AttributeSet>();
for (AttributeSet qualifier : qualifiers) {
if (qualifier.size() > 0) {
cleanedQualifiers.add(qualifier);
}
}
return cleanedQualifiers;
}
/**
* Using the type of the sent in value, determines what kind of SearchableAttributeValue implementation should be passed back
* @param attributeKey
* @param value
* @return
*/
protected SearchableAttributeValue buildSearchableAttribute(String attributeKey, Object value) {
if (value == null) return null;
if (isDateLike(value)) return buildSearchableDateTimeAttribute(attributeKey, value);
if (isDecimally(value)) return buildSearchableRealAttribute(attributeKey, value);
if (isIntable(value)) return buildSearchableFixnumAttribute(attributeKey, value);
return buildSearchableStringAttribute(attributeKey, value);
}
/**
* Determines if the given value is enough like a date to store it as a SearchableAttributeDateTimeValue
* @param value the value to determine the type of
* @return true if it is like a date, false otherwise
*/
protected boolean isDateLike(Object value) {
return value instanceof java.util.Date;
}
/**
* Determines if the given value is enough like a Float to store it as a SearchableAttributeFloatValue
* @param value the value to determine of the type of
* @return true if it is like a "float", false otherwise
*/
protected boolean isDecimally(Object value) {
return value instanceof Double || value instanceof Float || value.getClass().equals(Double.TYPE) || value.getClass().equals(Float.TYPE) || value instanceof BigDecimal || value instanceof KualiDecimal;
}
/**
* Determines if the given value is enough like a "long" to store it as a SearchableAttributeLongValue
* @param value the value to determine the type of
* @return true if it is like a "long", false otherwise
*/
protected boolean isIntable(Object value) {
return value instanceof Integer || value instanceof Long || value instanceof Short || value instanceof Byte || value instanceof BigInteger || value.getClass().equals(Integer.TYPE) || value.getClass().equals(Long.TYPE) || value.getClass().equals(Short.TYPE) || value.getClass().equals(Byte.TYPE);
}
/**
* Builds a date time SearchableAttributeValue for the given key and value
* @param attributeKey the key for the searchable attribute
* @param value the value that will be coerced to date/time data
* @return the generated SearchableAttributeDateTimeValue
*/
protected SearchableAttributeDateTimeValue buildSearchableDateTimeAttribute(String attributeKey, Object value) {
SearchableAttributeDateTimeValue attribute = new SearchableAttributeDateTimeValue();
attribute.setSearchableAttributeKey(attributeKey);
attribute.setSearchableAttributeValue(new Timestamp(((java.util.Date)value).getTime()));
return attribute;
}
/**
* Builds a "float" SearchableAttributeValue for the given key and value
* @param attributeKey the key for the searchable attribute
* @param value the value that will be coerced to "float" data
* @return the generated SearchableAttributeFloatValue
*/
protected SearchableAttributeFloatValue buildSearchableRealAttribute(String attributeKey, Object value) {
SearchableAttributeFloatValue attribute = new SearchableAttributeFloatValue();
attribute.setSearchableAttributeKey(attributeKey);
if (value instanceof BigDecimal) {
attribute.setSearchableAttributeValue((BigDecimal)value);
} else if (value instanceof KualiDecimal) {
attribute.setSearchableAttributeValue(((KualiDecimal)value).bigDecimalValue());
} else {
attribute.setSearchableAttributeValue(new BigDecimal(((Number)value).doubleValue()));
}
return attribute;
}
/**
* Builds a "integer" SearchableAttributeValue for the given key and value
* @param attributeKey the key for the searchable attribute
* @param value the value that will be coerced to "integer" type data
* @return the generated SearchableAttributeLongValue
*/
protected SearchableAttributeLongValue buildSearchableFixnumAttribute(String attributeKey, Object value) {
SearchableAttributeLongValue attribute = new SearchableAttributeLongValue();
attribute.setSearchableAttributeKey(attributeKey);
attribute.setSearchableAttributeValue(new Long(((Number)value).longValue()));
return attribute;
}
/**
* Our last ditch attempt, this builds a String SearchableAttributeValue for the given key and value
* @param attributeKey the key for the searchable attribute
* @param value the value that will be coerced to a String
* @return the generated SearchableAttributeStringValue
*/
protected SearchableAttributeStringValue buildSearchableStringAttribute(String attributeKey, Object value) {
SearchableAttributeStringValue attribute = new SearchableAttributeStringValue();
attribute.setSearchableAttributeKey(attributeKey);
attribute.setSearchableAttributeValue(value.toString());
return attribute;
}
/**
* @see org.kuali.kfs.sys.document.service.WorkflowAttributePropertyResolutionService#getPropertyByPath(java.lang.Object, java.lang.String)
*/
public Object getPropertyByPath(Object object, String path) {
if (object instanceof Collection) return getPropertyOfCollectionByPath((Collection)object, path);
path = path.trim();
final String[] splitPath = headAndTailPath(path);
final String head = splitPath[0];
final String tail = splitPath[1];
if (object instanceof PersistableBusinessObject && tail != null) {
if (persistenceStructureService.hasReference(object.getClass(), head)) {
((PersistableBusinessObject)object).refreshReferenceObject(head);
}
}
final Object headValue = ObjectUtils.getPropertyValue(object, head);
if (!ObjectUtils.isNull(headValue)) {
if (tail == null) {
return headValue;
} else {
// we've still got path left...
if (headValue instanceof Collection) {
// oh dear, a collection; we've got to loop through this
Collection values = makeNewCollectionOfSameType((Collection)headValue);
for (Object currentElement : (Collection)headValue) {
flatAdd(values, getPropertyByPath(currentElement, tail));
}
return values;
} else {
return getPropertyByPath(headValue, tail);
}
}
}
return null;
}
/**
* Finds a child object, specified by the given path, on each object of the given collection
* @param collection the collection of objects
* @param path the path of the property to retrieve
* @return a Collection of the values culled from each child
*/
public Collection getPropertyOfCollectionByPath(Collection collection, String path) {
Collection values = makeNewCollectionOfSameType(collection);
for (Object o : collection) {
flatAdd(values, getPropertyByPath(o, path));
}
return values;
}
/**
* Makes a new collection of exactly the same type of the collection that was handed to it
* @param collection the collection to make a new collection of the same type as
* @return a new collection. Of the same type.
*/
public Collection makeNewCollectionOfSameType(Collection collection) {
if (collection instanceof List) return new ArrayList();
if (collection instanceof Set) return new HashSet();
try {
return collection.getClass().newInstance();
}
catch (InstantiationException ie) {
throw new RuntimeException("Couldn't instantiate class of collection we'd already instantiated??", ie);
}
catch (IllegalAccessException iae) {
throw new RuntimeException("Illegal Access on class of collection we'd already accessed??", iae);
}
}
/**
* Splits the first property off from a path, leaving the tail
* @param path the path to split
* @return an array; if the path is nested, the first element will be the first part of the path up to a "." and second element is the rest of the path while if the path is simple, returns the path as the first element and a null as the second element
*/
protected String[] headAndTailPath(String path) {
final int firstDot = path.indexOf('.');
if (firstDot < 0) {
return new String[] { path, null };
}
return new String[] { path.substring(0, firstDot), path.substring(firstDot + 1) };
}
/**
* Convenience method which makes sure that if the given object is a collection, it is added to the given collection flatly
* @param c a collection, ready to be added to
* @param o an object of dubious type
*/
protected void flatAdd(Collection c, Object o) {
if (o instanceof Collection) {
c.addAll((Collection) o);
} else {
c.add(o);
}
}
/**
* Gets the persistenceStructureService attribute.
* @return Returns the persistenceStructureService.
*/
public PersistenceStructureService getPersistenceStructureService() {
return persistenceStructureService;
}
/**
* Sets the persistenceStructureService attribute value.
* @param persistenceStructureService The persistenceStructureService to set.
*/
public void setPersistenceStructureService(PersistenceStructureService persistenceStructureService) {
this.persistenceStructureService = persistenceStructureService;
}
/**
* Inner helper class which will track which routing attributes have been used
*/
class RoutingAttributeTracker {
private List<RoutingAttribute> routingAttributes;
private int currentRoutingAttributeIndex;
private Stack<Integer> checkPoints;
/**
* Constructs a WorkflowAttributePropertyResolutionServiceImpl
* @param routingAttributes the routing attributes to track
*/
public RoutingAttributeTracker(List<RoutingAttribute> routingAttributes) {
this.routingAttributes = routingAttributes;
checkPoints = new Stack<Integer>();
}
/**
* @return the routing attribute hopefully associated with the current qualifier
*/
public RoutingAttribute getCurrentRoutingAttribute() {
return routingAttributes.get(currentRoutingAttributeIndex);
}
/**
* Moves this routing attribute tracker to its next routing attribute
*/
public void moveToNext() {
currentRoutingAttributeIndex += 1;
}
/**
* Check points at the current routing attribute, so that this position is saved
*/
public void checkPoint() {
checkPoints.push(new Integer(currentRoutingAttributeIndex));
}
/**
* Returns to the point of the last check point
*/
public void backUpToCheckPoint() {
currentRoutingAttributeIndex = checkPoints.pop().intValue();
}
/**
* Resets this RoutingAttributeTracker, setting the current RoutingAttribute back to the top one and
* clearing the check point stack
*/
public void reset() {
currentRoutingAttributeIndex = 0;
checkPoints.clear();
}
}
}
| let's try to avoid trimming when we're in the recursion...
| work/src/org/kuali/kfs/sys/document/service/impl/WorkflowAttributePropertyResolutionServiceImpl.java | let's try to avoid trimming when we're in the recursion... | |
Java | agpl-3.0 | cda48d4d0c93fae253160b9d255ca54aaa57333b | 0 | Stanwar/agreementmaker,sabarish14/agreementmaker,Stanwar/agreementmaker,sabarish14/agreementmaker,sabarish14/agreementmaker,sabarish14/agreementmaker,Stanwar/agreementmaker,Stanwar/agreementmaker | package am.app.feedback;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Iterator;
import am.app.Core;
import am.app.feedback.CandidateConcept.ontology;
import am.app.feedback.measures.FamilialSimilarity;
import am.app.feedback.measures.RelevanceMeasure;
import am.app.feedback.measures.Specificity;
import am.app.mappingEngine.Alignment;
import am.app.mappingEngine.AlignmentSet;
import am.app.mappingEngine.AbstractMatcher.alignType;
import am.app.ontology.Node;
import am.app.ontology.Ontology;
public class CandidateSelection {
// relevance measures
public enum MeasuresRegistry {
FamilialSimilarity ( FamilialSimilarity.class ),
Specificity ( Specificity.class )
;
private String measure;
MeasuresRegistry( Class<?> classname ) { measure = classname.getName(); }
public String getMeasureClass() { return measure; }
}
ArrayList<RelevanceMeasure> measures;
ArrayList<ConceptList> relevanceLists;
FeedbackLoop fbL;
public CandidateSelection(FeedbackLoop feedbackLoop) {
fbL = feedbackLoop;
}
// create and run all the relevance measures
public void runMeasures() {
measures = new ArrayList<RelevanceMeasure>();
EnumSet<MeasuresRegistry> mrs = EnumSet.allOf(MeasuresRegistry.class);
Iterator<MeasuresRegistry> mi = mrs.iterator();
while( mi.hasNext() ) {
RelevanceMeasure m = getMeasureInstance( mi.next() );
if( m != null ) {
m.calculateRelevances();
measures.add(m);
}
}
return;
}
public AlignmentSet<Alignment> getCandidateAlignments( int k, int m ) {
relevanceLists = new ArrayList<ConceptList>();
// get the ConceptList from each relevance measure
Iterator<RelevanceMeasure> m1 = measures.iterator();
while( m1.hasNext() ) {
relevanceLists.add( m1.next().getRelevances() );
}
double totalSpread = 0.00d;
// calculate the total spread
Iterator<ConceptList> itrRL = relevanceLists.iterator();
while( itrRL.hasNext() ) {
totalSpread += itrRL.next().getSpread();
}
// set the weights
itrRL = relevanceLists.iterator();
while( itrRL.hasNext() ) {
itrRL.next().setWeight(totalSpread);
}
// now, do a linear combination of all the measures for each element in the ontologies
Ontology s = Core.getInstance().getSourceOntology();
Ontology t = Core.getInstance().getSourceOntology();
ArrayList<CandidateConcept> masterList = new ArrayList<CandidateConcept>();
ArrayList<Node> list = s.getClassesList();
masterList.addAll( getCombinedRelevances( list, CandidateConcept.ontology.source, alignType.aligningClasses ) );
list = s.getPropertiesList();
masterList.addAll( getCombinedRelevances(list, CandidateConcept.ontology.source, alignType.aligningProperties));
list = t.getClassesList();
masterList.addAll( getCombinedRelevances( list, CandidateConcept.ontology.target, alignType.aligningClasses ) );
list = t.getPropertiesList();
masterList.addAll( getCombinedRelevances(list, CandidateConcept.ontology.target, alignType.aligningProperties) );
// we now have the masterList, sort it.
Collections.sort( masterList );
ArrayList<CandidateConcept> topK = new ArrayList<CandidateConcept>();
if(masterList.size() < k){
topK.addAll( masterList);
}
else{
topK.addAll( masterList.subList(0, k) );
}
System.out.println("Candidate Selection: Top K CandidateConcepts:");
for( int ii = 0; ii < topK.size(); ii++ ) {
System.out.println( " " + Integer.toString(ii) + topK.get(ii).toString() );
}
Collections.sort(topK);
// we have the topK, now convert the concepts to mappings
AlignmentSet<Alignment> topMappings = new AlignmentSet<Alignment>();
Iterator<CandidateConcept> itr1 = topK.iterator();
while( itr1.hasNext() ) {
CandidateConcept top1 = itr1.next();
Alignment[] topM = null;
if( top1.isType( alignType.aligningClasses ) ) {
// we're looking in the classes matrix
if( top1.isOntology( CandidateConcept.ontology.source ) ) {
// source concept
topM = fbL.getClassesMatrix().getRowMaxValues( top1.getIndex(), m);
}
else {
// target concept
topM = fbL.getClassesMatrix().getColMaxValues( top1.getIndex(), m);
}
if( topM != null ) {
for( int i1 = 0; i1 < topM.length; i1++ ) {
if( topM[i1] != null ) topM[i1].setAlignmentType( alignType.aligningClasses );
}
}
}
else {
// we're looking in the properties matrix
if( top1.isOntology( CandidateConcept.ontology.source ) ) {
// source concept
topM = fbL.getPropertiesMatrix().getRowMaxValues( top1.getIndex(), m);
}
else {
// target concept
topM = fbL.getPropertiesMatrix().getColMaxValues( top1.getIndex(), m);
}
if( topM != null ) {
for( int i1 = 0; i1 < topM.length; i1++ ) {
if( topM[i1] != null ) topM[i1].setAlignmentType( alignType.aligningProperties );
}
}
};
if( topM != null ) {
for( int i1 = 0; i1 < m; i1++ ) {
if( topM[i1] != null && topM[i1].getSimilarity() != -1 ) topMappings.addAlignment( topM[i1]);
}
};
};
return topMappings;
}
private ArrayList<CandidateConcept> getCombinedRelevances(ArrayList<Node> list, ontology source, alignType type) {
ArrayList<CandidateConcept> subList = new ArrayList<CandidateConcept>();
Iterator<Node> nodeItr = list.iterator();
double combinedRelevance = 0.00d;
while( nodeItr.hasNext() ) {
Node currentNode = nodeItr.next();
Iterator<ConceptList> cl = relevanceLists.iterator();
while( cl.hasNext() ) {
ConceptList currentList = cl.next();
combinedRelevance += currentList.getWeight() * currentList.getRelevance( currentNode, source, type );
}
if( combinedRelevance > 0.00d ) {
subList.add( new CandidateConcept( currentNode, combinedRelevance, source, type));
}
}
return subList;
}
public AlignmentSet<ExtendedAlignment> getCurrentAlignments() {
// TODO Auto-generated method stub
return null;
}
// get a new measure instance given the MeasuresRegistry
private RelevanceMeasure getMeasureInstance(MeasuresRegistry name ) {
Class<?> measureClass = null;
try {
measureClass = Class.forName( name.getMeasureClass() );
} catch (ClassNotFoundException e) {
System.out.println("DEVELOPER: You have entered a wrong class name in the MeasuresRegistry");
e.printStackTrace();
return null;
}
RelevanceMeasure a = null;
try {
a = (RelevanceMeasure) measureClass.newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
a.setName(name);
a.setFeedbackLoop(fbL);
return a;
}
}
| AgreementMaker/src/am/app/feedback/CandidateSelection.java | package am.app.feedback;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Iterator;
import am.app.Core;
import am.app.feedback.CandidateConcept.ontology;
import am.app.feedback.measures.FamilialSimilarity;
import am.app.feedback.measures.RelevanceMeasure;
import am.app.feedback.measures.Specificity;
import am.app.mappingEngine.Alignment;
import am.app.mappingEngine.AlignmentSet;
import am.app.mappingEngine.AbstractMatcher.alignType;
import am.app.ontology.Node;
import am.app.ontology.Ontology;
public class CandidateSelection {
// relevance measures
public enum MeasuresRegistry {
FamilialSimilarity ( FamilialSimilarity.class ),
//Specificity ( Specificity.class )
;
private String measure;
MeasuresRegistry( Class<?> classname ) { measure = classname.getName(); }
public String getMeasureClass() { return measure; }
}
ArrayList<RelevanceMeasure> measures;
ArrayList<ConceptList> relevanceLists;
FeedbackLoop fbL;
public CandidateSelection(FeedbackLoop feedbackLoop) {
fbL = feedbackLoop;
}
// create and run all the relevance measures
public void runMeasures() {
measures = new ArrayList<RelevanceMeasure>();
EnumSet<MeasuresRegistry> mrs = EnumSet.allOf(MeasuresRegistry.class);
Iterator<MeasuresRegistry> mi = mrs.iterator();
while( mi.hasNext() ) {
RelevanceMeasure m = getMeasureInstance( mi.next() );
if( m != null ) {
m.calculateRelevances();
measures.add(m);
}
}
return;
}
public AlignmentSet<Alignment> getCandidateAlignments( int k, int m ) {
relevanceLists = new ArrayList<ConceptList>();
// get the ConceptList from each relevance measure
Iterator<RelevanceMeasure> m1 = measures.iterator();
while( m1.hasNext() ) {
relevanceLists.add( m1.next().getRelevances() );
}
double totalSpread = 0.00d;
// calculate the total spread
Iterator<ConceptList> itrRL = relevanceLists.iterator();
while( itrRL.hasNext() ) {
totalSpread += itrRL.next().getSpread();
}
// set the weights
itrRL = relevanceLists.iterator();
while( itrRL.hasNext() ) {
itrRL.next().setWeight(totalSpread);
}
// now, do a linear combination of all the measures for each element in the ontologies
Ontology s = Core.getInstance().getSourceOntology();
Ontology t = Core.getInstance().getSourceOntology();
ArrayList<CandidateConcept> masterList = new ArrayList<CandidateConcept>();
ArrayList<Node> list = s.getClassesList();
masterList.addAll( getCombinedRelevances( list, CandidateConcept.ontology.source, alignType.aligningClasses ) );
list = s.getPropertiesList();
masterList.addAll( getCombinedRelevances(list, CandidateConcept.ontology.source, alignType.aligningProperties));
list = t.getClassesList();
masterList.addAll( getCombinedRelevances( list, CandidateConcept.ontology.target, alignType.aligningClasses ) );
list = t.getPropertiesList();
masterList.addAll( getCombinedRelevances(list, CandidateConcept.ontology.target, alignType.aligningProperties) );
// we now have the masterList, sort it.
Collections.sort( masterList );
ArrayList<CandidateConcept> topK = new ArrayList<CandidateConcept>();
if(masterList.size() < k){
topK.addAll( masterList);
}
else{
topK.addAll( masterList.subList(0, k) );
}
Collections.sort(topK);
// we have the topK, now convert the concepts to mappings
AlignmentSet<Alignment> topMappings = new AlignmentSet<Alignment>();
Iterator<CandidateConcept> itr1 = topK.iterator();
while( itr1.hasNext() ) {
CandidateConcept top1 = itr1.next();
Alignment[] topM = null;
if( top1.isType( alignType.aligningClasses ) ) {
// we're looking in the classes matrix
if( top1.isOntology( CandidateConcept.ontology.source ) ) {
// source concept
topM = fbL.getClassesMatrix().getRowMaxValues( top1.getIndex(), m);
}
else {
// target concept
topM = fbL.getClassesMatrix().getColMaxValues( top1.getIndex(), m);
}
if( topM != null ) {
for( int i1 = 0; i1 < topM.length; i1++ ) {
if( topM[i1] != null ) topM[i1].setAlignmentType( alignType.aligningClasses );
}
}
}
else {
// we're looking in the properties matrix
if( top1.isOntology( CandidateConcept.ontology.source ) ) {
// source concept
topM = fbL.getPropertiesMatrix().getRowMaxValues( top1.getIndex(), m);
}
else {
// target concept
topM = fbL.getPropertiesMatrix().getColMaxValues( top1.getIndex(), m);
}
if( topM != null ) {
for( int i1 = 0; i1 < topM.length; i1++ ) {
if( topM[i1] != null ) topM[i1].setAlignmentType( alignType.aligningProperties );
}
}
};
if( topM != null ) {
for( int i1 = 0; i1 < m; i1++ ) {
if( topM[i1] != null && topM[i1].getSimilarity() != -1 ) topMappings.addAlignment( topM[i1]);
}
};
};
return topMappings;
}
private ArrayList<CandidateConcept> getCombinedRelevances(ArrayList<Node> list, ontology source, alignType type) {
ArrayList<CandidateConcept> subList = new ArrayList<CandidateConcept>();
Iterator<Node> nodeItr = list.iterator();
double combinedRelevance = 0.00d;
while( nodeItr.hasNext() ) {
Node currentNode = nodeItr.next();
Iterator<ConceptList> cl = relevanceLists.iterator();
while( cl.hasNext() ) {
ConceptList currentList = cl.next();
combinedRelevance += currentList.getWeight() * currentList.getRelevance( currentNode, source, type );
}
if( combinedRelevance > 0.00d ) {
subList.add( new CandidateConcept( currentNode, combinedRelevance, source, type));
}
}
return subList;
}
public AlignmentSet<ExtendedAlignment> getCurrentAlignments() {
// TODO Auto-generated method stub
return null;
}
// get a new measure instance given the MeasuresRegistry
private RelevanceMeasure getMeasureInstance(MeasuresRegistry name ) {
Class<?> measureClass = null;
try {
measureClass = Class.forName( name.getMeasureClass() );
} catch (ClassNotFoundException e) {
System.out.println("DEVELOPER: You have entered a wrong class name in the MeasuresRegistry");
e.printStackTrace();
return null;
}
RelevanceMeasure a = null;
try {
a = (RelevanceMeasure) measureClass.newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
a.setName(name);
a.setFeedbackLoop(fbL);
return a;
}
}
| Show what's in the top K everytime.
| AgreementMaker/src/am/app/feedback/CandidateSelection.java | Show what's in the top K everytime. | |
Java | lgpl-2.1 | 8c23fed7eb633a7052a12f15adfaa419d0a358fc | 0 | evlist/orbeon-forms,evlist/orbeon-forms,orbeon/orbeon-forms,brunobuzzi/orbeon-forms,orbeon/orbeon-forms,wesley1001/orbeon-forms,evlist/orbeon-forms,joansmith/orbeon-forms,ajw625/orbeon-forms,joansmith/orbeon-forms,ajw625/orbeon-forms,martinluther/orbeon-forms,martinluther/orbeon-forms,ajw625/orbeon-forms,orbeon/orbeon-forms,martinluther/orbeon-forms,wesley1001/orbeon-forms,wesley1001/orbeon-forms,ajw625/orbeon-forms,orbeon/orbeon-forms,tanbo800/orbeon-forms,brunobuzzi/orbeon-forms,wesley1001/orbeon-forms,evlist/orbeon-forms,joansmith/orbeon-forms,martinluther/orbeon-forms,tanbo800/orbeon-forms,tanbo800/orbeon-forms,joansmith/orbeon-forms,evlist/orbeon-forms,tanbo800/orbeon-forms,brunobuzzi/orbeon-forms,brunobuzzi/orbeon-forms | /**
* Copyright (C) 2004 Orbeon, Inc.
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU Lesser General Public License as published by the Free Software Foundation; either version
* 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
*/
package org.orbeon.oxf.processor.serializer.legacy;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.jfree.chart.*;
import org.jfree.chart.axis.*;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.*;
import org.jfree.chart.renderer.AbstractRenderer;
import org.jfree.chart.renderer.category.*;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.chart.title.LegendTitle;
import org.jfree.data.Range;
import org.jfree.data.xy.*;
import org.jfree.data.time.*;
import org.jfree.data.general.*;
import org.jfree.data.category.*;
import org.orbeon.oxf.common.OXFException;
import org.orbeon.oxf.pipeline.api.PipelineContext;
import org.orbeon.oxf.processor.ProcessorInput;
import org.orbeon.oxf.processor.ProcessorInputOutputInfo;
import org.orbeon.oxf.processor.serializer.HttpBinarySerializer;
import org.orbeon.oxf.xml.XPathUtils;
import java.awt.*;
import java.awt.font.LineMetrics;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.text.SimpleDateFormat;
import org.jfree.chart.block.BlockFrame;
import org.jfree.ui.RectangleEdge;
import org.jfree.ui.RectangleInsets;
import org.jfree.chart.labels.StandardXYItemLabelGenerator;
public class JFreeChartSerializer extends HttpBinarySerializer {
public static final String CHART_CONVERTER_CHART_NAMESPACE_URI = "http://www.orbeon.com/oxf/converter/chart-chart";
public static String DEFAULT_CONTENT_TYPE = "image/png";
public static final String INPUT_CHART = "chart";
public static final Color DEFAULT_BACKGROUND_COLOR = getRGBColor("#FFFFFF");
public static final Color DEFAULT_TITLE_COLOR = getRGBColor("#000000");
public JFreeChartSerializer() {
addInputInfo(new ProcessorInputOutputInfo(INPUT_CHART, CHART_CONVERTER_CHART_NAMESPACE_URI));
}
protected String getDefaultContentType() {
return DEFAULT_CONTENT_TYPE;
}
protected void readInput(PipelineContext pipelineContext, ProcessorInput input, Config config, OutputStream outputStream) {
try {
ChartConfig chartConfig = (ChartConfig) readCacheInputAsObject(pipelineContext, getInputByName(INPUT_CHART),
new org.orbeon.oxf.processor.CacheableInputReader() {
public Object read(org.orbeon.oxf.pipeline.api.PipelineContext context, org.orbeon.oxf.processor.ProcessorInput input) {
return createChartConfig(context, input);
}
});
Document data = readInputAsDOM4J(pipelineContext, (input != null) ? input : getInputByName(INPUT_DATA));
Dataset ds;
if (chartConfig.getType() == ChartConfig.PIE_TYPE ||
chartConfig.getType() == ChartConfig.PIE3D_TYPE)
ds = createPieDataset(chartConfig, data);
else if(chartConfig.getType() == ChartConfig.XY_LINE_TYPE)
ds = createXYDataset(chartConfig, data);
else if(chartConfig.getType() == ChartConfig.TIME_SERIES_TYPE)
ds = createTimeSeriesDataset(chartConfig, data);
else
ds = createDataset(chartConfig, data);
JFreeChart chart = drawChart(chartConfig, ds);
ChartRenderingInfo info = new ChartRenderingInfo();
ChartUtilities.writeChartAsPNG(outputStream, chart, chartConfig.getxSize(), chartConfig.getySize(), info, true, 5);
} catch (Exception e) {
throw new OXFException(e);
}
}
protected PieDataset createPieDataset(ChartConfig chartConfig, Document data) {
ExtendedPieDataset ds = new ExtendedPieDataset();
Value value = (Value) chartConfig.getValueIterator().next();
Iterator cats = XPathUtils.selectIterator(data, value.getCategories());
Iterator series = XPathUtils.selectIterator(data, value.getSeries());
Iterator colors = null;
if (value.getColors() != null)
colors = XPathUtils.selectIterator(data, value.getColors());
Iterator explodedPercents = null;
if (value.getExplodedPercents() != null)
explodedPercents = XPathUtils.selectIterator(data, value.getExplodedPercents());
while (cats.hasNext() && series.hasNext()) {
Element s = (Element) series.next();
Element c = (Element) cats.next();
Double d = new Double(s.getText().trim());
Paint p = null;
double ep = 0;
if (colors != null) {
Element col = (Element) colors.next();
p = getRGBColor(col.getText());
}
if (explodedPercents != null) {
Element e = (Element) explodedPercents.next();
ep = Double.parseDouble(e.getText());
}
ds.setValue(c.getText(), d, p, ep);
}
return ds;
}
protected CategoryDataset createDataset(ChartConfig chartConfig, Document data) {
ItemPaintCategoryDataset ds = new ItemPaintCategoryDataset();
for (Iterator i = chartConfig.getValueIterator(); i.hasNext();) {
Value value = (Value) i.next();
Iterator cats = XPathUtils.selectIterator(data, value.getCategories());
Iterator series = XPathUtils.selectIterator(data, value.getSeries());
Iterator colors = null;
if (value.getColors() != null)
colors = XPathUtils.selectIterator(data, value.getColors());
while (cats.hasNext() && series.hasNext()) {
Node s = (Node) series.next();
Node c = (Node) cats.next();
Double d = new Double(s.getStringValue());
if (colors != null) {
Node col = (Node) colors.next();
Color color = getRGBColor(col.getStringValue());
ds.addValue(d, color, value.getTitle(), c.getStringValue());
} else
ds.addValue(d, value.getTitle(), c.getStringValue());
}
}
return ds;
}
protected XYSeriesCollection createXYDataset(ChartConfig chartConfig, Document data) {
XYSeriesCollection ds = new XYSeriesCollection();
for (Iterator i = chartConfig.getValueIterator(); i.hasNext();) {
Value value = (Value) i.next();
String title = value.getTitle();
Iterator x = XPathUtils.selectIterator(data, value.getCategories());
Iterator y = XPathUtils.selectIterator(data, value.getSeries());
XYSeries xyseries = new XYSeries(title);
while (x.hasNext() && y.hasNext()) {
Node s = (Node) y.next();
Node c = (Node) x.next();
Double abcissa = new Double(c.getStringValue());
Double ordinate = new Double(s.getStringValue());
xyseries.add(abcissa, ordinate);
}
ds.addSeries(xyseries);
}
return ds;
}
protected TimeSeriesCollection createTimeSeriesDataset(ChartConfig chartConfig, Document data) {
TimeSeriesCollection ds = new TimeSeriesCollection();
for (Iterator i = chartConfig.getValueIterator(); i.hasNext();) {
Value value = (Value) i.next();
String title = value.getTitle();
Iterator x = XPathUtils.selectIterator(data, value.getCategories());
Iterator y = XPathUtils.selectIterator(data, value.getSeries());
TimeSeries timeSeries = new TimeSeries(title, FixedMillisecond.class );
while (x.hasNext() && y.hasNext()) {
Node s = (Node) y.next();
Node c = (Node) x.next();
SimpleDateFormat sdf = new SimpleDateFormat(chartConfig.getDateFormat());
FixedMillisecond fm;
try {
fm = new FixedMillisecond(sdf.parse(c.getStringValue()).getTime());
}
catch(java.text.ParseException pe) {
throw new OXFException("Date Format " + chartConfig.getDateFormat() + " does not match with the date data", pe);
}
Double ordinate = new Double(s.getStringValue());
timeSeries.add(fm,ordinate);
}
ds.addSeries(timeSeries);
}
return ds;
}
protected ChartConfig createChartConfig(org.orbeon.oxf.pipeline.api.PipelineContext context, org.orbeon.oxf.processor.ProcessorInput input) {
ChartConfig chart = new ChartConfig();
Document doc = readInputAsDOM4J(context, input);
DefaultDrawingSupplier defaults = new DefaultDrawingSupplier();
String type = XPathUtils.selectStringValueNormalize(doc, "/chart/type");
if (type.equals("vertical-bar"))
chart.setType(ChartConfig.VERTICAL_BAR_TYPE);
else if (type.equals("horizontal-bar"))
chart.setType(ChartConfig.HORIZONTAL_BAR_TYPE);
else if (type.equals("line"))
chart.setType(ChartConfig.LINE_TYPE);
else if (type.equals("area"))
chart.setType(ChartConfig.AREA_TYPE);
else if (type.equals("stacked-vertical-bar"))
chart.setType(ChartConfig.STACKED_VERTICAL_BAR_TYPE);
else if (type.equals("stacked-horizontal-bar"))
chart.setType(ChartConfig.STACKED_HORIZONTAL_BAR_TYPE);
else if (type.equals("stacked-vertical-bar-3d"))
chart.setType(ChartConfig.STACKED_VERTICAL_BAR3D_TYPE);
else if (type.equals("stacked-horizontal-bar-3d"))
chart.setType(ChartConfig.STACKED_HORIZONTAL_BAR3D_TYPE);
else if (type.equals("vertical-bar-3d"))
chart.setType(ChartConfig.VERTICAL_BAR3D_TYPE);
else if (type.equals("horizontal-bar-3d"))
chart.setType(ChartConfig.HORIZONTAL_BAR3D_TYPE);
else if (type.equals("pie"))
chart.setType(ChartConfig.PIE_TYPE);
else if (type.equals("pie-3d"))
chart.setType(ChartConfig.PIE3D_TYPE);
else if (type.equals("xy-line"))
chart.setType(ChartConfig.XY_LINE_TYPE);
else if (type.equals("time-series"))
chart.setType(ChartConfig.TIME_SERIES_TYPE);
else
throw new OXFException("Chart type " + type + " is not supported");
String title = XPathUtils.selectStringValueNormalize(doc, "/chart/title");
chart.setTitle(title == null ? "" : title);
chart.setMap(XPathUtils.selectStringValueNormalize(doc, "/chart/map"));
chart.setCategoryTitle(XPathUtils.selectStringValueNormalize(doc, "/chart/category-title"));
String catMargin = XPathUtils.selectStringValueNormalize(doc, "/chart/category-margin");
if (catMargin != null)
chart.setCategoryMargin(Double.parseDouble(catMargin));
chart.setSerieTitle(XPathUtils.selectStringValueNormalize(doc, "/chart/serie-title"));
chart.setxSize(XPathUtils.selectIntegerValue(doc, "/chart/x-size").intValue());
chart.setySize(XPathUtils.selectIntegerValue(doc, "/chart/y-size").intValue());
String bgColor = XPathUtils.selectStringValueNormalize(doc, "/chart/background-color");
String tColor = XPathUtils.selectStringValueNormalize(doc, "/chart/title-color");
Integer maxNumOfTickUnit = XPathUtils.selectIntegerValue(doc, "/chart/max-number-of-labels");
String sDateFormat = XPathUtils.selectStringValueNormalize(doc, "/chart/date-format");
String categoryLabelAngle = XPathUtils.selectStringValueNormalize(doc, "/chart/category-label-angle");
chart.setBackgroundColor(bgColor == null ? DEFAULT_BACKGROUND_COLOR : getRGBColor(bgColor));
chart.setTitleColor(tColor == null ? DEFAULT_TITLE_COLOR : getRGBColor(tColor));
if(maxNumOfTickUnit != null)
chart.setMaxNumOfLabels(maxNumOfTickUnit.intValue());
if(sDateFormat != null)
chart.setDateFormat(sDateFormat);
if (categoryLabelAngle != null) {
double angle = Double.parseDouble(categoryLabelAngle);
chart.setCategoryLabelPosition(CategoryLabelPositions.createUpRotationLabelPositions(angle * (Math.PI / 180)));
chart.setCategoryLabelAngle(angle);
}
String margin = XPathUtils.selectStringValueNormalize(doc, "/chart/bar-margin");
if (margin != null)
chart.setBarMargin(Double.parseDouble(margin));
// legend
CustomLegend legend = new CustomLegend(null);
Boolean legendVis = XPathUtils.selectBooleanValue(doc, "/chart/legend/@visible = 'true'");
legend.setVisible(legendVis.booleanValue());
if(legend.isVisible()) {
String pos = XPathUtils.selectStringValueNormalize(doc, "/chart/legend/@position");
if ("north".equals(pos)) {
legend.setPosition(RectangleEdge.TOP);
}
else if ("east".equals(pos)) {
legend.setPosition(RectangleEdge.RIGHT);
}
else if ("south".equals(pos)) {
legend.setPosition(RectangleEdge.BOTTOM);
}
else if ("west".equals(pos)) {
legend.setPosition(RectangleEdge.LEFT);
}
for (Iterator i = XPathUtils.selectIterator(doc, "/chart/legend/item"); i.hasNext();) {
Element el = (Element) i.next();
Color color = getRGBColor(el.attributeValue("color"));
String label = el.attributeValue("label");
legend.addItem(label, color);
}
}
chart.setLegendConfig(legend);
for (Iterator i = XPathUtils.selectIterator(doc, "/chart/*[name()='value']"); i.hasNext();) {
Element el = (Element) i.next();
String c = el.attributeValue("color");
Paint color;
if (c != null)
color = getRGBColor(c);
else
color = defaults.getNextPaint();
chart.addValue(el.attributeValue("title"),
el.attributeValue("categories"),
el.attributeValue("series"),
el.attributeValue("colors"),
el.attributeValue("exploded-percents"),
color);
}
return chart;
}
protected JFreeChart drawChart(ChartConfig chartConfig, final Dataset ds) {
JFreeChart chart = null;
Axis categoryAxis = null;
if(ds instanceof XYSeriesCollection) {
categoryAxis = new RestrictedNumberAxis(chartConfig.getCategoryTitle());
}
else if(ds instanceof TimeSeriesCollection) {
categoryAxis = new DateAxis(chartConfig.getCategoryTitle());
((DateAxis)categoryAxis).setDateFormatOverride(new SimpleDateFormat(chartConfig.getDateFormat()));
if (chartConfig.getCategoryLabelAngle() == 90) {
((DateAxis)categoryAxis).setVerticalTickLabels(true);
} else {
if (chartConfig.getCategoryLabelAngle() != 0)
throw new OXFException("The only supported values of category-label-angle for time-series charts are 0 or 90");
}
}
else {
categoryAxis = new CategoryAxis(chartConfig.getCategoryTitle());
((CategoryAxis)categoryAxis).setCategoryLabelPositions(chartConfig.getCategoryLabelPosition());
}
Axis valueAxis = new RestrictedNumberAxis(chartConfig.getSerieTitle());
AbstractRenderer renderer = null;
Plot plot = null;
switch (chartConfig.getType()) {
case ChartConfig.VERTICAL_BAR_TYPE:
case ChartConfig.HORIZONTAL_BAR_TYPE:
renderer = (ds instanceof ItemPaintCategoryDataset) ? new BarRenderer() {
public Paint getItemPaint(int row, int column) {
Paint p = ((ItemPaintCategoryDataset) ds).getItemPaint(row, column);
if (p != null)
return p;
else
return getSeriesPaint(row);
}
} : new BarRenderer();
plot = new CategoryPlot((CategoryDataset) ds, (CategoryAxis)categoryAxis, (ValueAxis)valueAxis, (CategoryItemRenderer)renderer);
if(chartConfig.getType() == ChartConfig.VERTICAL_BAR_TYPE)
((CategoryPlot) plot).setOrientation(PlotOrientation.VERTICAL);
else
((CategoryPlot) plot).setOrientation(PlotOrientation.HORIZONTAL);
break;
case ChartConfig.STACKED_VERTICAL_BAR_TYPE:
case ChartConfig.STACKED_HORIZONTAL_BAR_TYPE:
renderer = (ds instanceof ItemPaintCategoryDataset) ? new StackedBarRenderer() {
public Paint getItemPaint(int row, int column) {
Paint p = ((ItemPaintCategoryDataset) ds).getItemPaint(row, column);
if (p != null)
return p;
else
return getSeriesPaint(row);
}
} : new StackedBarRenderer();
plot = new CategoryPlot((CategoryDataset) ds, (CategoryAxis)categoryAxis, (ValueAxis)valueAxis,(CategoryItemRenderer)renderer);
if(chartConfig.getType() == ChartConfig.STACKED_VERTICAL_BAR_TYPE)
((CategoryPlot) plot).setOrientation(PlotOrientation.VERTICAL);
else
((CategoryPlot) plot).setOrientation(PlotOrientation.HORIZONTAL);
break;
case ChartConfig.LINE_TYPE:
renderer = (ds instanceof ItemPaintCategoryDataset) ? new LineAndShapeRenderer(true,false) {
public Paint getItemPaint(int row, int column) {
Paint p = ((ItemPaintCategoryDataset) ds).getItemPaint(row, column);
if (p != null)
return p;
else
return getSeriesPaint(row);
}
} : (new LineAndShapeRenderer(true,false));
plot = new CategoryPlot((CategoryDataset) ds, (CategoryAxis)categoryAxis, (ValueAxis)valueAxis, (CategoryItemRenderer)renderer);
((CategoryPlot) plot).setOrientation(PlotOrientation.VERTICAL);
break;
case ChartConfig.AREA_TYPE:
renderer = (ds instanceof ItemPaintCategoryDataset) ? new AreaRenderer() {
public Paint getItemPaint(int row, int column) {
Paint p = ((ItemPaintCategoryDataset) ds).getItemPaint(row, column);
if (p != null)
return p;
else
return getSeriesPaint(row);
}
} : new AreaRenderer();
plot = new CategoryPlot((CategoryDataset) ds, (CategoryAxis)categoryAxis, (ValueAxis)valueAxis, (CategoryItemRenderer)renderer);
((CategoryPlot) plot).setOrientation(PlotOrientation.VERTICAL);
break;
case ChartConfig.VERTICAL_BAR3D_TYPE:
case ChartConfig.HORIZONTAL_BAR3D_TYPE:
categoryAxis = new CategoryAxis3D(chartConfig.getCategoryTitle());
valueAxis = new NumberAxis3D(chartConfig.getSerieTitle());
renderer = (ds instanceof ItemPaintCategoryDataset) ? new BarRenderer3D() {
public Paint getItemPaint(int row, int column) {
Paint p = ((ItemPaintCategoryDataset) ds).getItemPaint(row, column);
if (p != null)
return p;
else
return getSeriesPaint(row);
}
} : new BarRenderer3D();
plot = new CategoryPlot((CategoryDataset) ds, (CategoryAxis)categoryAxis, (ValueAxis)valueAxis, (CategoryItemRenderer)renderer);
if(chartConfig.getType() == ChartConfig.VERTICAL_BAR3D_TYPE)
((CategoryPlot) plot).setOrientation(PlotOrientation.VERTICAL);
else
((CategoryPlot) plot).setOrientation(PlotOrientation.HORIZONTAL);
break;
case ChartConfig.STACKED_VERTICAL_BAR3D_TYPE:
case ChartConfig.STACKED_HORIZONTAL_BAR3D_TYPE:
categoryAxis = new CategoryAxis3D(chartConfig.getCategoryTitle());
valueAxis = new NumberAxis3D(chartConfig.getSerieTitle());
renderer = (ds instanceof ItemPaintCategoryDataset) ? new StackedBarRenderer3D() {
public Paint getItemPaint(int row, int column) {
Paint p = ((ItemPaintCategoryDataset) ds).getItemPaint(row, column);
if (p != null)
return p;
else
return getSeriesPaint(row);
}
} : new StackedBarRenderer3D();
plot = new CategoryPlot((CategoryDataset) ds, (CategoryAxis)categoryAxis, (ValueAxis)valueAxis,(CategoryItemRenderer) renderer);
if(chartConfig.getType() == ChartConfig.STACKED_VERTICAL_BAR3D_TYPE)
((CategoryPlot) plot).setOrientation(PlotOrientation.VERTICAL);
else
((CategoryPlot) plot).setOrientation(PlotOrientation.HORIZONTAL);
break;
case ChartConfig.PIE_TYPE:
case ChartConfig.PIE3D_TYPE:
categoryAxis = null;
valueAxis = null;
renderer = null;
ExtendedPieDataset pds = (ExtendedPieDataset) ds;
plot = chartConfig.getType() == ChartConfig.PIE_TYPE ? new PiePlot(pds) : new PiePlot3D(pds);
PiePlot pp = (PiePlot) plot;
pp.setLabelGenerator(new StandardPieSectionLabelGenerator());
for (int i = 0; i < pds.getItemCount(); i++) {
Paint p = pds.getPaint(i);
if (p != null)
pp.setSectionPaint(i, p);
pp.setExplodePercent(i, pds.getExplodePercent(i));
Paint paint = pds.getPaint(i);
if (paint != null)
pp.setSectionPaint(i, paint);
}
break;
case ChartConfig.XY_LINE_TYPE:
renderer = new XYLineAndShapeRenderer(true,false);
plot = new XYPlot((XYDataset) ds, (ValueAxis)categoryAxis, (ValueAxis)valueAxis, (XYLineAndShapeRenderer) renderer);
break;
case ChartConfig.TIME_SERIES_TYPE:
renderer = new XYLineAndShapeRenderer(true,false);
plot = new XYPlot((XYDataset) ds, (DateAxis)categoryAxis, (ValueAxis)valueAxis, (XYLineAndShapeRenderer) renderer);
break;
default:
throw new OXFException("Chart Type not supported");
}
if (categoryAxis != null) {
categoryAxis.setLabelPaint(chartConfig.getTitleColor());
categoryAxis.setTickLabelPaint(chartConfig.getTitleColor());
categoryAxis.setTickMarkPaint(chartConfig.getTitleColor());
if(categoryAxis instanceof RestrictedNumberAxis) {
((RestrictedNumberAxis)categoryAxis).setMaxTicks(chartConfig.getMaxNumOfLabels());
((RestrictedNumberAxis)categoryAxis).adjustTickUnits();
}
if (categoryAxis instanceof CategoryAxis && chartConfig.getCategoryMargin() != 0)
((CategoryAxis)categoryAxis).setCategoryMargin(chartConfig.getCategoryMargin());
}
if (valueAxis != null) {
valueAxis.setLabelPaint(chartConfig.getTitleColor());
valueAxis.setTickLabelPaint(chartConfig.getTitleColor());
valueAxis.setTickMarkPaint(chartConfig.getTitleColor());
((RestrictedNumberAxis)valueAxis).setMaxTicks(chartConfig.getMaxNumOfLabels());
((RestrictedNumberAxis)valueAxis).adjustTickUnits();
}
if (renderer != null) {
if(renderer instanceof XYLineAndShapeRenderer) {
((XYLineAndShapeRenderer) renderer).setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());
}
else {
((CategoryItemRenderer) renderer).setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
}
if (renderer instanceof BarRenderer)
((BarRenderer) renderer).setItemMargin(chartConfig.getBarMargin());
int j = 0;
for (Iterator i = chartConfig.getValueIterator(); i.hasNext();) {
Value v = (Value) i.next();
renderer.setSeriesPaint(j, v.getColor());
j++;
}
}
plot.setOutlinePaint(chartConfig.getTitleColor());
CustomLegend legend = chartConfig.getLegendConfig();
chart = new JFreeChart(chartConfig.getTitle(), TextTitle.DEFAULT_FONT, plot, false);
if(legend.isVisible()) {
legend.setSources(new LegendItemSource[] {plot});
chart.addLegend(legend);
}
chart.setBackgroundPaint(chartConfig.getBackgroundColor());
TextTitle textTitle = new TextTitle(chartConfig.getTitle(),TextTitle.DEFAULT_FONT,chartConfig.getTitleColor(),
TextTitle.DEFAULT_POSITION, TextTitle.DEFAULT_HORIZONTAL_ALIGNMENT,TextTitle.DEFAULT_VERTICAL_ALIGNMENT,
TextTitle.DEFAULT_PADDING);
chart.setTitle(textTitle);
return chart;
}
protected static class ChartConfig {
public static final int VERTICAL_BAR_TYPE = 0;
public static final int HORIZONTAL_BAR_TYPE = 1;
public static final int STACKED_VERTICAL_BAR_TYPE = 2;
public static final int STACKED_HORIZONTAL_BAR_TYPE = 3;
public static final int LINE_TYPE = 4;
public static final int AREA_TYPE = 5;
public static final int VERTICAL_BAR3D_TYPE = 6;
public static final int HORIZONTAL_BAR3D_TYPE = 7;
public static final int STACKED_VERTICAL_BAR3D_TYPE = 8;
public static final int STACKED_HORIZONTAL_BAR3D_TYPE = 9;
public static final int PIE_TYPE = 10;
public static final int PIE3D_TYPE = 11;
public static final int XY_LINE_TYPE = 12;
public static final int TIME_SERIES_TYPE = 13;
private int type;
private String title;
private String map;
private String categoryTitle;
private String serieTitle;
private double categoryMargin;
private Color titleColor;
private Color backgroundColor;
private double barMargin;
private int maxNumOfLabels = 10;
private String dateFormat;
private CategoryLabelPositions categoryLabelPosition = CategoryLabelPositions.STANDARD;
private CustomLegend legendConfig;
private double categoryLabelAngle = 0;
private List values = new ArrayList();
private int xSize;
private int ySize;
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategoryTitle() {
return categoryTitle;
}
public void setCategoryTitle(String categoryTitle) {
this.categoryTitle = categoryTitle;
}
public String getSerieTitle() {
return serieTitle;
}
public void setSerieTitle(String serieTitle) {
this.serieTitle = serieTitle;
}
public int getxSize() {
return xSize;
}
public void setxSize(int xSize) {
this.xSize = xSize;
}
public int getySize() {
return ySize;
}
public void setySize(int ySize) {
this.ySize = ySize;
}
public Color getTitleColor() {
return titleColor;
}
public void setTitleColor(Color titleColor) {
this.titleColor = titleColor;
}
public Color getBackgroundColor() {
return backgroundColor;
}
public void setBackgroundColor(Color backgroundColor) {
this.backgroundColor = backgroundColor;
}
public void addValue(String title, String categories, String series, String colors, String explodedPercent, Paint color) {
values.add(new Value(title, categories, series, colors, explodedPercent, color));
}
public Iterator getValueIterator() {
return values.iterator();
}
public String getMap() {
return map;
}
public void setMap(String map) {
this.map = map;
}
public double getBarMargin() {
return barMargin;
}
public void setBarMargin(double barMargin) {
this.barMargin = barMargin;
}
public CustomLegend getLegendConfig() {
return legendConfig;
}
public void setLegendConfig(CustomLegend legendConfig) {
this.legendConfig = legendConfig;
}
public double getCategoryMargin() {
return categoryMargin;
}
public void setCategoryMargin(double categoryMargin) {
this.categoryMargin = categoryMargin;
}
public CategoryLabelPositions getCategoryLabelPosition() {
return categoryLabelPosition;
}
public void setCategoryLabelPosition(CategoryLabelPositions categoryLabelPosition) {
this.categoryLabelPosition = categoryLabelPosition;
}
public int getMaxNumOfLabels() {
return maxNumOfLabels;
}
public void setMaxNumOfLabels(int maxNumOfLabels) {
this.maxNumOfLabels = maxNumOfLabels;
}
public String getDateFormat() {
return dateFormat;
}
public void setDateFormat(String dateFormat) {
this.dateFormat = dateFormat;
}
public double getCategoryLabelAngle() {
return categoryLabelAngle;
}
public void setCategoryLabelAngle(double categoryLabelAngle) {
this.categoryLabelAngle = categoryLabelAngle;
}
}
protected static class Value {
private String title;
private String categories;
private String series;
private String colors;
private String explodedPercents;
private Paint color;
public Value(String title, String categories, String series, String colors, String explodedPercents, Paint color) {
this.title = title;
this.categories = categories;
this.series = series;
this.colors = colors;
this.explodedPercents = explodedPercents;
this.color = color;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategories() {
return categories;
}
public void setCategories(String categories) {
this.categories = categories;
}
public String getSeries() {
return series;
}
public void setSeries(String series) {
this.series = series;
}
public Paint getColor() {
return color;
}
public void setColor(Paint color) {
this.color = color;
}
public String getColors() {
return colors;
}
public void setColors(String colors) {
this.colors = colors;
}
public String getExplodedPercents() {
return explodedPercents;
}
public void setExplodedPercents(String explodedPercents) {
this.explodedPercents = explodedPercents;
}
}
protected static class CustomLegend extends LegendTitle {
private boolean visible = true;
private LegendItemCollection legendItems = new LegendItemCollection();
public static final Font DEFAULT_TITLE_FONT = new Font("SansSerif", 1, 11);
public static Paint DEFAULT_BACKGROUND_PAINT = Color.white;
public static Paint DEFAULT_OUTLINE_PAINT = Color.gray;
public static final Stroke DEFAULT_OUTLINE_STROKE = new BasicStroke();
public CustomLegend(Plot plot) {
super(plot);
}
public void addItem(String label, Color color) {
LegendItem legendItem = new LegendItem(label,label,label,label,AbstractRenderer.DEFAULT_SHAPE,
color,AbstractRenderer.DEFAULT_OUTLINE_STROKE,
AbstractRenderer.DEFAULT_OUTLINE_PAINT);
legendItems.add(legendItem);
}
public boolean hasItems() {
return legendItems.getItemCount() > 0;
}
public Iterator itemIterator() {
return legendItems.iterator();
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public Rectangle2D draw(Graphics2D g2, Rectangle2D available, ChartRenderingInfo info) {
boolean horizontal = RectangleEdge.isLeftOrRight(getPosition());
boolean inverted = RectangleEdge.isTopOrBottom(getPosition());
RectangleInsets insets = getFrame().getInsets();
String title = null;
if ((legendItems != null) && (legendItems.getItemCount() > 0)) {
DrawableLegendItem legendTitle = null;
Rectangle2D legendArea = new Rectangle2D.Double();
double availableWidth = available.getWidth();
double availableHeight = available.getHeight();
// the translation point for the origin of the drawing system
Point2D translation = new Point2D.Double();
// Create buffer for individual rectangles within the legend
DrawableLegendItem[] items = new DrawableLegendItem[legendItems.getItemCount()];
// Compute individual rectangles in the legend, translation point as well
// as the bounding box for the legend.
if (horizontal) {
double xstart = available.getX() ;
double xlimit = available.getMaxX();
double maxRowWidth = 0;
double xoffset = 0;
double rowHeight = 0;
double totalHeight = 0;
boolean startingNewRow = true;
if (title != null && !title.equals("")) {
g2.setFont(CustomLegend.DEFAULT_TITLE_FONT);
LegendItem titleItem = new LegendItem(title,title,title,title,AbstractRenderer.DEFAULT_SHAPE,
Color.black,AbstractRenderer.DEFAULT_OUTLINE_STROKE,
AbstractRenderer.DEFAULT_OUTLINE_PAINT);
legendTitle = createDrawableLegendItem(g2, titleItem,xoffset,totalHeight);
rowHeight = Math.max(rowHeight, legendTitle.getHeight());
xoffset += legendTitle.getWidth();
}
g2.setFont(LegendTitle.DEFAULT_ITEM_FONT);
for (int i = 0; i < legendItems.getItemCount(); i++) {
items[i] = createDrawableLegendItem(g2, legendItems.get(i),
xoffset, totalHeight);
if ((!startingNewRow)
&& (items[i].getX() + items[i].getWidth() + xstart > xlimit)) {
maxRowWidth = Math.max(maxRowWidth, xoffset);
xoffset = 0;
totalHeight += rowHeight;
i--;
startingNewRow = true;
} else {
rowHeight = Math.max(rowHeight, items[i].getHeight());
xoffset += items[i].getWidth();
startingNewRow = false;
}
}
maxRowWidth = Math.max(maxRowWidth, xoffset);
totalHeight += rowHeight;
// Create the bounding box
legendArea = new Rectangle2D.Double(0, 0, maxRowWidth, totalHeight);
// The yloc point is the variable part of the translation point
// for horizontal legends. xloc is constant.
double yloc = (inverted)
? available.getMaxY() - totalHeight
- insets.calculateBottomOutset(availableHeight)
: available.getY() + insets.calculateTopOutset(availableHeight);
double xloc = available.getX() + available.getWidth() / 2 - maxRowWidth / 2;
// Create the translation point
translation = new Point2D.Double(xloc, yloc);
} else { // vertical...
double totalHeight = 0;
double maxWidth = 0;
if (title != null && !title.equals("")) {
g2.setFont(CustomLegend.DEFAULT_TITLE_FONT);
LegendItem titleItem = new LegendItem(title,title,title,title,AbstractRenderer.DEFAULT_SHAPE,
Color.black,AbstractRenderer.DEFAULT_OUTLINE_STROKE,
AbstractRenderer.DEFAULT_OUTLINE_PAINT);
legendTitle = createDrawableLegendItem(g2, titleItem, 0,totalHeight);
totalHeight += legendTitle.getHeight();
maxWidth = Math.max(maxWidth, legendTitle.getWidth());
}
g2.setFont(LegendTitle.DEFAULT_ITEM_FONT);
for (int i = 0; i < items.length; i++) {
items[i] = createDrawableLegendItem(g2, legendItems.get(i),
0, totalHeight);
totalHeight += items[i].getHeight();
maxWidth = Math.max(maxWidth, items[i].getWidth());
}
// Create the bounding box
legendArea = new Rectangle2D.Float(0, 0, (float) maxWidth, (float) totalHeight);
// The xloc point is the variable part of the translation point
// for vertical legends. yloc is constant.
double xloc = (inverted)
? available.getMaxX() - maxWidth - insets.calculateRightOutset(availableWidth)
: available.getX() + insets.calculateLeftOutset(availableWidth);
double yloc = available.getY() + (available.getHeight() / 2) - (totalHeight / 2);
// Create the translation point
translation = new Point2D.Double(xloc, yloc);
}
// Move the origin of the drawing to the appropriate location
g2.translate(translation.getX(), translation.getY());
// Draw the legend's bounding box
g2.setPaint(CustomLegend.DEFAULT_BACKGROUND_PAINT);
g2.fill(legendArea);
g2.setPaint(CustomLegend.DEFAULT_OUTLINE_PAINT);
g2.setStroke(CustomLegend.DEFAULT_OUTLINE_STROKE);
g2.draw(legendArea);
// draw legend title
if (legendTitle != null) {
// XXX dsm - make title bold?
g2.setPaint(legendTitle.getItem().getFillPaint());
g2.setPaint(Color.black);
g2.setFont(CustomLegend.DEFAULT_TITLE_FONT);
g2.drawString(legendTitle.getItem().getLabel(),
(float) legendTitle.getLabelPosition().getX(),
(float) legendTitle.getLabelPosition().getY());
}
// Draw individual series elements
for (int i = 0; i < items.length; i++) {
g2.setPaint(items[i].getItem().getFillPaint());
Shape keyBox = items[i].getMarker();
g2.fill(keyBox);
g2.setPaint(Color.black);
g2.setFont(LegendTitle.DEFAULT_ITEM_FONT);
g2.drawString(items[i].getItem().getLabel(),
(float) items[i].getLabelPosition().getX(),
(float) items[i].getLabelPosition().getY());
}
// translate the origin back to what it was prior to drawing the legend
g2.translate(-translation.getX(), -translation.getY());
if (horizontal) {
// The remaining drawing area bounding box will have the same
// x origin, width and height independent of the anchor's
// location. The variable is the y coordinate. If the anchor is
// SOUTH, the y coordinate is simply the original y coordinate
// of the available area. If it is NORTH, we adjust original y
// by the total height of the legend and the initial gap.
double yy = available.getY();
double yloc = (inverted) ? yy
: yy + legendArea.getHeight()
+ insets.calculateBottomOutset(availableHeight);
// return the remaining available drawing area
return new Rectangle2D.Double(available.getX(), yloc, availableWidth,
availableHeight - legendArea.getHeight()
- insets.calculateTopOutset(availableHeight)
- insets.calculateBottomOutset(availableHeight));
} else {
// The remaining drawing area bounding box will have the same
// y origin, width and height independent of the anchor's
// location. The variable is the x coordinate. If the anchor is
// EAST, the x coordinate is simply the original x coordinate
// of the available area. If it is WEST, we adjust original x
// by the total width of the legend and the initial gap.
double xloc = (inverted) ? available.getX()
: available.getX()
+ legendArea.getWidth()
+ insets.calculateLeftOutset(availableWidth)
+ insets.calculateRightOutset(availableWidth);
// return the remaining available drawing area
return new Rectangle2D.Double(xloc, available.getY(),
availableWidth - legendArea.getWidth()
- insets.calculateLeftOutset(availableWidth)
- insets.calculateRightOutset(availableWidth),
availableHeight);
}
} else {
return available;
}
}
private DrawableLegendItem createDrawableLegendItem(Graphics2D graphics,
LegendItem legendItem,
double x, double y) {
int innerGap = 2;
FontMetrics fm = graphics.getFontMetrics();
LineMetrics lm = fm.getLineMetrics(legendItem.getLabel(), graphics);
float textAscent = lm.getAscent();
float lineHeight = textAscent + lm.getDescent() + lm.getLeading();
DrawableLegendItem item = new DrawableLegendItem(legendItem);
float xloc = (float) (x + innerGap + 1.15f * lineHeight);
float yloc = (float) (y + innerGap + 0.15f * lineHeight + textAscent);
item.setLabelPosition(new Point2D.Float(xloc, yloc));
float boxDim = lineHeight * 0.70f;
xloc = (float) (x + innerGap + 0.15f * lineHeight);
yloc = (float) (y + innerGap + 0.15f * lineHeight);
item.setMarker(new Rectangle2D.Float(xloc, yloc, boxDim, boxDim));
float width = (float) (item.getLabelPosition().getX() - x
+ fm.getStringBounds(legendItem.getLabel(), graphics).getWidth()
+ 0.5 * textAscent);
float height = (2 * innerGap + lineHeight);
item.setBounds(x, y, width, height);
return item;
}
}
protected static class ExtendedPieDataset extends AbstractDataset implements PieDataset {
private List data = new ArrayList();
class Value {
public Comparable key;
public Number value;
public Paint paint = null;
public double explodePercent = 0;
}
public void setValue(Comparable key, Number value, Paint paint, double explode) {
Value v = new Value();
v.key = key;
v.value = value;
v.paint = paint;
v.explodePercent = explode;
int keyIndex = getIndex(key);
if (keyIndex >= 0) {
data.set(keyIndex, v);
} else {
data.add(v);
}
fireDatasetChanged();
}
public Comparable getKey(int index) {
return ((Value) data.get(index)).key;
}
public int getIndex(Comparable key) {
int result = -1;
int i = 0;
Iterator iterator = this.data.iterator();
while (iterator.hasNext()) {
Value v = (Value) iterator.next();
if (v.key.equals(key)) {
result = i;
}
i++;
}
return result;
}
public List getKeys() {
List keys = new ArrayList();
for (Iterator i = data.iterator(); i.hasNext();)
keys.add(((Value) i.next()).key);
return keys;
}
public Number getValue(Comparable key) {
int i = getIndex(key);
if (i != -1)
return ((Value) data.get(i)).value;
else
return null;
}
public int getItemCount() {
return data.size();
}
public Number getValue(int item) {
return ((Value) data.get(item)).value;
}
public Paint getPaint(int item) {
return ((Value) data.get(item)).paint;
}
public double getExplodePercent(int item) {
return ((Value) data.get(item)).explodePercent;
}
}
protected static class ItemPaintCategoryDataset extends DefaultCategoryDataset {
private List rowValues = new ArrayList();
public void addValue(double value, Paint paint, Comparable rowKey, Comparable columnKey) {
super.addValue(value, rowKey, columnKey);
addPaintValue(paint, rowKey, columnKey);
}
public void addValue(Number value, Paint paint, Comparable rowKey, Comparable columnKey) {
super.addValue(value, rowKey, columnKey);
addPaintValue(paint, rowKey, columnKey);
}
public Paint getItemPaint(int rowIndex, int columnIndex) {
try {
List columnValues = (List) rowValues.get(rowIndex);
return (Paint) columnValues.get(columnIndex);
} catch (IndexOutOfBoundsException e) {
return null;
}
}
private void addPaintValue(Paint paint, Comparable rowKey, Comparable columnKey) {
int rowIndex = getRowIndex(rowKey);
int colIndex = getColumnIndex(columnKey);
List colValues;
if(rowIndex < rowValues.size())
colValues = (List) rowValues.get(rowIndex);
else {
colValues = new ArrayList();
rowValues.add(rowIndex, colValues);
}
colValues.add(colIndex, paint);
}
}
protected static Color getRGBColor(String rgb) {
try {
return new Color(Integer.parseInt(rgb.substring(1), 16));
} catch (NumberFormatException e) {
throw new OXFException("Can't parse RGB color: " + rgb, e);
}
}
protected static class RestrictedNumberAxis extends NumberAxis{
private int maxTicks = NumberAxis.MAXIMUM_TICK_COUNT;
/**
* Creates a Number axis with the specified label.
*
* @param label the axis label (<code>null</code> permitted).
*/
public RestrictedNumberAxis(String label) {
super(label);
}
public int getMaxTicks() {
return maxTicks;
}
public void setMaxTicks(int maxTicks) {
this.maxTicks = maxTicks;
}
protected int getVisibleTickCount() {
double unit = getTickUnit().getSize();
Range range = getRange();
return (int)(Math.floor(range.getUpperBound() / unit)
- Math.ceil(range.getLowerBound() / unit) + 1);
}
protected void adjustTickUnits() {
int tickUnit = getVisibleTickCount()/maxTicks;
if(tickUnit != 0) {
super.setTickUnit(new NumberTickUnit(tickUnit));
}
}
}
}
| src/java/org/orbeon/oxf/processor/serializer/legacy/JFreeChartSerializer.java | /**
* Copyright (C) 2004 Orbeon, Inc.
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU Lesser General Public License as published by the Free Software Foundation; either version
* 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
*/
package org.orbeon.oxf.processor.serializer.legacy;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.jfree.chart.*;
import org.jfree.chart.axis.*;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.*;
import org.jfree.chart.renderer.AbstractRenderer;
import org.jfree.chart.renderer.category.*;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.chart.title.LegendTitle;
import org.jfree.data.Range;
import org.jfree.data.xy.*;
import org.jfree.data.time.*;
import org.jfree.data.general.*;
import org.jfree.data.category.*;
import org.orbeon.oxf.common.OXFException;
import org.orbeon.oxf.pipeline.api.PipelineContext;
import org.orbeon.oxf.processor.ProcessorInput;
import org.orbeon.oxf.processor.ProcessorInputOutputInfo;
import org.orbeon.oxf.processor.serializer.HttpBinarySerializer;
import org.orbeon.oxf.xml.XPathUtils;
import java.awt.*;
import java.awt.font.LineMetrics;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.text.SimpleDateFormat;
import org.jfree.chart.block.BlockFrame;
import org.jfree.ui.RectangleEdge;
import org.jfree.ui.RectangleInsets;
import org.jfree.chart.labels.StandardXYItemLabelGenerator;
public class JFreeChartSerializer extends HttpBinarySerializer {
public static final String CHART_CONVERTER_CHART_NAMESPACE_URI = "http://www.orbeon.com/oxf/converter/chart-chart";
public static String DEFAULT_CONTENT_TYPE = "image/png";
public static final String INPUT_CHART = "chart";
public static final Color DEFAULT_BACKGROUND_COLOR = getRGBColor("#FFFFFF");
public static final Color DEFAULT_TITLE_COLOR = getRGBColor("#000000");
public JFreeChartSerializer() {
addInputInfo(new ProcessorInputOutputInfo(INPUT_CHART, CHART_CONVERTER_CHART_NAMESPACE_URI));
}
protected String getDefaultContentType() {
return DEFAULT_CONTENT_TYPE;
}
protected void readInput(PipelineContext pipelineContext, ProcessorInput input, Config config, OutputStream outputStream) {
try {
ChartConfig chartConfig = (ChartConfig) readCacheInputAsObject(pipelineContext, getInputByName(INPUT_CHART),
new org.orbeon.oxf.processor.CacheableInputReader() {
public Object read(org.orbeon.oxf.pipeline.api.PipelineContext context, org.orbeon.oxf.processor.ProcessorInput input) {
return createChartConfig(context, input);
}
});
Document data = readInputAsDOM4J(pipelineContext, (input != null) ? input : getInputByName(INPUT_DATA));
Dataset ds;
if (chartConfig.getType() == ChartConfig.PIE_TYPE ||
chartConfig.getType() == ChartConfig.PIE3D_TYPE)
ds = createPieDataset(chartConfig, data);
else if(chartConfig.getType() == ChartConfig.XY_LINE_TYPE)
ds = createXYDataset(chartConfig, data);
else if(chartConfig.getType() == ChartConfig.TIME_SERIES_TYPE)
ds = createTimeSeriesDataset(chartConfig, data);
else
ds = createDataset(chartConfig, data);
JFreeChart chart = drawChart(chartConfig, ds);
ChartRenderingInfo info = new ChartRenderingInfo();
ChartUtilities.writeChartAsPNG(outputStream, chart, chartConfig.getxSize(), chartConfig.getySize(), info, true, 5);
} catch (Exception e) {
throw new OXFException(e);
}
}
protected PieDataset createPieDataset(ChartConfig chartConfig, Document data) {
ExtendedPieDataset ds = new ExtendedPieDataset();
Value value = (Value) chartConfig.getValueIterator().next();
Iterator cats = XPathUtils.selectIterator(data, value.getCategories());
Iterator series = XPathUtils.selectIterator(data, value.getSeries());
Iterator colors = null;
if (value.getColors() != null)
colors = XPathUtils.selectIterator(data, value.getColors());
Iterator explodedPercents = null;
if (value.getExplodedPercents() != null)
explodedPercents = XPathUtils.selectIterator(data, value.getExplodedPercents());
while (cats.hasNext() && series.hasNext()) {
Element s = (Element) series.next();
Element c = (Element) cats.next();
Double d = new Double(s.getText().trim());
Paint p = null;
double ep = 0;
if (colors != null) {
Element col = (Element) colors.next();
p = getRGBColor(col.getText());
}
if (explodedPercents != null) {
Element e = (Element) explodedPercents.next();
ep = Double.parseDouble(e.getText());
}
ds.setValue(c.getText(), d, p, ep);
}
return ds;
}
protected CategoryDataset createDataset(ChartConfig chartConfig, Document data) {
ItemPaintCategoryDataset ds = new ItemPaintCategoryDataset();
for (Iterator i = chartConfig.getValueIterator(); i.hasNext();) {
Value value = (Value) i.next();
Iterator cats = XPathUtils.selectIterator(data, value.getCategories());
Iterator series = XPathUtils.selectIterator(data, value.getSeries());
Iterator colors = null;
if (value.getColors() != null)
colors = XPathUtils.selectIterator(data, value.getColors());
while (cats.hasNext() && series.hasNext()) {
Node s = (Node) series.next();
Node c = (Node) cats.next();
Double d = new Double(s.getStringValue());
if (colors != null) {
Node col = (Node) colors.next();
Color color = getRGBColor(col.getStringValue());
ds.addValue(d, color, value.getTitle(), c.getStringValue());
} else
ds.addValue(d, value.getTitle(), c.getStringValue());
}
}
return ds;
}
protected XYSeriesCollection createXYDataset(ChartConfig chartConfig, Document data) {
XYSeriesCollection ds = new XYSeriesCollection();
for (Iterator i = chartConfig.getValueIterator(); i.hasNext();) {
Value value = (Value) i.next();
String title = value.getTitle();
Iterator x = XPathUtils.selectIterator(data, value.getCategories());
Iterator y = XPathUtils.selectIterator(data, value.getSeries());
XYSeries xyseries = new XYSeries(title);
while (x.hasNext() && y.hasNext()) {
Node s = (Node) y.next();
Node c = (Node) x.next();
Double abcissa = new Double(c.getStringValue());
Double ordinate = new Double(s.getStringValue());
xyseries.add(abcissa, ordinate);
}
ds.addSeries(xyseries);
}
return ds;
}
protected TimeSeriesCollection createTimeSeriesDataset(ChartConfig chartConfig, Document data) {
TimeSeriesCollection ds = new TimeSeriesCollection();
for (Iterator i = chartConfig.getValueIterator(); i.hasNext();) {
Value value = (Value) i.next();
String title = value.getTitle();
Iterator x = XPathUtils.selectIterator(data, value.getCategories());
Iterator y = XPathUtils.selectIterator(data, value.getSeries());
TimeSeries timeSeries = new TimeSeries(title, FixedMillisecond.class );
while (x.hasNext() && y.hasNext()) {
Node s = (Node) y.next();
Node c = (Node) x.next();
SimpleDateFormat sdf = new SimpleDateFormat(chartConfig.getDateFormat());
FixedMillisecond fm;
try {
fm = new FixedMillisecond(sdf.parse(c.getStringValue()).getTime());
}
catch(java.text.ParseException pe) {
throw new OXFException("Date Format " + chartConfig.getDateFormat() + " does not match with the date data", pe);
}
Double ordinate = new Double(s.getStringValue());
timeSeries.add(fm,ordinate);
}
ds.addSeries(timeSeries);
}
return ds;
}
protected ChartConfig createChartConfig(org.orbeon.oxf.pipeline.api.PipelineContext context, org.orbeon.oxf.processor.ProcessorInput input) {
ChartConfig chart = new ChartConfig();
Document doc = readInputAsDOM4J(context, input);
DefaultDrawingSupplier defaults = new DefaultDrawingSupplier();
String type = XPathUtils.selectStringValueNormalize(doc, "/chart/type");
if (type.equals("vertical-bar"))
chart.setType(ChartConfig.VERTICAL_BAR_TYPE);
else if (type.equals("horizontal-bar"))
chart.setType(ChartConfig.HORIZONTAL_BAR_TYPE);
else if (type.equals("line"))
chart.setType(ChartConfig.LINE_TYPE);
else if (type.equals("area"))
chart.setType(ChartConfig.AREA_TYPE);
else if (type.equals("stacked-vertical-bar"))
chart.setType(ChartConfig.STACKED_VERTICAL_BAR_TYPE);
else if (type.equals("stacked-horizontal-bar"))
chart.setType(ChartConfig.STACKED_HORIZONTAL_BAR_TYPE);
else if (type.equals("stacked-vertical-bar-3d"))
chart.setType(ChartConfig.STACKED_VERTICAL_BAR3D_TYPE);
else if (type.equals("stacked-horizontal-bar-3d"))
chart.setType(ChartConfig.STACKED_HORIZONTAL_BAR3D_TYPE);
else if (type.equals("vertical-bar-3d"))
chart.setType(ChartConfig.VERTICAL_BAR3D_TYPE);
else if (type.equals("horizontal-bar-3d"))
chart.setType(ChartConfig.HORIZONTAL_BAR3D_TYPE);
else if (type.equals("pie"))
chart.setType(ChartConfig.PIE_TYPE);
else if (type.equals("pie-3d"))
chart.setType(ChartConfig.PIE3D_TYPE);
else if (type.equals("xy-line"))
chart.setType(ChartConfig.XY_LINE_TYPE);
else if (type.equals("time-series"))
chart.setType(ChartConfig.TIME_SERIES_TYPE);
else
throw new OXFException("Chart type " + type + " is not supported");
String title = XPathUtils.selectStringValueNormalize(doc, "/chart/title");
chart.setTitle(title == null ? "" : title);
chart.setMap(XPathUtils.selectStringValueNormalize(doc, "/chart/map"));
chart.setCategoryTitle(XPathUtils.selectStringValueNormalize(doc, "/chart/category-title"));
String catMargin = XPathUtils.selectStringValueNormalize(doc, "/chart/category-margin");
if (catMargin != null)
chart.setCategoryMargin(Double.parseDouble(catMargin));
chart.setSerieTitle(XPathUtils.selectStringValueNormalize(doc, "/chart/serie-title"));
chart.setxSize(XPathUtils.selectIntegerValue(doc, "/chart/x-size").intValue());
chart.setySize(XPathUtils.selectIntegerValue(doc, "/chart/y-size").intValue());
String bgColor = XPathUtils.selectStringValueNormalize(doc, "/chart/background-color");
String tColor = XPathUtils.selectStringValueNormalize(doc, "/chart/title-color");
Integer maxNumOfTickUnit = XPathUtils.selectIntegerValue(doc, "/chart/max-number-of-labels");
String sDateFormat = XPathUtils.selectStringValueNormalize(doc, "/chart/date-format");
String categoryLabelAngle = XPathUtils.selectStringValueNormalize(doc, "/chart/category-label-angle");
chart.setBackgroundColor(bgColor == null ? DEFAULT_BACKGROUND_COLOR : getRGBColor(bgColor));
chart.setTitleColor(tColor == null ? DEFAULT_TITLE_COLOR : getRGBColor(tColor));
if(maxNumOfTickUnit != null)
chart.setMaxNumOfLabels(maxNumOfTickUnit.intValue());
if(sDateFormat != null)
chart.setDateFormat(sDateFormat);
if (categoryLabelAngle != null) {
double angle = Double.parseDouble(categoryLabelAngle);
chart.setCategoryLabelPosition(CategoryLabelPositions.createUpRotationLabelPositions(angle * (Math.PI / 180)));
}
String margin = XPathUtils.selectStringValueNormalize(doc, "/chart/bar-margin");
if (margin != null)
chart.setBarMargin(Double.parseDouble(margin));
// legend
CustomLegend legend = new CustomLegend(null);
Boolean legendVis = XPathUtils.selectBooleanValue(doc, "/chart/legend/@visible = 'true'");
legend.setVisible(legendVis.booleanValue());
if(legend.isVisible()) {
String pos = XPathUtils.selectStringValueNormalize(doc, "/chart/legend/@position");
if ("north".equals(pos)) {
legend.setPosition(RectangleEdge.TOP);
}
else if ("east".equals(pos)) {
legend.setPosition(RectangleEdge.RIGHT);
}
else if ("south".equals(pos)) {
legend.setPosition(RectangleEdge.BOTTOM);
}
else if ("west".equals(pos)) {
legend.setPosition(RectangleEdge.LEFT);
}
for (Iterator i = XPathUtils.selectIterator(doc, "/chart/legend/item"); i.hasNext();) {
Element el = (Element) i.next();
Color color = getRGBColor(el.attributeValue("color"));
String label = el.attributeValue("label");
legend.addItem(label, color);
}
}
chart.setLegendConfig(legend);
for (Iterator i = XPathUtils.selectIterator(doc, "/chart/*[name()='value']"); i.hasNext();) {
Element el = (Element) i.next();
String c = el.attributeValue("color");
Paint color;
if (c != null)
color = getRGBColor(c);
else
color = defaults.getNextPaint();
chart.addValue(el.attributeValue("title"),
el.attributeValue("categories"),
el.attributeValue("series"),
el.attributeValue("colors"),
el.attributeValue("exploded-percents"),
color);
}
return chart;
}
protected JFreeChart drawChart(ChartConfig chartConfig, final Dataset ds) {
JFreeChart chart = null;
Axis categoryAxis = null;
if(ds instanceof XYSeriesCollection) {
categoryAxis = new RestrictedNumberAxis(chartConfig.getCategoryTitle());
}
else if(ds instanceof TimeSeriesCollection) {
categoryAxis = new DateAxis(chartConfig.getCategoryTitle());
((DateAxis)categoryAxis).setDateFormatOverride(new SimpleDateFormat(chartConfig.getDateFormat()));
if (chartConfig.getCategoryLabelAngle() == 90) {
((DateAxis)categoryAxis).setVerticalTickLabels(true);
} else {
if (chartConfig.getCategoryLabelAngle() != 0)
throw new OXFException("The only supported values of category-label-angle for time-series charts are 0 or 90");
}
}
else {
categoryAxis = new CategoryAxis(chartConfig.getCategoryTitle());
((CategoryAxis)categoryAxis).setCategoryLabelPositions(chartConfig.getCategoryLabelPosition());
}
Axis valueAxis = new RestrictedNumberAxis(chartConfig.getSerieTitle());
AbstractRenderer renderer = null;
Plot plot = null;
switch (chartConfig.getType()) {
case ChartConfig.VERTICAL_BAR_TYPE:
case ChartConfig.HORIZONTAL_BAR_TYPE:
renderer = (ds instanceof ItemPaintCategoryDataset) ? new BarRenderer() {
public Paint getItemPaint(int row, int column) {
Paint p = ((ItemPaintCategoryDataset) ds).getItemPaint(row, column);
if (p != null)
return p;
else
return getSeriesPaint(row);
}
} : new BarRenderer();
plot = new CategoryPlot((CategoryDataset) ds, (CategoryAxis)categoryAxis, (ValueAxis)valueAxis, (CategoryItemRenderer)renderer);
if(chartConfig.getType() == ChartConfig.VERTICAL_BAR_TYPE)
((CategoryPlot) plot).setOrientation(PlotOrientation.VERTICAL);
else
((CategoryPlot) plot).setOrientation(PlotOrientation.HORIZONTAL);
break;
case ChartConfig.STACKED_VERTICAL_BAR_TYPE:
case ChartConfig.STACKED_HORIZONTAL_BAR_TYPE:
renderer = (ds instanceof ItemPaintCategoryDataset) ? new StackedBarRenderer() {
public Paint getItemPaint(int row, int column) {
Paint p = ((ItemPaintCategoryDataset) ds).getItemPaint(row, column);
if (p != null)
return p;
else
return getSeriesPaint(row);
}
} : new StackedBarRenderer();
plot = new CategoryPlot((CategoryDataset) ds, (CategoryAxis)categoryAxis, (ValueAxis)valueAxis,(CategoryItemRenderer)renderer);
if(chartConfig.getType() == ChartConfig.STACKED_VERTICAL_BAR_TYPE)
((CategoryPlot) plot).setOrientation(PlotOrientation.VERTICAL);
else
((CategoryPlot) plot).setOrientation(PlotOrientation.HORIZONTAL);
break;
case ChartConfig.LINE_TYPE:
renderer = (ds instanceof ItemPaintCategoryDataset) ? new LineAndShapeRenderer(true,false) {
public Paint getItemPaint(int row, int column) {
Paint p = ((ItemPaintCategoryDataset) ds).getItemPaint(row, column);
if (p != null)
return p;
else
return getSeriesPaint(row);
}
} : (new LineAndShapeRenderer(true,false));
plot = new CategoryPlot((CategoryDataset) ds, (CategoryAxis)categoryAxis, (ValueAxis)valueAxis, (CategoryItemRenderer)renderer);
((CategoryPlot) plot).setOrientation(PlotOrientation.VERTICAL);
break;
case ChartConfig.AREA_TYPE:
renderer = (ds instanceof ItemPaintCategoryDataset) ? new AreaRenderer() {
public Paint getItemPaint(int row, int column) {
Paint p = ((ItemPaintCategoryDataset) ds).getItemPaint(row, column);
if (p != null)
return p;
else
return getSeriesPaint(row);
}
} : new AreaRenderer();
plot = new CategoryPlot((CategoryDataset) ds, (CategoryAxis)categoryAxis, (ValueAxis)valueAxis, (CategoryItemRenderer)renderer);
((CategoryPlot) plot).setOrientation(PlotOrientation.VERTICAL);
break;
case ChartConfig.VERTICAL_BAR3D_TYPE:
case ChartConfig.HORIZONTAL_BAR3D_TYPE:
categoryAxis = new CategoryAxis3D(chartConfig.getCategoryTitle());
valueAxis = new NumberAxis3D(chartConfig.getSerieTitle());
renderer = (ds instanceof ItemPaintCategoryDataset) ? new BarRenderer3D() {
public Paint getItemPaint(int row, int column) {
Paint p = ((ItemPaintCategoryDataset) ds).getItemPaint(row, column);
if (p != null)
return p;
else
return getSeriesPaint(row);
}
} : new BarRenderer3D();
plot = new CategoryPlot((CategoryDataset) ds, (CategoryAxis)categoryAxis, (ValueAxis)valueAxis, (CategoryItemRenderer)renderer);
if(chartConfig.getType() == ChartConfig.VERTICAL_BAR3D_TYPE)
((CategoryPlot) plot).setOrientation(PlotOrientation.VERTICAL);
else
((CategoryPlot) plot).setOrientation(PlotOrientation.HORIZONTAL);
break;
case ChartConfig.STACKED_VERTICAL_BAR3D_TYPE:
case ChartConfig.STACKED_HORIZONTAL_BAR3D_TYPE:
categoryAxis = new CategoryAxis3D(chartConfig.getCategoryTitle());
valueAxis = new NumberAxis3D(chartConfig.getSerieTitle());
renderer = (ds instanceof ItemPaintCategoryDataset) ? new StackedBarRenderer3D() {
public Paint getItemPaint(int row, int column) {
Paint p = ((ItemPaintCategoryDataset) ds).getItemPaint(row, column);
if (p != null)
return p;
else
return getSeriesPaint(row);
}
} : new StackedBarRenderer3D();
plot = new CategoryPlot((CategoryDataset) ds, (CategoryAxis)categoryAxis, (ValueAxis)valueAxis,(CategoryItemRenderer) renderer);
if(chartConfig.getType() == ChartConfig.STACKED_VERTICAL_BAR3D_TYPE)
((CategoryPlot) plot).setOrientation(PlotOrientation.VERTICAL);
else
((CategoryPlot) plot).setOrientation(PlotOrientation.HORIZONTAL);
break;
case ChartConfig.PIE_TYPE:
case ChartConfig.PIE3D_TYPE:
categoryAxis = null;
valueAxis = null;
renderer = null;
ExtendedPieDataset pds = (ExtendedPieDataset) ds;
plot = chartConfig.getType() == ChartConfig.PIE_TYPE ? new PiePlot(pds) : new PiePlot3D(pds);
PiePlot pp = (PiePlot) plot;
pp.setLabelGenerator(new StandardPieSectionLabelGenerator());
for (int i = 0; i < pds.getItemCount(); i++) {
Paint p = pds.getPaint(i);
if (p != null)
pp.setSectionPaint(i, p);
pp.setExplodePercent(i, pds.getExplodePercent(i));
Paint paint = pds.getPaint(i);
if (paint != null)
pp.setSectionPaint(i, paint);
}
break;
case ChartConfig.XY_LINE_TYPE:
renderer = new XYLineAndShapeRenderer(true,false);
plot = new XYPlot((XYDataset) ds, (ValueAxis)categoryAxis, (ValueAxis)valueAxis, (XYLineAndShapeRenderer) renderer);
break;
case ChartConfig.TIME_SERIES_TYPE:
renderer = new XYLineAndShapeRenderer(true,false);
plot = new XYPlot((XYDataset) ds, (DateAxis)categoryAxis, (ValueAxis)valueAxis, (XYLineAndShapeRenderer) renderer);
break;
default:
throw new OXFException("Chart Type not supported");
}
if (categoryAxis != null) {
categoryAxis.setLabelPaint(chartConfig.getTitleColor());
categoryAxis.setTickLabelPaint(chartConfig.getTitleColor());
categoryAxis.setTickMarkPaint(chartConfig.getTitleColor());
if(categoryAxis instanceof RestrictedNumberAxis) {
((RestrictedNumberAxis)categoryAxis).setMaxTicks(chartConfig.getMaxNumOfLabels());
((RestrictedNumberAxis)categoryAxis).adjustTickUnits();
}
if (categoryAxis instanceof CategoryAxis && chartConfig.getCategoryMargin() != 0)
((CategoryAxis)categoryAxis).setCategoryMargin(chartConfig.getCategoryMargin());
}
if (valueAxis != null) {
valueAxis.setLabelPaint(chartConfig.getTitleColor());
valueAxis.setTickLabelPaint(chartConfig.getTitleColor());
valueAxis.setTickMarkPaint(chartConfig.getTitleColor());
((RestrictedNumberAxis)valueAxis).setMaxTicks(chartConfig.getMaxNumOfLabels());
((RestrictedNumberAxis)valueAxis).adjustTickUnits();
}
if (renderer != null) {
if(renderer instanceof XYLineAndShapeRenderer) {
((XYLineAndShapeRenderer) renderer).setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());
}
else {
((CategoryItemRenderer) renderer).setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
}
if (renderer instanceof BarRenderer)
((BarRenderer) renderer).setItemMargin(chartConfig.getBarMargin());
int j = 0;
for (Iterator i = chartConfig.getValueIterator(); i.hasNext();) {
Value v = (Value) i.next();
renderer.setSeriesPaint(j, v.getColor());
j++;
}
}
plot.setOutlinePaint(chartConfig.getTitleColor());
CustomLegend legend = chartConfig.getLegendConfig();
chart = new JFreeChart(chartConfig.getTitle(), TextTitle.DEFAULT_FONT, plot, false);
if(legend.isVisible()) {
legend.setSources(new LegendItemSource[] {plot});
chart.addLegend(legend);
}
chart.setBackgroundPaint(chartConfig.getBackgroundColor());
TextTitle textTitle = new TextTitle(chartConfig.getTitle(),TextTitle.DEFAULT_FONT,chartConfig.getTitleColor(),
TextTitle.DEFAULT_POSITION, TextTitle.DEFAULT_HORIZONTAL_ALIGNMENT,TextTitle.DEFAULT_VERTICAL_ALIGNMENT,
TextTitle.DEFAULT_PADDING);
chart.setTitle(textTitle);
return chart;
}
protected static class ChartConfig {
public static final int VERTICAL_BAR_TYPE = 0;
public static final int HORIZONTAL_BAR_TYPE = 1;
public static final int STACKED_VERTICAL_BAR_TYPE = 2;
public static final int STACKED_HORIZONTAL_BAR_TYPE = 3;
public static final int LINE_TYPE = 4;
public static final int AREA_TYPE = 5;
public static final int VERTICAL_BAR3D_TYPE = 6;
public static final int HORIZONTAL_BAR3D_TYPE = 7;
public static final int STACKED_VERTICAL_BAR3D_TYPE = 8;
public static final int STACKED_HORIZONTAL_BAR3D_TYPE = 9;
public static final int PIE_TYPE = 10;
public static final int PIE3D_TYPE = 11;
public static final int XY_LINE_TYPE = 12;
public static final int TIME_SERIES_TYPE = 13;
private int type;
private String title;
private String map;
private String categoryTitle;
private String serieTitle;
private double categoryMargin;
private Color titleColor;
private Color backgroundColor;
private double barMargin;
private int maxNumOfLabels = 10;
private String dateFormat;
private CategoryLabelPositions categoryLabelPosition = CategoryLabelPositions.STANDARD;
private CustomLegend legendConfig;
private double categoryLabelAngle = 0;
private List values = new ArrayList();
private int xSize;
private int ySize;
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategoryTitle() {
return categoryTitle;
}
public void setCategoryTitle(String categoryTitle) {
this.categoryTitle = categoryTitle;
}
public String getSerieTitle() {
return serieTitle;
}
public void setSerieTitle(String serieTitle) {
this.serieTitle = serieTitle;
}
public int getxSize() {
return xSize;
}
public void setxSize(int xSize) {
this.xSize = xSize;
}
public int getySize() {
return ySize;
}
public void setySize(int ySize) {
this.ySize = ySize;
}
public Color getTitleColor() {
return titleColor;
}
public void setTitleColor(Color titleColor) {
this.titleColor = titleColor;
}
public Color getBackgroundColor() {
return backgroundColor;
}
public void setBackgroundColor(Color backgroundColor) {
this.backgroundColor = backgroundColor;
}
public void addValue(String title, String categories, String series, String colors, String explodedPercent, Paint color) {
values.add(new Value(title, categories, series, colors, explodedPercent, color));
}
public Iterator getValueIterator() {
return values.iterator();
}
public String getMap() {
return map;
}
public void setMap(String map) {
this.map = map;
}
public double getBarMargin() {
return barMargin;
}
public void setBarMargin(double barMargin) {
this.barMargin = barMargin;
}
public CustomLegend getLegendConfig() {
return legendConfig;
}
public void setLegendConfig(CustomLegend legendConfig) {
this.legendConfig = legendConfig;
}
public double getCategoryMargin() {
return categoryMargin;
}
public void setCategoryMargin(double categoryMargin) {
this.categoryMargin = categoryMargin;
}
public CategoryLabelPositions getCategoryLabelPosition() {
return categoryLabelPosition;
}
public void setCategoryLabelPosition(CategoryLabelPositions categoryLabelPosition) {
this.categoryLabelPosition = categoryLabelPosition;
}
public int getMaxNumOfLabels() {
return maxNumOfLabels;
}
public void setMaxNumOfLabels(int maxNumOfLabels) {
this.maxNumOfLabels = maxNumOfLabels;
}
public String getDateFormat() {
return dateFormat;
}
public void setDateFormat(String dateFormat) {
this.dateFormat = dateFormat;
}
public double getCategoryLabelAngle() {
return categoryLabelAngle;
}
public void setCategoryLabelAngle(double categoryLabelAngle) {
this.categoryLabelAngle = categoryLabelAngle;
}
}
protected static class Value {
private String title;
private String categories;
private String series;
private String colors;
private String explodedPercents;
private Paint color;
public Value(String title, String categories, String series, String colors, String explodedPercents, Paint color) {
this.title = title;
this.categories = categories;
this.series = series;
this.colors = colors;
this.explodedPercents = explodedPercents;
this.color = color;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategories() {
return categories;
}
public void setCategories(String categories) {
this.categories = categories;
}
public String getSeries() {
return series;
}
public void setSeries(String series) {
this.series = series;
}
public Paint getColor() {
return color;
}
public void setColor(Paint color) {
this.color = color;
}
public String getColors() {
return colors;
}
public void setColors(String colors) {
this.colors = colors;
}
public String getExplodedPercents() {
return explodedPercents;
}
public void setExplodedPercents(String explodedPercents) {
this.explodedPercents = explodedPercents;
}
}
protected static class CustomLegend extends LegendTitle {
private boolean visible = true;
private LegendItemCollection legendItems = new LegendItemCollection();
public static final Font DEFAULT_TITLE_FONT = new Font("SansSerif", 1, 11);
public static Paint DEFAULT_BACKGROUND_PAINT = Color.white;
public static Paint DEFAULT_OUTLINE_PAINT = Color.gray;
public static final Stroke DEFAULT_OUTLINE_STROKE = new BasicStroke();
public CustomLegend(Plot plot) {
super(plot);
}
public void addItem(String label, Color color) {
LegendItem legendItem = new LegendItem(label,label,label,label,AbstractRenderer.DEFAULT_SHAPE,
color,AbstractRenderer.DEFAULT_OUTLINE_STROKE,
AbstractRenderer.DEFAULT_OUTLINE_PAINT);
legendItems.add(legendItem);
}
public boolean hasItems() {
return legendItems.getItemCount() > 0;
}
public Iterator itemIterator() {
return legendItems.iterator();
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public Rectangle2D draw(Graphics2D g2, Rectangle2D available, ChartRenderingInfo info) {
boolean horizontal = RectangleEdge.isLeftOrRight(getPosition());
boolean inverted = RectangleEdge.isTopOrBottom(getPosition());
RectangleInsets insets = getFrame().getInsets();
String title = null;
if ((legendItems != null) && (legendItems.getItemCount() > 0)) {
DrawableLegendItem legendTitle = null;
Rectangle2D legendArea = new Rectangle2D.Double();
double availableWidth = available.getWidth();
double availableHeight = available.getHeight();
// the translation point for the origin of the drawing system
Point2D translation = new Point2D.Double();
// Create buffer for individual rectangles within the legend
DrawableLegendItem[] items = new DrawableLegendItem[legendItems.getItemCount()];
// Compute individual rectangles in the legend, translation point as well
// as the bounding box for the legend.
if (horizontal) {
double xstart = available.getX() ;
double xlimit = available.getMaxX();
double maxRowWidth = 0;
double xoffset = 0;
double rowHeight = 0;
double totalHeight = 0;
boolean startingNewRow = true;
if (title != null && !title.equals("")) {
g2.setFont(CustomLegend.DEFAULT_TITLE_FONT);
LegendItem titleItem = new LegendItem(title,title,title,title,AbstractRenderer.DEFAULT_SHAPE,
Color.black,AbstractRenderer.DEFAULT_OUTLINE_STROKE,
AbstractRenderer.DEFAULT_OUTLINE_PAINT);
legendTitle = createDrawableLegendItem(g2, titleItem,xoffset,totalHeight);
rowHeight = Math.max(rowHeight, legendTitle.getHeight());
xoffset += legendTitle.getWidth();
}
g2.setFont(LegendTitle.DEFAULT_ITEM_FONT);
for (int i = 0; i < legendItems.getItemCount(); i++) {
items[i] = createDrawableLegendItem(g2, legendItems.get(i),
xoffset, totalHeight);
if ((!startingNewRow)
&& (items[i].getX() + items[i].getWidth() + xstart > xlimit)) {
maxRowWidth = Math.max(maxRowWidth, xoffset);
xoffset = 0;
totalHeight += rowHeight;
i--;
startingNewRow = true;
} else {
rowHeight = Math.max(rowHeight, items[i].getHeight());
xoffset += items[i].getWidth();
startingNewRow = false;
}
}
maxRowWidth = Math.max(maxRowWidth, xoffset);
totalHeight += rowHeight;
// Create the bounding box
legendArea = new Rectangle2D.Double(0, 0, maxRowWidth, totalHeight);
// The yloc point is the variable part of the translation point
// for horizontal legends. xloc is constant.
double yloc = (inverted)
? available.getMaxY() - totalHeight
- insets.calculateBottomOutset(availableHeight)
: available.getY() + insets.calculateTopOutset(availableHeight);
double xloc = available.getX() + available.getWidth() / 2 - maxRowWidth / 2;
// Create the translation point
translation = new Point2D.Double(xloc, yloc);
} else { // vertical...
double totalHeight = 0;
double maxWidth = 0;
if (title != null && !title.equals("")) {
g2.setFont(CustomLegend.DEFAULT_TITLE_FONT);
LegendItem titleItem = new LegendItem(title,title,title,title,AbstractRenderer.DEFAULT_SHAPE,
Color.black,AbstractRenderer.DEFAULT_OUTLINE_STROKE,
AbstractRenderer.DEFAULT_OUTLINE_PAINT);
legendTitle = createDrawableLegendItem(g2, titleItem, 0,totalHeight);
totalHeight += legendTitle.getHeight();
maxWidth = Math.max(maxWidth, legendTitle.getWidth());
}
g2.setFont(LegendTitle.DEFAULT_ITEM_FONT);
for (int i = 0; i < items.length; i++) {
items[i] = createDrawableLegendItem(g2, legendItems.get(i),
0, totalHeight);
totalHeight += items[i].getHeight();
maxWidth = Math.max(maxWidth, items[i].getWidth());
}
// Create the bounding box
legendArea = new Rectangle2D.Float(0, 0, (float) maxWidth, (float) totalHeight);
// The xloc point is the variable part of the translation point
// for vertical legends. yloc is constant.
double xloc = (inverted)
? available.getMaxX() - maxWidth - insets.calculateRightOutset(availableWidth)
: available.getX() + insets.calculateLeftOutset(availableWidth);
double yloc = available.getY() + (available.getHeight() / 2) - (totalHeight / 2);
// Create the translation point
translation = new Point2D.Double(xloc, yloc);
}
// Move the origin of the drawing to the appropriate location
g2.translate(translation.getX(), translation.getY());
// Draw the legend's bounding box
g2.setPaint(CustomLegend.DEFAULT_BACKGROUND_PAINT);
g2.fill(legendArea);
g2.setPaint(CustomLegend.DEFAULT_OUTLINE_PAINT);
g2.setStroke(CustomLegend.DEFAULT_OUTLINE_STROKE);
g2.draw(legendArea);
// draw legend title
if (legendTitle != null) {
// XXX dsm - make title bold?
g2.setPaint(legendTitle.getItem().getFillPaint());
g2.setPaint(Color.black);
g2.setFont(CustomLegend.DEFAULT_TITLE_FONT);
g2.drawString(legendTitle.getItem().getLabel(),
(float) legendTitle.getLabelPosition().getX(),
(float) legendTitle.getLabelPosition().getY());
}
// Draw individual series elements
for (int i = 0; i < items.length; i++) {
g2.setPaint(items[i].getItem().getFillPaint());
Shape keyBox = items[i].getMarker();
g2.fill(keyBox);
g2.setPaint(Color.black);
g2.setFont(LegendTitle.DEFAULT_ITEM_FONT);
g2.drawString(items[i].getItem().getLabel(),
(float) items[i].getLabelPosition().getX(),
(float) items[i].getLabelPosition().getY());
}
// translate the origin back to what it was prior to drawing the legend
g2.translate(-translation.getX(), -translation.getY());
if (horizontal) {
// The remaining drawing area bounding box will have the same
// x origin, width and height independent of the anchor's
// location. The variable is the y coordinate. If the anchor is
// SOUTH, the y coordinate is simply the original y coordinate
// of the available area. If it is NORTH, we adjust original y
// by the total height of the legend and the initial gap.
double yy = available.getY();
double yloc = (inverted) ? yy
: yy + legendArea.getHeight()
+ insets.calculateBottomOutset(availableHeight);
// return the remaining available drawing area
return new Rectangle2D.Double(available.getX(), yloc, availableWidth,
availableHeight - legendArea.getHeight()
- insets.calculateTopOutset(availableHeight)
- insets.calculateBottomOutset(availableHeight));
} else {
// The remaining drawing area bounding box will have the same
// y origin, width and height independent of the anchor's
// location. The variable is the x coordinate. If the anchor is
// EAST, the x coordinate is simply the original x coordinate
// of the available area. If it is WEST, we adjust original x
// by the total width of the legend and the initial gap.
double xloc = (inverted) ? available.getX()
: available.getX()
+ legendArea.getWidth()
+ insets.calculateLeftOutset(availableWidth)
+ insets.calculateRightOutset(availableWidth);
// return the remaining available drawing area
return new Rectangle2D.Double(xloc, available.getY(),
availableWidth - legendArea.getWidth()
- insets.calculateLeftOutset(availableWidth)
- insets.calculateRightOutset(availableWidth),
availableHeight);
}
} else {
return available;
}
}
private DrawableLegendItem createDrawableLegendItem(Graphics2D graphics,
LegendItem legendItem,
double x, double y) {
int innerGap = 2;
FontMetrics fm = graphics.getFontMetrics();
LineMetrics lm = fm.getLineMetrics(legendItem.getLabel(), graphics);
float textAscent = lm.getAscent();
float lineHeight = textAscent + lm.getDescent() + lm.getLeading();
DrawableLegendItem item = new DrawableLegendItem(legendItem);
float xloc = (float) (x + innerGap + 1.15f * lineHeight);
float yloc = (float) (y + innerGap + 0.15f * lineHeight + textAscent);
item.setLabelPosition(new Point2D.Float(xloc, yloc));
float boxDim = lineHeight * 0.70f;
xloc = (float) (x + innerGap + 0.15f * lineHeight);
yloc = (float) (y + innerGap + 0.15f * lineHeight);
item.setMarker(new Rectangle2D.Float(xloc, yloc, boxDim, boxDim));
float width = (float) (item.getLabelPosition().getX() - x
+ fm.getStringBounds(legendItem.getLabel(), graphics).getWidth()
+ 0.5 * textAscent);
float height = (2 * innerGap + lineHeight);
item.setBounds(x, y, width, height);
return item;
}
}
protected static class ExtendedPieDataset extends AbstractDataset implements PieDataset {
private List data = new ArrayList();
class Value {
public Comparable key;
public Number value;
public Paint paint = null;
public double explodePercent = 0;
}
public void setValue(Comparable key, Number value, Paint paint, double explode) {
Value v = new Value();
v.key = key;
v.value = value;
v.paint = paint;
v.explodePercent = explode;
int keyIndex = getIndex(key);
if (keyIndex >= 0) {
data.set(keyIndex, v);
} else {
data.add(v);
}
fireDatasetChanged();
}
public Comparable getKey(int index) {
return ((Value) data.get(index)).key;
}
public int getIndex(Comparable key) {
int result = -1;
int i = 0;
Iterator iterator = this.data.iterator();
while (iterator.hasNext()) {
Value v = (Value) iterator.next();
if (v.key.equals(key)) {
result = i;
}
i++;
}
return result;
}
public List getKeys() {
List keys = new ArrayList();
for (Iterator i = data.iterator(); i.hasNext();)
keys.add(((Value) i.next()).key);
return keys;
}
public Number getValue(Comparable key) {
int i = getIndex(key);
if (i != -1)
return ((Value) data.get(i)).value;
else
return null;
}
public int getItemCount() {
return data.size();
}
public Number getValue(int item) {
return ((Value) data.get(item)).value;
}
public Paint getPaint(int item) {
return ((Value) data.get(item)).paint;
}
public double getExplodePercent(int item) {
return ((Value) data.get(item)).explodePercent;
}
}
protected static class ItemPaintCategoryDataset extends DefaultCategoryDataset {
private List rowValues = new ArrayList();
public void addValue(double value, Paint paint, Comparable rowKey, Comparable columnKey) {
super.addValue(value, rowKey, columnKey);
addPaintValue(paint, rowKey, columnKey);
}
public void addValue(Number value, Paint paint, Comparable rowKey, Comparable columnKey) {
super.addValue(value, rowKey, columnKey);
addPaintValue(paint, rowKey, columnKey);
}
public Paint getItemPaint(int rowIndex, int columnIndex) {
try {
List columnValues = (List) rowValues.get(rowIndex);
return (Paint) columnValues.get(columnIndex);
} catch (IndexOutOfBoundsException e) {
return null;
}
}
private void addPaintValue(Paint paint, Comparable rowKey, Comparable columnKey) {
int rowIndex = getRowIndex(rowKey);
int colIndex = getColumnIndex(columnKey);
List colValues;
if(rowIndex < rowValues.size())
colValues = (List) rowValues.get(rowIndex);
else {
colValues = new ArrayList();
rowValues.add(rowIndex, colValues);
}
colValues.add(colIndex, paint);
}
}
protected static Color getRGBColor(String rgb) {
try {
return new Color(Integer.parseInt(rgb.substring(1), 16));
} catch (NumberFormatException e) {
throw new OXFException("Can't parse RGB color: " + rgb, e);
}
}
protected static class RestrictedNumberAxis extends NumberAxis{
private int maxTicks = NumberAxis.MAXIMUM_TICK_COUNT;
/**
* Creates a Number axis with the specified label.
*
* @param label the axis label (<code>null</code> permitted).
*/
public RestrictedNumberAxis(String label) {
super(label);
}
public int getMaxTicks() {
return maxTicks;
}
public void setMaxTicks(int maxTicks) {
this.maxTicks = maxTicks;
}
protected int getVisibleTickCount() {
double unit = getTickUnit().getSize();
Range range = getRange();
return (int)(Math.floor(range.getUpperBound() / unit)
- Math.ceil(range.getLowerBound() / unit) + 1);
}
protected void adjustTickUnits() {
int tickUnit = getVisibleTickCount()/maxTicks;
if(tickUnit != 0) {
super.setTickUnit(new NumberTickUnit(tickUnit));
}
}
}
}
| Fix: 90 deg angle was not working, forgot line
| src/java/org/orbeon/oxf/processor/serializer/legacy/JFreeChartSerializer.java | Fix: 90 deg angle was not working, forgot line | |
Java | lgpl-2.1 | dc2780afca438af240241c8b60ff15c88540e4ac | 0 | xwiki/xwiki-enterprise,xwiki/xwiki-enterprise | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.test.ui;
import junit.framework.Assert;
import org.junit.Test;
import org.xwiki.test.ui.framework.AbstractAdminAuthenticatedTest;
import org.xwiki.test.ui.framework.elements.HistoryTab;
import org.xwiki.test.ui.framework.elements.ViewPage;
import org.xwiki.test.ui.framework.elements.editor.WikiEditPage;
/**
* Verify versioning features of documents and attachments.
*
* @version $Id$
* @since 3.1M2
*/
public class VersionTest extends AbstractAdminAuthenticatedTest
{
private static final String PAGE_NAME = "HistoryTest";
private static final String SPACE_NAME = "HistorySpaceTest";
private static final String TITLE = "Page Title";
private static final String CONTENT1 = "First version of Content";
private static final String CONTENT2 = "Second version of Content";
@Test
public void testRollbackToFirstVersion() throws Exception
{
getUtil().deletePage(SPACE_NAME, PAGE_NAME);
// Create first version of the page
ViewPage vp = getUtil().createPage(SPACE_NAME, PAGE_NAME, CONTENT1, TITLE);
// Adds second version
WikiEditPage wikiEditPage = vp.editWiki();
wikiEditPage.setContent(CONTENT2);
wikiEditPage.clickSaveAndView();
// Verify that we can rollback to the first version
HistoryTab historyTab = vp.openHistoryDocExtraPane();
vp = historyTab.rollbackToVersion("1.1");
// Try to debug flickering test. From time to time the assert fails, which means the rollbacks somehow fails.
// Since I (Vincent) cannot guess why I'm taking a screenshot to see what's on the screen when it fails.
try {
Assert.assertEquals("First version of Content", vp.getContent());
} catch (Error error) {
getUtil().takeScreenshot();
throw error;
}
historyTab = vp.openHistoryDocExtraPane();
Assert.assertEquals("Rollback to version 1.1", historyTab.getCurrentVersionComment());
Assert.assertEquals("Administrator", historyTab.getCurrentAuthor());
}
}
| xwiki-enterprise-test/xwiki-enterprise-test-ui/src/test/it/org/xwiki/test/ui/VersionTest.java | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.test.ui;
import junit.framework.Assert;
import org.junit.Test;
import org.xwiki.test.ui.framework.AbstractAdminAuthenticatedTest;
import org.xwiki.test.ui.framework.elements.HistoryTab;
import org.xwiki.test.ui.framework.elements.ViewPage;
import org.xwiki.test.ui.framework.elements.editor.WikiEditPage;
/**
* Verify versioning features of documents and attachments.
*
* @version $Id$
* @since 3.1M2
*/
public class VersionTest extends AbstractAdminAuthenticatedTest
{
private static final String PAGE_NAME = "HistoryTest";
private static final String SPACE_NAME = "HistorySpaceTest";
private static final String TITLE = "Page Title";
private static final String CONTENT1 = "First version of Content";
private static final String CONTENT2 = "Second version of Content";
@Test
public void testRollbackToFirstVersion() throws Exception
{
getUtil().deletePage(SPACE_NAME, PAGE_NAME);
// Create first version of the page
ViewPage vp = getUtil().createPage(SPACE_NAME, PAGE_NAME, CONTENT1, TITLE);
// Adds second version
WikiEditPage wikiEditPage = vp.editWiki();
wikiEditPage.setContent(CONTENT2);
wikiEditPage.clickSaveAndView();
// Verify that we can rollback to the first version
HistoryTab historyTab = vp.openHistoryDocExtraPane();
vp = historyTab.rollbackToVersion("1.1");
// @Ignore for the moment since it's causing some flickering. Needs to be fixed.
// Assert.assertEquals("First version of Content", vp.getContent());
historyTab = vp.openHistoryDocExtraPane();
Assert.assertEquals("Rollback to version 1.1", historyTab.getCurrentVersionComment());
Assert.assertEquals("Administrator", historyTab.getCurrentAuthor());
}
}
| try to debug flicker
| xwiki-enterprise-test/xwiki-enterprise-test-ui/src/test/it/org/xwiki/test/ui/VersionTest.java | try to debug flicker | |
Java | lgpl-2.1 | a45c792a53bbe6b635498b56e84fe07ec9dc4633 | 0 | open-eid/MOPP-Android | package ee.ria.DigiDoc.configuration.util;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
import ee.ria.DigiDoc.configuration.BuildConfig;
import timber.log.Timber;
public class FileUtils {
private static final Logger logger = Logger.getLogger(FileUtils.class.getName());
public static String readFileContent(String filePath) {
try (FileInputStream fileInputStream = new FileInputStream(filePath)) {
return readFileContent(fileInputStream);
} catch (IOException e) {
throw new IllegalStateException("Failed to read content of cached file '" + filePath + "'", e);
}
}
public static String readFileContent(InputStream inputStream) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
StringBuilder sb = new StringBuilder();
int i;
while((i = reader.read()) != -1) {
sb.append((char) i);
}
return sb.toString().trim();
} catch (IOException e) {
throw new IllegalStateException("Failed to read content of cached file", e);
}
}
public static byte[] readFileContentBytes(String filePath) {
try (FileInputStream fileInputStream = new FileInputStream(filePath)) {
return readFileContentBytes(fileInputStream);
} catch (IOException e) {
throw new IllegalStateException("Failed to read content of cached file '" + filePath + "'", e);
}
}
public static byte[] readFileContentBytes(InputStream inputStream) {
try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()){
int nRead;
byte[] data = new byte[16384];
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
return buffer.toByteArray();
} catch (IOException e) {
throw new IllegalStateException("Failed to read content of cached file", e);
}
}
public static void storeFile(String filePath, String content) {
File file = new File(filePath);
boolean isDirsCreated = file.getParentFile().mkdirs();
if (isDirsCreated) {
logMessage(Level.INFO, "Directories created for " + filePath);
}
try (FileOutputStream fileStream = new FileOutputStream(file.getAbsoluteFile());
OutputStreamWriter writer = new OutputStreamWriter(fileStream, StandardCharsets.UTF_8)) {
writer.write(content);
} catch (IOException e) {
throw new IllegalStateException("Failed to store file '" + filePath + "'!", e);
}
}
public static void storeFile(String filePath, byte[] content) {
File file = new File(filePath);
boolean isDirsCreated = file.getParentFile().mkdirs();
if (isDirsCreated) {
logMessage(Level.INFO, "Directories created for " + filePath);
}
try (FileOutputStream os = new FileOutputStream(file)) {
os.write(content);
} catch (IOException e) {
throw new IllegalStateException("Failed to store file '" + filePath + "'!", e);
}
}
public static void createDirectoryIfNotExist(String directory) {
File destinationDirectory = new File(directory);
if (!destinationDirectory.exists()) {
boolean isDirsCreated = destinationDirectory.mkdirs();
if (isDirsCreated) {
logMessage(Level.INFO, "Directories created for " + directory);
}
}
}
public static boolean fileExists(String filePath) {
return new File(filePath).exists();
}
public static void removeFile(String filePath) {
File fileToDelete = new File(filePath);
if (fileToDelete.exists()) {
boolean isFileDeleted = fileToDelete.delete();
if (isFileDeleted) {
logMessage(Level.INFO, "File deleted: " + filePath);
}
}
}
public static void writeToFile(BufferedReader reader, String destinationPath, String fileName) {
try (FileOutputStream fileStream = new FileOutputStream(new File(destinationPath + File.separator + fileName));
OutputStreamWriter writer = new OutputStreamWriter(fileStream, StandardCharsets.UTF_8)) {
String fileLine;
while ((fileLine = reader.readLine()) != null) {
writer.write(fileLine + System.getProperty("line.separator"));
}
} catch (IOException e) {
Timber.e(e, "Failed to open file: %s", fileName);
}
}
private static void logMessage(Level level, String message) {
if (BuildConfig.DEBUG && logger.isLoggable(level)) {
logger.log(level, message);
}
}
}
| configuration-lib/src/main/java/ee/ria/DigiDoc/configuration/util/FileUtils.java | package ee.ria.DigiDoc.configuration.util;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import timber.log.Timber;
public class FileUtils {
public static String readFileContent(String filePath) {
try (FileInputStream fileInputStream = new FileInputStream(filePath)) {
return readFileContent(fileInputStream);
} catch (IOException e) {
throw new IllegalStateException("Failed to read content of cached file '" + filePath + "'", e);
}
}
public static String readFileContent(InputStream inputStream) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
StringBuilder sb = new StringBuilder();
int i;
while((i = reader.read()) != -1) {
sb.append((char) i);
}
return sb.toString().trim();
} catch (IOException e) {
throw new IllegalStateException("Failed to read content of cached file", e);
}
}
public static byte[] readFileContentBytes(String filePath) {
try (FileInputStream fileInputStream = new FileInputStream(filePath)) {
return readFileContentBytes(fileInputStream);
} catch (IOException e) {
throw new IllegalStateException("Failed to read content of cached file '" + filePath + "'", e);
}
}
public static byte[] readFileContentBytes(InputStream inputStream) {
try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()){
int nRead;
byte[] data = new byte[16384];
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
return buffer.toByteArray();
} catch (IOException e) {
throw new IllegalStateException("Failed to read content of cached file", e);
}
}
public static void storeFile(String filePath, String content) {
File file = new File(filePath);
boolean isDirsCreated = file.getParentFile().mkdirs();
if (isDirsCreated) {
Timber.d("Directories created for %s", filePath);
}
try (FileOutputStream fileStream = new FileOutputStream(file.getAbsoluteFile());
OutputStreamWriter writer = new OutputStreamWriter(fileStream, StandardCharsets.UTF_8)) {
writer.write(content);
} catch (IOException e) {
throw new IllegalStateException("Failed to store file '" + filePath + "'!", e);
}
}
public static void storeFile(String filePath, byte[] content) {
File file = new File(filePath);
boolean isDirsCreated = file.getParentFile().mkdirs();
if (isDirsCreated) {
Timber.d("Directories created for %s", filePath);
}
try (FileOutputStream os = new FileOutputStream(file)) {
os.write(content);
} catch (IOException e) {
throw new IllegalStateException("Failed to store file '" + filePath + "'!", e);
}
}
public static void createDirectoryIfNotExist(String directory) {
File destinationDirectory = new File(directory);
if (!destinationDirectory.exists()) {
boolean isDirsCreated = destinationDirectory.mkdirs();
if (isDirsCreated) {
Timber.d("Directories created for %s", directory);
}
}
}
public static boolean fileExists(String filePath) {
return new File(filePath).exists();
}
public static void removeFile(String filePath) {
File fileToDelete = new File(filePath);
if (fileToDelete.exists()) {
boolean isFileDeleted = fileToDelete.delete();
if (isFileDeleted) {
Timber.d("File %s deleted", filePath);
}
}
}
public static void writeToFile(BufferedReader reader, String destinationPath, String fileName) {
try (FileOutputStream fileStream = new FileOutputStream(new File(destinationPath + File.separator + fileName));
OutputStreamWriter writer = new OutputStreamWriter(fileStream, StandardCharsets.UTF_8)) {
String fileLine;
while ((fileLine = reader.readLine()) != null) {
writer.write(fileLine + System.getProperty("line.separator"));
}
} catch (IOException e) {
Timber.e(e, "Failed to open file: %s", fileName);
}
}
}
| Logging fixes
* MOPPAND-713
| configuration-lib/src/main/java/ee/ria/DigiDoc/configuration/util/FileUtils.java | Logging fixes | |
Java | apache-2.0 | ba31f4604ae33cb6ba6e632095f4b942fae20b9d | 0 | rmpestano/cukedoctor,rmpestano/cukedoctor,rmpestano/cukedoctor | package com.github.cukedoctor.extension;
import static com.github.cukedoctor.extension.CukedoctorExtensionRegistry.*;
import java.util.Map;
import org.asciidoctor.ast.Document;
import org.asciidoctor.extension.Postprocessor;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
/**
* Created by pestano on 20/07/15.
* extends html document styles
*/
public class CukedoctorStyleExtension extends Postprocessor{
public CukedoctorStyleExtension(Map<String, Object> config) {
super(config);
}
@Override
public String process(Document document, String output) {
if (document.basebackend("html")) {
org.jsoup.nodes.Document doc = Jsoup.parse(output, "UTF-8");
Element contentElement = doc.getElementById("footer");
if (System.getProperty(STYLE_DISABLE_EXT_KEY) == null) {
addStyleClass(contentElement);
}
return doc.html();
} else {
return output;
}
}
private void addStyleClass(Element contentElement) {
String styleClass = " <style> \n" + "\n" + "#content:padding:0!important;\n" + ".sidebarblock, .sectionbody, .content{\n" + "overflow:auto!important;\n" + "}\n";
contentElement.after(styleClass);
}
}
| cukedoctor-extension/src/main/java/com/github/cukedoctor/extension/CukedoctorStyleExtension.java | package com.github.cukedoctor.extension;
import static com.github.cukedoctor.extension.CukedoctorExtensionRegistry.*;
import java.util.Map;
import org.asciidoctor.ast.Document;
import org.asciidoctor.extension.Postprocessor;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
/**
* Created by pestano on 20/07/15.
* extends html document styles
*/
public class CukedoctorStyleExtension extends Postprocessor{
public CukedoctorStyleExtension(Map<String, Object> config) {
super(config);
}
@Override
public String process(Document document, String output) {
if(document.basebackend("html") ){
org.jsoup.nodes.Document doc = Jsoup.parse(output, "UTF-8");
Element contentElement = doc.getElementById("footer");
if(System.getProperty(STYLE_DISABLE_EXT_KEY) == null) {
addStyleClass(contentElement);
}
return doc.html();
}else{
return output;
}
}
private void addStyleClass(Element contentElement) {
String styleClass = " <style> \n" +
"\n" +
".sidebarblock, .sectionbody, .content{\n" +
"overflow:auto!important;\n" +
"}\n";
contentElement.after(styleClass);
}
}
| avoid horizontal bar in summary section
| cukedoctor-extension/src/main/java/com/github/cukedoctor/extension/CukedoctorStyleExtension.java | avoid horizontal bar in summary section | |
Java | apache-2.0 | f2cdfde4164a053fe8d6e00e6a80a361ed07941b | 0 | cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x | /*
* Copyright 2002-2007 the original author or authors.
*
* 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 org.springframework.transaction.interceptor;
import java.lang.reflect.Method;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.transaction.MockCallbackPreferringTransactionManager;
import org.springframework.transaction.NoTransactionException;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.TransactionSystemException;
import org.springframework.transaction.UnexpectedRollbackException;
import org.springframework.transaction.interceptor.TransactionAspectSupport.TransactionInfo;
/**
* Mock object based tests for transaction aspects.
* True unit test in that it tests how the transaction aspect uses
* the PlatformTransactionManager helper, rather than indirectly
* testing the helper implementation.
*
* This is a superclass to allow testing both the AOP Alliance MethodInterceptor
* and the AspectJ aspect.
*
* @author Rod Johnson
* @since 16.03.2003
*/
public abstract class AbstractTransactionAspectTests extends TestCase {
protected Method exceptionalMethod;
protected Method getNameMethod;
protected Method setNameMethod;
public AbstractTransactionAspectTests() {
try {
// Cache the methods we'll be testing
exceptionalMethod = ITestBean.class.getMethod("exceptional", new Class[] { Throwable.class });
getNameMethod = ITestBean.class.getMethod("getName", (Class[]) null);
setNameMethod = ITestBean.class.getMethod("setName", new Class[] { String.class} );
}
catch (NoSuchMethodException ex) {
throw new RuntimeException("Shouldn't happen", ex);
}
}
public void testNoTransaction() throws Exception {
MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class);
PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock();
// expect no calls
ptmControl.replay();
TestBean tb = new TestBean();
TransactionAttributeSource tas = new MapTransactionAttributeSource();
// All the methods in this class use the advised() template method
// to obtain a transaction object, configured with the given PlatformTransactionManager
// and transaction attribute source
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
checkTransactionStatus(false);
itb.getName();
checkTransactionStatus(false);
ptmControl.verify();
}
/**
* Check that a transaction is created and committed.
*/
public void testTransactionShouldSucceed() throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute();
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(getNameMethod, txatt);
TransactionStatus status = transactionStatusForNewTransaction();
MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class);
PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock();
// expect a transaction
ptm.getTransaction(txatt);
ptmControl.setReturnValue(status, 1);
ptm.commit(status);
ptmControl.setVoidCallable(1);
ptmControl.replay();
TestBean tb = new TestBean();
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
checkTransactionStatus(false);
itb.getName();
checkTransactionStatus(false);
ptmControl.verify();
}
/**
* Check that a transaction is created and committed using
* CallbackPreferringPlatformTransactionManager.
*/
public void testTransactionShouldSucceedWithCallbackPreference() throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute();
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(getNameMethod, txatt);
MockCallbackPreferringTransactionManager ptm = new MockCallbackPreferringTransactionManager();
TestBean tb = new TestBean();
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
checkTransactionStatus(false);
itb.getName();
checkTransactionStatus(false);
assertSame(txatt, ptm.getDefinition());
assertFalse(ptm.getStatus().isRollbackOnly());
}
public void testTransactionExceptionPropagatedWithCallbackPreference() throws Throwable {
TransactionAttribute txatt = new DefaultTransactionAttribute();
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(exceptionalMethod, txatt);
MockCallbackPreferringTransactionManager ptm = new MockCallbackPreferringTransactionManager();
TestBean tb = new TestBean();
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
checkTransactionStatus(false);
try {
itb.exceptional(new OptimisticLockingFailureException(""));
fail("Should have thrown OptimisticLockingFailureException");
}
catch (OptimisticLockingFailureException ex) {
// expected
}
checkTransactionStatus(false);
assertSame(txatt, ptm.getDefinition());
assertFalse(ptm.getStatus().isRollbackOnly());
}
/**
* Check that two transactions are created and committed.
*/
public void testTwoTransactionsShouldSucceed() throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute();
MapTransactionAttributeSource tas1 = new MapTransactionAttributeSource();
tas1.register(getNameMethod, txatt);
MapTransactionAttributeSource tas2 = new MapTransactionAttributeSource();
tas2.register(setNameMethod, txatt);
TransactionStatus status = transactionStatusForNewTransaction();
MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class);
PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock();
// expect a transaction
ptm.getTransaction(txatt);
ptmControl.setReturnValue(status, 2);
ptm.commit(status);
ptmControl.setVoidCallable(2);
ptmControl.replay();
TestBean tb = new TestBean();
ITestBean itb = (ITestBean) advised(tb, ptm, new TransactionAttributeSource[] {tas1, tas2});
checkTransactionStatus(false);
itb.getName();
checkTransactionStatus(false);
itb.setName("myName");
checkTransactionStatus(false);
ptmControl.verify();
}
/**
* Check that a transaction is created and committed.
*/
public void testTransactionShouldSucceedWithNotNew() throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute();
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(getNameMethod, txatt);
MockControl statusControl = MockControl.createControl(TransactionStatus.class);
TransactionStatus status = (TransactionStatus) statusControl.getMock();
MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class);
PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock();
// expect a transaction
ptm.getTransaction(txatt);
ptmControl.setReturnValue(status, 1);
ptm.commit(status);
ptmControl.setVoidCallable(1);
ptmControl.replay();
TestBean tb = new TestBean();
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
checkTransactionStatus(false);
// verification!?
itb.getName();
checkTransactionStatus(false);
ptmControl.verify();
}
public void testEnclosingTransactionWithNonTransactionMethodOnAdvisedInside() throws Throwable {
TransactionAttribute txatt = new DefaultTransactionAttribute();
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(exceptionalMethod, txatt);
TransactionStatus status = transactionStatusForNewTransaction();
MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class);
PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock();
// Expect a transaction
ptm.getTransaction(txatt);
ptmControl.setReturnValue(status, 1);
ptm.commit(status);
ptmControl.setVoidCallable(1);
ptmControl.replay();
final String spouseName = "innerName";
TestBean outer = new TestBean() {
public void exceptional(Throwable t) throws Throwable {
TransactionInfo ti = TransactionAspectSupport.currentTransactionInfo();
assertTrue(ti.hasTransaction());
assertEquals(spouseName, getSpouse().getName());
}
};
TestBean inner = new TestBean() {
public String getName() {
// Assert that we're in the inner proxy
TransactionInfo ti = TransactionAspectSupport.currentTransactionInfo();
assertFalse(ti.hasTransaction());
return spouseName;
}
};
ITestBean outerProxy = (ITestBean) advised(outer, ptm, tas);
ITestBean innerProxy = (ITestBean) advised(inner, ptm, tas);
outer.setSpouse(innerProxy);
checkTransactionStatus(false);
// Will invoke inner.getName, which is non-transactional
outerProxy.exceptional(null);
checkTransactionStatus(false);
ptmControl.verify();
}
public void testEnclosingTransactionWithNestedTransactionOnAdvisedInside() throws Throwable {
final TransactionAttribute outerTxatt = new DefaultTransactionAttribute();
final TransactionAttribute innerTxatt = new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_NESTED);
Method outerMethod = exceptionalMethod;
Method innerMethod = getNameMethod;
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(outerMethod, outerTxatt);
tas.register(innerMethod, innerTxatt);
TransactionStatus outerStatus = transactionStatusForNewTransaction();
TransactionStatus innerStatus = transactionStatusForNewTransaction();
MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class);
PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock();
// Expect a transaction
ptm.getTransaction(outerTxatt);
ptmControl.setReturnValue(outerStatus, 1);
ptm.getTransaction(innerTxatt);
ptmControl.setReturnValue(innerStatus, 1);
ptm.commit(innerStatus);
ptmControl.setVoidCallable(1);
ptm.commit(outerStatus);
ptmControl.setVoidCallable(1);
ptmControl.replay();
final String spouseName = "innerName";
TestBean outer = new TestBean() {
public void exceptional(Throwable t) throws Throwable {
TransactionInfo ti = TransactionAspectSupport.currentTransactionInfo();
assertTrue(ti.hasTransaction());
assertEquals(outerTxatt, ti.getTransactionAttribute());
assertEquals(spouseName, getSpouse().getName());
}
};
TestBean inner = new TestBean() {
public String getName() {
// Assert that we're in the inner proxy
TransactionInfo ti = TransactionAspectSupport.currentTransactionInfo();
// Has nested transaction
assertTrue(ti.hasTransaction());
assertEquals(innerTxatt, ti.getTransactionAttribute());
return spouseName;
}
};
ITestBean outerProxy = (ITestBean) advised(outer, ptm, tas);
ITestBean innerProxy = (ITestBean) advised(inner, ptm, tas);
outer.setSpouse(innerProxy);
checkTransactionStatus(false);
// Will invoke inner.getName, which is non-transactional
outerProxy.exceptional(null);
checkTransactionStatus(false);
ptmControl.verify();
}
public void testRollbackOnCheckedException() throws Throwable {
doTestRollbackOnException(new Exception(), true, false);
}
public void testNoRollbackOnCheckedException() throws Throwable {
doTestRollbackOnException(new Exception(), false, false);
}
public void testRollbackOnUncheckedException() throws Throwable {
doTestRollbackOnException(new RuntimeException(), true, false);
}
public void testNoRollbackOnUncheckedException() throws Throwable {
doTestRollbackOnException(new RuntimeException(), false, false);
}
public void testRollbackOnCheckedExceptionWithRollbackException() throws Throwable {
doTestRollbackOnException(new Exception(), true, true);
}
public void testNoRollbackOnCheckedExceptionWithRollbackException() throws Throwable {
doTestRollbackOnException(new Exception(), false, true);
}
public void testRollbackOnUncheckedExceptionWithRollbackException() throws Throwable {
doTestRollbackOnException(new RuntimeException(), true, true);
}
public void testNoRollbackOnUncheckedExceptionWithRollbackException() throws Throwable {
doTestRollbackOnException(new RuntimeException(), false, true);
}
/**
* Check that the given exception thrown by the target can produce the
* desired behavior with the appropriate transaction attribute.
* @param ex exception to be thrown by the target
* @param shouldRollback whether this should cause a transaction rollback
*/
protected void doTestRollbackOnException(
final Exception ex, final boolean shouldRollback, boolean rollbackException) throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute() {
public boolean rollbackOn(Throwable t) {
assertTrue(t == ex);
return shouldRollback;
}
};
Method m = exceptionalMethod;
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(m, txatt);
MockControl statusControl = MockControl.createControl(TransactionStatus.class);
TransactionStatus status = (TransactionStatus) statusControl.getMock();
MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class);
PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock();
// Gets additional call(s) from TransactionControl
ptm.getTransaction(txatt);
ptmControl.setReturnValue(status, 1);
if (shouldRollback) {
ptm.rollback(status);
}
else {
ptm.commit(status);
}
TransactionSystemException tex = new TransactionSystemException("system exception");
if (rollbackException) {
ptmControl.setThrowable(tex, 1);
}
else {
ptmControl.setVoidCallable(1);
}
ptmControl.replay();
TestBean tb = new TestBean();
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
try {
itb.exceptional(ex);
fail("Should have thrown exception");
}
catch (Throwable t) {
if (rollbackException) {
assertEquals("Caught wrong exception", tex, t );
}
else {
assertEquals("Caught wrong exception", ex, t);
}
}
ptmControl.verify();
}
/**
* Test that TransactionStatus.setRollbackOnly works.
*/
public void testProgrammaticRollback() throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute();
Method m = getNameMethod;
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(m, txatt);
TransactionStatus status = transactionStatusForNewTransaction();
MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class);
PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock();
ptm.getTransaction(txatt);
ptmControl.setReturnValue(status, 1);
ptm.commit(status);
ptmControl.setVoidCallable(1);
ptmControl.replay();
final String name = "jenny";
TestBean tb = new TestBean() {
public String getName() {
TransactionStatus txStatus = TransactionInterceptor.currentTransactionStatus();
txStatus.setRollbackOnly();
return name;
}
};
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
// verification!?
assertTrue(name.equals(itb.getName()));
ptmControl.verify();
}
/**
* @return a TransactionStatus object configured for a new transaction
*/
private TransactionStatus transactionStatusForNewTransaction() {
MockControl statusControl = MockControl.createControl(TransactionStatus.class);
return (TransactionStatus) statusControl.getMock();
}
/**
* Simulate a transaction infrastructure failure.
* Shouldn't invoke target method.
*/
public void testCannotCreateTransaction() throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute();
Method m = getNameMethod;
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(m, txatt);
MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class);
PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock();
// Expect a transaction
ptm.getTransaction(txatt);
CannotCreateTransactionException ex = new CannotCreateTransactionException("foobar", null);
ptmControl.setThrowable(ex);
ptmControl.replay();
TestBean tb = new TestBean() {
public String getName() {
throw new UnsupportedOperationException(
"Shouldn't have invoked target method when couldn't create transaction for transactional method");
}
};
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
try {
itb.getName();
fail("Shouldn't have invoked method");
}
catch (CannotCreateTransactionException thrown) {
assertTrue(thrown == ex);
}
ptmControl.verify();
}
/**
* Simulate failure of the underlying transaction infrastructure to commit.
* Check that the target method was invoked, but that the transaction
* infrastructure exception was thrown to the client
*/
public void testCannotCommitTransaction() throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute();
Method m = setNameMethod;
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(m, txatt);
Method m2 = getNameMethod;
// No attributes for m2
MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class);
PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock();
TransactionStatus status = transactionStatusForNewTransaction();
ptm.getTransaction(txatt);
ptmControl.setReturnValue(status);
UnexpectedRollbackException ex = new UnexpectedRollbackException("foobar", null);
ptm.commit(status);
ptmControl.setThrowable(ex);
ptmControl.replay();
TestBean tb = new TestBean();
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
String name = "new name";
try {
itb.setName(name);
fail("Shouldn't have succeeded");
}
catch (UnexpectedRollbackException thrown) {
assertTrue(thrown == ex);
}
// Should have invoked target and changed name
assertTrue(itb.getName() == name);
ptmControl.verify();
}
protected void checkTransactionStatus(boolean expected) {
try {
TransactionInterceptor.currentTransactionStatus();
if (!expected) {
fail("Should have thrown NoTransactionException");
}
}
catch (NoTransactionException ex) {
if (expected) {
fail("Should have current TransactionStatus");
}
}
}
protected Object advised(
Object target, PlatformTransactionManager ptm, TransactionAttributeSource[] tas) throws Exception {
return advised(target, ptm, new CompositeTransactionAttributeSource(tas));
}
/**
* Subclasses must implement this to create an advised object based on the
* given target. In the case of AspectJ, the advised object will already
* have been created, as there's no distinction between target and proxy.
* In the case of Spring's own AOP framework, a proxy must be created
* using a suitably configured transaction interceptor
* @param target target if there's a distinct target. If not (AspectJ),
* return target.
* @return transactional advised object
*/
protected abstract Object advised(
Object target, PlatformTransactionManager ptm, TransactionAttributeSource tas) throws Exception;
}
| test/org/springframework/transaction/interceptor/AbstractTransactionAspectTests.java | /*
* Copyright 2002-2006 the original author or authors.
*
* 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 org.springframework.transaction.interceptor;
import java.lang.reflect.Method;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.transaction.MockCallbackPreferringTransactionManager;
import org.springframework.transaction.NoTransactionException;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.TransactionSystemException;
import org.springframework.transaction.UnexpectedRollbackException;
import org.springframework.transaction.interceptor.TransactionAspectSupport.TransactionInfo;
/**
* Mock object based tests for transaction aspects.
* True unit test in that it tests how the transaction aspect uses
* the PlatformTransactionManager helper, rather than indirectly
* testing the helper implementation.
*
* This is a superclass to allow testing both the AOP Alliance MethodInterceptor
* and the AspectJ aspect.
*
* @author Rod Johnson
* @since 16.03.2003
*/
public abstract class AbstractTransactionAspectTests extends TestCase {
protected Method exceptionalMethod;
protected Method getNameMethod;
protected Method setNameMethod;
public AbstractTransactionAspectTests() {
try {
// Cache the methods we'll be testing
exceptionalMethod = ITestBean.class.getMethod("exceptional", new Class[] { Throwable.class });
getNameMethod = ITestBean.class.getMethod("getName", (Class[]) null);
setNameMethod = ITestBean.class.getMethod("setName", new Class[] { String.class} );
}
catch (NoSuchMethodException ex) {
throw new RuntimeException("Shouldn't happen", ex);
}
}
public void testNoTransaction() throws Exception {
MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class);
PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock();
// expect no calls
ptmControl.replay();
TestBean tb = new TestBean();
TransactionAttributeSource tas = new MapTransactionAttributeSource();
// All the methods in this class use the advised() template method
// to obtain a transaction object, configured with the given PlatformTransactionManager
// and transaction attribute source
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
checkTransactionStatus(false);
itb.getName();
checkTransactionStatus(false);
ptmControl.verify();
}
/**
* Check that a transaction is created and committed.
*/
public void testTransactionShouldSucceed() throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute();
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(getNameMethod, txatt);
TransactionStatus status = transactionStatusForNewTransaction();
MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class);
PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock();
// expect a transaction
ptm.getTransaction(txatt);
ptmControl.setReturnValue(status, 1);
ptm.commit(status);
ptmControl.setVoidCallable(1);
ptmControl.replay();
TestBean tb = new TestBean();
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
checkTransactionStatus(false);
itb.getName();
checkTransactionStatus(false);
ptmControl.verify();
}
/**
* Check that a transaction is created and committed using
* CallbackPreferringPlatformTransactionManager.
*/
public void testTransactionShouldSucceedWithCallbackPreference() throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute();
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(getNameMethod, txatt);
MockCallbackPreferringTransactionManager ptm = new MockCallbackPreferringTransactionManager();
TestBean tb = new TestBean();
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
checkTransactionStatus(false);
itb.getName();
checkTransactionStatus(false);
assertSame(txatt, ptm.getDefinition());
assertFalse(ptm.getStatus().isRollbackOnly());
}
/**
* Check that two transactions are created and committed.
*/
public void testTwoTransactionsShouldSucceed() throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute();
MapTransactionAttributeSource tas1 = new MapTransactionAttributeSource();
tas1.register(getNameMethod, txatt);
MapTransactionAttributeSource tas2 = new MapTransactionAttributeSource();
tas2.register(setNameMethod, txatt);
TransactionStatus status = transactionStatusForNewTransaction();
MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class);
PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock();
// expect a transaction
ptm.getTransaction(txatt);
ptmControl.setReturnValue(status, 2);
ptm.commit(status);
ptmControl.setVoidCallable(2);
ptmControl.replay();
TestBean tb = new TestBean();
ITestBean itb = (ITestBean) advised(tb, ptm, new TransactionAttributeSource[] {tas1, tas2});
checkTransactionStatus(false);
itb.getName();
checkTransactionStatus(false);
itb.setName("myName");
checkTransactionStatus(false);
ptmControl.verify();
}
/**
* Check that a transaction is created and committed.
*/
public void testTransactionShouldSucceedWithNotNew() throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute();
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(getNameMethod, txatt);
MockControl statusControl = MockControl.createControl(TransactionStatus.class);
TransactionStatus status = (TransactionStatus) statusControl.getMock();
MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class);
PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock();
// expect a transaction
ptm.getTransaction(txatt);
ptmControl.setReturnValue(status, 1);
ptm.commit(status);
ptmControl.setVoidCallable(1);
ptmControl.replay();
TestBean tb = new TestBean();
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
checkTransactionStatus(false);
// verification!?
itb.getName();
checkTransactionStatus(false);
ptmControl.verify();
}
public void testEnclosingTransactionWithNonTransactionMethodOnAdvisedInside() throws Throwable {
TransactionAttribute txatt = new DefaultTransactionAttribute();
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(exceptionalMethod, txatt);
TransactionStatus status = transactionStatusForNewTransaction();
MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class);
PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock();
// Expect a transaction
ptm.getTransaction(txatt);
ptmControl.setReturnValue(status, 1);
ptm.commit(status);
ptmControl.setVoidCallable(1);
ptmControl.replay();
final String spouseName = "innerName";
TestBean outer = new TestBean() {
public void exceptional(Throwable t) throws Throwable {
TransactionInfo ti = TransactionAspectSupport.currentTransactionInfo();
assertTrue(ti.hasTransaction());
assertEquals(spouseName, getSpouse().getName());
}
};
TestBean inner = new TestBean() {
public String getName() {
// Assert that we're in the inner proxy
TransactionInfo ti = TransactionAspectSupport.currentTransactionInfo();
assertFalse(ti.hasTransaction());
return spouseName;
}
};
ITestBean outerProxy = (ITestBean) advised(outer, ptm, tas);
ITestBean innerProxy = (ITestBean) advised(inner, ptm, tas);
outer.setSpouse(innerProxy);
checkTransactionStatus(false);
// Will invoke inner.getName, which is non-transactional
outerProxy.exceptional(null);
checkTransactionStatus(false);
ptmControl.verify();
}
public void testEnclosingTransactionWithNestedTransactionOnAdvisedInside() throws Throwable {
final TransactionAttribute outerTxatt = new DefaultTransactionAttribute();
final TransactionAttribute innerTxatt = new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_NESTED);
Method outerMethod = exceptionalMethod;
Method innerMethod = getNameMethod;
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(outerMethod, outerTxatt);
tas.register(innerMethod, innerTxatt);
TransactionStatus outerStatus = transactionStatusForNewTransaction();
TransactionStatus innerStatus = transactionStatusForNewTransaction();
MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class);
PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock();
// Expect a transaction
ptm.getTransaction(outerTxatt);
ptmControl.setReturnValue(outerStatus, 1);
ptm.getTransaction(innerTxatt);
ptmControl.setReturnValue(innerStatus, 1);
ptm.commit(innerStatus);
ptmControl.setVoidCallable(1);
ptm.commit(outerStatus);
ptmControl.setVoidCallable(1);
ptmControl.replay();
final String spouseName = "innerName";
TestBean outer = new TestBean() {
public void exceptional(Throwable t) throws Throwable {
TransactionInfo ti = TransactionAspectSupport.currentTransactionInfo();
assertTrue(ti.hasTransaction());
assertEquals(outerTxatt, ti.getTransactionAttribute());
assertEquals(spouseName, getSpouse().getName());
}
};
TestBean inner = new TestBean() {
public String getName() {
// Assert that we're in the inner proxy
TransactionInfo ti = TransactionAspectSupport.currentTransactionInfo();
// Has nested transaction
assertTrue(ti.hasTransaction());
assertEquals(innerTxatt, ti.getTransactionAttribute());
return spouseName;
}
};
ITestBean outerProxy = (ITestBean) advised(outer, ptm, tas);
ITestBean innerProxy = (ITestBean) advised(inner, ptm, tas);
outer.setSpouse(innerProxy);
checkTransactionStatus(false);
// Will invoke inner.getName, which is non-transactional
outerProxy.exceptional(null);
checkTransactionStatus(false);
ptmControl.verify();
}
public void testRollbackOnCheckedException() throws Throwable {
doTestRollbackOnException(new Exception(), true, false);
}
public void testNoRollbackOnCheckedException() throws Throwable {
doTestRollbackOnException(new Exception(), false, false);
}
public void testRollbackOnUncheckedException() throws Throwable {
doTestRollbackOnException(new RuntimeException(), true, false);
}
public void testNoRollbackOnUncheckedException() throws Throwable {
doTestRollbackOnException(new RuntimeException(), false, false);
}
public void testRollbackOnCheckedExceptionWithRollbackException() throws Throwable {
doTestRollbackOnException(new Exception(), true, true);
}
public void testNoRollbackOnCheckedExceptionWithRollbackException() throws Throwable {
doTestRollbackOnException(new Exception(), false, true);
}
public void testRollbackOnUncheckedExceptionWithRollbackException() throws Throwable {
doTestRollbackOnException(new RuntimeException(), true, true);
}
public void testNoRollbackOnUncheckedExceptionWithRollbackException() throws Throwable {
doTestRollbackOnException(new RuntimeException(), false, true);
}
/**
* Check that the given exception thrown by the target can produce the
* desired behavior with the appropriate transaction attribute.
* @param ex exception to be thrown by the target
* @param shouldRollback whether this should cause a transaction rollback
*/
protected void doTestRollbackOnException(
final Exception ex, final boolean shouldRollback, boolean rollbackException) throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute() {
public boolean rollbackOn(Throwable t) {
assertTrue(t == ex);
return shouldRollback;
}
};
Method m = exceptionalMethod;
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(m, txatt);
MockControl statusControl = MockControl.createControl(TransactionStatus.class);
TransactionStatus status = (TransactionStatus) statusControl.getMock();
MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class);
PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock();
// Gets additional call(s) from TransactionControl
ptm.getTransaction(txatt);
ptmControl.setReturnValue(status, 1);
if (shouldRollback) {
ptm.rollback(status);
}
else {
ptm.commit(status);
}
TransactionSystemException tex = new TransactionSystemException("system exception");
if (rollbackException) {
ptmControl.setThrowable(tex, 1);
}
else {
ptmControl.setVoidCallable(1);
}
ptmControl.replay();
TestBean tb = new TestBean();
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
try {
itb.exceptional(ex);
fail("Should have thrown exception");
}
catch (Throwable t) {
if (rollbackException) {
assertEquals("Caught wrong exception", tex, t );
}
else {
assertEquals("Caught wrong exception", ex, t);
}
}
ptmControl.verify();
}
/**
* Test that TransactionStatus.setRollbackOnly works.
*/
public void testProgrammaticRollback() throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute();
Method m = getNameMethod;
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(m, txatt);
TransactionStatus status = transactionStatusForNewTransaction();
MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class);
PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock();
ptm.getTransaction(txatt);
ptmControl.setReturnValue(status, 1);
ptm.commit(status);
ptmControl.setVoidCallable(1);
ptmControl.replay();
final String name = "jenny";
TestBean tb = new TestBean() {
public String getName() {
TransactionStatus txStatus = TransactionInterceptor.currentTransactionStatus();
txStatus.setRollbackOnly();
return name;
}
};
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
// verification!?
assertTrue(name.equals(itb.getName()));
ptmControl.verify();
}
/**
* @return a TransactionStatus object configured for a new transaction
*/
private TransactionStatus transactionStatusForNewTransaction() {
MockControl statusControl = MockControl.createControl(TransactionStatus.class);
return (TransactionStatus) statusControl.getMock();
}
/**
* Simulate a transaction infrastructure failure.
* Shouldn't invoke target method.
*/
public void testCannotCreateTransaction() throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute();
Method m = getNameMethod;
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(m, txatt);
MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class);
PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock();
// Expect a transaction
ptm.getTransaction(txatt);
CannotCreateTransactionException ex = new CannotCreateTransactionException("foobar", null);
ptmControl.setThrowable(ex);
ptmControl.replay();
TestBean tb = new TestBean() {
public String getName() {
throw new UnsupportedOperationException(
"Shouldn't have invoked target method when couldn't create transaction for transactional method");
}
};
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
try {
itb.getName();
fail("Shouldn't have invoked method");
}
catch (CannotCreateTransactionException thrown) {
assertTrue(thrown == ex);
}
ptmControl.verify();
}
/**
* Simulate failure of the underlying transaction infrastructure to commit.
* Check that the target method was invoked, but that the transaction
* infrastructure exception was thrown to the client
*/
public void testCannotCommitTransaction() throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute();
Method m = setNameMethod;
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(m, txatt);
Method m2 = getNameMethod;
// No attributes for m2
MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class);
PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock();
TransactionStatus status = transactionStatusForNewTransaction();
ptm.getTransaction(txatt);
ptmControl.setReturnValue(status);
UnexpectedRollbackException ex = new UnexpectedRollbackException("foobar", null);
ptm.commit(status);
ptmControl.setThrowable(ex);
ptmControl.replay();
TestBean tb = new TestBean();
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
String name = "new name";
try {
itb.setName(name);
fail("Shouldn't have succeeded");
}
catch (UnexpectedRollbackException thrown) {
assertTrue(thrown == ex);
}
// Should have invoked target and changed name
assertTrue(itb.getName() == name);
ptmControl.verify();
}
protected void checkTransactionStatus(boolean expected) {
try {
TransactionInterceptor.currentTransactionStatus();
if (!expected) {
fail("Should have thrown NoTransactionException");
}
}
catch (NoTransactionException ex) {
if (expected) {
fail("Should have current TransactionStatus");
}
}
}
protected Object advised(
Object target, PlatformTransactionManager ptm, TransactionAttributeSource[] tas) throws Exception {
return advised(target, ptm, new CompositeTransactionAttributeSource(tas));
}
/**
* Subclasses must implement this to create an advised object based on the
* given target. In the case of AspectJ, the advised object will already
* have been created, as there's no distinction between target and proxy.
* In the case of Spring's own AOP framework, a proxy must be created
* using a suitably configured transaction interceptor
* @param target target if there's a distinct target. If not (AspectJ),
* return target.
* @return transactional advised object
*/
protected abstract Object advised(
Object target, PlatformTransactionManager ptm, TransactionAttributeSource tas) throws Exception;
}
| added test for exception propagation
git-svn-id: b619a0c99665f88f1afe72824344cefe9a1c8c90@14234 fd5a2b45-1f63-4059-99e9-3c7cb7fd75c8
| test/org/springframework/transaction/interceptor/AbstractTransactionAspectTests.java | added test for exception propagation | |
Java | apache-2.0 | 2f71e34e1079738dc644147856c0667aef5b3e90 | 0 | blindpirate/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle | /*
* Copyright 2020 the original author or authors.
*
* 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 org.gradle.internal.classpath;
import org.gradle.api.GradleException;
import org.gradle.api.UncheckedIOException;
import org.gradle.api.file.RelativePath;
import org.gradle.api.internal.file.archive.ZipEntry;
import org.gradle.api.internal.file.archive.ZipInput;
import org.gradle.api.internal.file.archive.impl.FileZipInput;
import org.gradle.internal.Pair;
import org.gradle.internal.UncheckedException;
import org.gradle.internal.file.FileException;
import org.gradle.internal.file.FileType;
import org.gradle.internal.hash.HashCode;
import org.gradle.internal.hash.Hasher;
import org.gradle.internal.hash.Hashing;
import org.gradle.internal.io.ExponentialBackoff;
import org.gradle.internal.snapshot.FileSystemLocationSnapshot;
import org.gradle.util.GFileUtils;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.util.concurrent.TimeUnit;
import static java.lang.String.format;
class InstrumentingClasspathFileTransformer implements ClasspathFileTransformer {
private static final Logger LOGGER = LoggerFactory.getLogger(InstrumentingClasspathFileTransformer.class);
private static final int CACHE_FORMAT = 1;
private final ClasspathWalker classpathWalker;
private final ClasspathBuilder classpathBuilder;
private final CachedClasspathTransformer.Transform transform;
private final HashCode configHash;
public InstrumentingClasspathFileTransformer(ClasspathWalker classpathWalker, ClasspathBuilder classpathBuilder, CachedClasspathTransformer.Transform transform) {
this.classpathWalker = classpathWalker;
this.classpathBuilder = classpathBuilder;
this.transform = transform;
this.configHash = configHashFor(transform);
}
private HashCode configHashFor(CachedClasspathTransformer.Transform transform) {
Hasher hasher = Hashing.defaultFunction().newHasher();
hasher.putInt(CACHE_FORMAT);
transform.applyConfigurationTo(hasher);
return hasher.hash();
}
@Override
public File transform(File source, FileSystemLocationSnapshot sourceSnapshot, File cacheDir) {
String name = sourceSnapshot.getType() == FileType.Directory
? source.getName() + ".jar"
: source.getName();
String destFileName = hashOf(sourceSnapshot).toString() + '/' + name;
return transformIfNeeded(source, cacheDir, destFileName);
}
private File transformIfNeeded(File source, File cacheDir, String destFileName) {
File receipt = new File(cacheDir, destFileName + ".receipt");
File transformed = new File(cacheDir, destFileName);
if (receipt.isFile()) {
return transformed;
}
if (transformed.isFile()) {
// A concurrent writer has already started writing to the file.
// Just wait until the transformed file is ready for consumption.
waitForReceiptOf(destFileName, receipt);
return transformed;
}
try {
transform(source, transformed);
} catch (GradleException e) {
if (e.getCause() instanceof FileAlreadyExistsException) {
// A concurrent writer has already started writing to the file.
// We run identical transforms concurrently and we can sometimes finish two transforms at the same
// time in a way that Files.move (see [ClasspathBuilder.nonReplacingJar]) will see [transformed] created before
// the move is done.
// Just wait until the transformed file is ready for consumption.
LOGGER.debug("Instrumented classpath file '{}' already exists.", destFileName, e);
waitForReceiptOf(destFileName, receipt);
return transformed;
} else {
throw e;
}
}
try {
receipt.createNewFile();
} catch (IOException e) {
LOGGER.debug("Failed to create receipt for instrumented classpath file '{}'.", destFileName, e);
}
return transformed;
}
private void waitForReceiptOf(String destFileName, File receipt) {
if (!waitFor(receipt)) {
throw new IllegalStateException(
format("Timeout waiting for instrumented classpath file: '%s'.", destFileName)
);
}
}
/**
* Waits up to 60 seconds for the given file to appear.
*
* @return true when the file appears before the timeout, false otherwise.
*/
private boolean waitFor(File file) {
try {
return ExponentialBackoff
.of(60, TimeUnit.SECONDS)
.retryUntil(() -> file.isFile() ? file : null) != null;
} catch (InterruptedException | IOException e) {
throw UncheckedException.throwAsUncheckedException(e);
}
}
private HashCode hashOf(FileSystemLocationSnapshot sourceSnapshot) {
Hasher hasher = Hashing.defaultFunction().newHasher();
hasher.putHash(configHash);
// TODO - apply runtime classpath normalization?
hasher.putHash(sourceSnapshot.getHash());
return hasher.hash();
}
private void transform(File source, File dest) {
if (isSignedJar(source)) {
LOGGER.debug("Signed archive '{}'. Skipping instrumentation.", source.getName());
GFileUtils.copyFile(source, dest);
} else {
instrument(source, dest);
}
}
private void instrument(File source, File dest) {
classpathBuilder.nonReplacingJar(dest, builder -> {
try {
visitEntries(source, builder);
} catch (FileException e) {
// Badly formed archive, so discard the contents and produce an empty JAR
LOGGER.debug("Malformed archive '{}'. Discarding contents.", source.getName(), e);
}
});
}
private void visitEntries(File source, ClasspathBuilder.EntryBuilder builder) throws IOException, FileException {
classpathWalker.visit(source, entry -> {
if (entry.getName().endsWith(".class")) {
ClassReader reader = new ClassReader(entry.getContent());
ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
Pair<RelativePath, ClassVisitor> chain = transform.apply(entry, classWriter);
reader.accept(chain.right, 0);
byte[] bytes = classWriter.toByteArray();
builder.put(chain.left.getPathString(), bytes);
} else {
builder.put(entry.getName(), entry.getContent());
}
});
}
private boolean isSignedJar(File source) {
if (!source.isFile()) {
return false;
}
try (ZipInput entries = FileZipInput.create(source)) {
for (ZipEntry entry : entries) {
String entryName = entry.getName();
if (entryName.startsWith("META-INF/") && entryName.endsWith(".SF")) {
return true;
}
}
} catch (FileException e) {
// Ignore malformed archive
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return false;
}
}
| subprojects/core/src/main/java/org/gradle/internal/classpath/InstrumentingClasspathFileTransformer.java | /*
* Copyright 2020 the original author or authors.
*
* 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 org.gradle.internal.classpath;
import org.gradle.api.GradleException;
import org.gradle.api.UncheckedIOException;
import org.gradle.api.file.RelativePath;
import org.gradle.api.internal.file.archive.ZipEntry;
import org.gradle.api.internal.file.archive.ZipInput;
import org.gradle.api.internal.file.archive.impl.FileZipInput;
import org.gradle.internal.Pair;
import org.gradle.internal.UncheckedException;
import org.gradle.internal.file.FileException;
import org.gradle.internal.file.FileType;
import org.gradle.internal.hash.HashCode;
import org.gradle.internal.hash.Hasher;
import org.gradle.internal.hash.Hashing;
import org.gradle.internal.io.ExponentialBackoff;
import org.gradle.internal.snapshot.FileSystemLocationSnapshot;
import org.gradle.util.GFileUtils;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.util.concurrent.TimeUnit;
import static java.lang.String.format;
class InstrumentingClasspathFileTransformer implements ClasspathFileTransformer {
private static final Logger LOGGER = LoggerFactory.getLogger(InstrumentingClasspathFileTransformer.class);
private static final int CACHE_FORMAT = 1;
private final ClasspathWalker classpathWalker;
private final ClasspathBuilder classpathBuilder;
private final CachedClasspathTransformer.Transform transform;
private final HashCode configHash;
public InstrumentingClasspathFileTransformer(ClasspathWalker classpathWalker, ClasspathBuilder classpathBuilder, CachedClasspathTransformer.Transform transform) {
this.classpathWalker = classpathWalker;
this.classpathBuilder = classpathBuilder;
this.transform = transform;
this.configHash = configHashFor(transform);
}
private HashCode configHashFor(CachedClasspathTransformer.Transform transform) {
Hasher hasher = Hashing.defaultFunction().newHasher();
hasher.putInt(CACHE_FORMAT);
transform.applyConfigurationTo(hasher);
return hasher.hash();
}
@Override
public File transform(File source, FileSystemLocationSnapshot sourceSnapshot, File cacheDir) {
String name = sourceSnapshot.getType() == FileType.Directory
? source.getName() + ".jar"
: source.getName();
String destFileName = hashOf(sourceSnapshot).toString() + '/' + name;
return transformIfNeeded(source, cacheDir, destFileName);
}
private File transformIfNeeded(File source, File cacheDir, String destFileName) {
File receipt = new File(cacheDir, destFileName + ".receipt");
File transformed = new File(cacheDir, destFileName);
if (receipt.isFile()) {
return transformed;
}
if (transformed.isFile()) {
// A concurrent writer has already started writing to the file.
// Just wait until the transformed file is ready for consumption.
waitForReceiptOf(destFileName, receipt);
return transformed;
}
try {
transform(source, transformed);
} catch (GradleException e) {
if (e.getCause() instanceof FileAlreadyExistsException) {
// A concurrent writer has already started writing to the file.
// We run identical transforms concurrently and we can sometimes finish two transforms at the same
// time in a way that Files.move (see [ClasspathBuilder.nonReplacingJar]) will see [transformed] created before
// the move is done.
// Just wait until the transformed file is ready for consumption.
LOGGER.debug("Instrumented classpath file '{}' already exists.", destFileName, e);
waitForReceiptOf(destFileName, receipt);
return transformed;
} else {
throw e;
}
}
try {
receipt.createNewFile();
} catch (IOException e) {
LOGGER.debug("Failed to create receipt for instrumented classpath file '{}'.", destFileName, e);
}
return transformed;
}
private void waitForReceiptOf(String destFileName, File receipt) {
if (!waitFor(receipt)) {
throw new IllegalStateException(
format("Timeout waiting for instrumented classpath file: '%s'.", destFileName)
);
}
}
/**
* Waits up to 30 seconds for the given file to appear.
*
* @return true when the file appears before the timeout, false otherwise.
*/
private boolean waitFor(File file) {
try {
return ExponentialBackoff
.of(30, TimeUnit.SECONDS)
.retryUntil(() -> file.isFile() ? file : null) != null;
} catch (InterruptedException | IOException e) {
throw UncheckedException.throwAsUncheckedException(e);
}
}
private HashCode hashOf(FileSystemLocationSnapshot sourceSnapshot) {
Hasher hasher = Hashing.defaultFunction().newHasher();
hasher.putHash(configHash);
// TODO - apply runtime classpath normalization?
hasher.putHash(sourceSnapshot.getHash());
return hasher.hash();
}
private void transform(File source, File dest) {
if (isSignedJar(source)) {
LOGGER.debug("Signed archive '{}'. Skipping instrumentation.", source.getName());
GFileUtils.copyFile(source, dest);
} else {
instrument(source, dest);
}
}
private void instrument(File source, File dest) {
classpathBuilder.nonReplacingJar(dest, builder -> {
try {
visitEntries(source, builder);
} catch (FileException e) {
// Badly formed archive, so discard the contents and produce an empty JAR
LOGGER.debug("Malformed archive '{}'. Discarding contents.", source.getName(), e);
}
});
}
private void visitEntries(File source, ClasspathBuilder.EntryBuilder builder) throws IOException, FileException {
classpathWalker.visit(source, entry -> {
if (entry.getName().endsWith(".class")) {
ClassReader reader = new ClassReader(entry.getContent());
ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
Pair<RelativePath, ClassVisitor> chain = transform.apply(entry, classWriter);
reader.accept(chain.right, 0);
byte[] bytes = classWriter.toByteArray();
builder.put(chain.left.getPathString(), bytes);
} else {
builder.put(entry.getName(), entry.getContent());
}
});
}
private boolean isSignedJar(File source) {
if (!source.isFile()) {
return false;
}
try (ZipInput entries = FileZipInput.create(source)) {
for (ZipEntry entry : entries) {
String entryName = entry.getName();
if (entryName.startsWith("META-INF/") && entryName.endsWith(".SF")) {
return true;
}
}
} catch (FileException e) {
// Ignore malformed archive
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return false;
}
}
| Increase classpath file instrumentation timeout to 60 seconds
| subprojects/core/src/main/java/org/gradle/internal/classpath/InstrumentingClasspathFileTransformer.java | Increase classpath file instrumentation timeout to 60 seconds | |
Java | apache-2.0 | 24c50ba7051d2bb685e2a98085baf8034758fd71 | 0 | zwets/flowable-engine,yvoswillens/flowable-engine,motorina0/flowable-engine,dbmalkovsky/flowable-engine,stefan-ziel/Activiti,martin-grofcik/flowable-engine,zwets/flowable-engine,paulstapleton/flowable-engine,yvoswillens/flowable-engine,paulstapleton/flowable-engine,martin-grofcik/flowable-engine,yvoswillens/flowable-engine,roberthafner/flowable-engine,gro-mar/flowable-engine,gro-mar/flowable-engine,dbmalkovsky/flowable-engine,marcus-nl/flowable-engine,martin-grofcik/flowable-engine,stefan-ziel/Activiti,yvoswillens/flowable-engine,stefan-ziel/Activiti,motorina0/flowable-engine,gro-mar/flowable-engine,stephraleigh/flowable-engine,flowable/flowable-engine,roberthafner/flowable-engine,marcus-nl/flowable-engine,Activiti/Activiti,lsmall/flowable-engine,robsoncardosoti/flowable-engine,roberthafner/flowable-engine,zwets/flowable-engine,dbmalkovsky/flowable-engine,gro-mar/flowable-engine,stefan-ziel/Activiti,robsoncardosoti/flowable-engine,motorina0/flowable-engine,sibok666/flowable-engine,Activiti/Activiti,sibok666/flowable-engine,lsmall/flowable-engine,flowable/flowable-engine,motorina0/flowable-engine,stephraleigh/flowable-engine,lsmall/flowable-engine,stephraleigh/flowable-engine,marcus-nl/flowable-engine,paulstapleton/flowable-engine,paulstapleton/flowable-engine,sibok666/flowable-engine,marcus-nl/flowable-engine,robsoncardosoti/flowable-engine,roberthafner/flowable-engine,sibok666/flowable-engine,lsmall/flowable-engine,dbmalkovsky/flowable-engine,martin-grofcik/flowable-engine,robsoncardosoti/flowable-engine,flowable/flowable-engine,flowable/flowable-engine,stephraleigh/flowable-engine,zwets/flowable-engine | /* 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 org.activiti.engine.test.bpmn.event.end;
import java.util.List;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;
import org.activiti.engine.impl.test.PluggableActivitiTestCase;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.test.Deployment;
/**
* @author Nico Rehwaldt
*/
public class TerminateEndEventTest extends PluggableActivitiTestCase {
public static int serviceTaskInvokedCount = 0;
public static class CountDelegate implements JavaDelegate {
public void execute(DelegateExecution execution) throws Exception {
serviceTaskInvokedCount++;
// leave only 3 out of n subprocesses
execution.setVariableLocal("terminate", serviceTaskInvokedCount > 3);
}
}
public static int serviceTaskInvokedCount2 = 0;
public static class CountDelegate2 implements JavaDelegate {
public void execute(DelegateExecution execution) throws Exception {
serviceTaskInvokedCount2++;
}
}
@Deployment
public void testProcessTerminate() throws Exception {
ProcessInstance pi = runtimeService.startProcessInstanceByKey("terminateEndEventExample");
long executionEntities = runtimeService.createExecutionQuery().processInstanceId(pi.getId()).count();
assertEquals(3, executionEntities);
Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).taskDefinitionKey("preTerminateTask").singleResult();
taskService.complete(task.getId());
assertProcessEnded(pi.getId());
}
@Deployment
public void testTerminateWithSubProcess() throws Exception {
ProcessInstance pi = runtimeService.startProcessInstanceByKey("terminateEndEventExample");
// should terminate the process and
long executionEntities = runtimeService.createExecutionQuery().processInstanceId(pi.getId()).count();
assertEquals(4, executionEntities);
Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).taskDefinitionKey("preTerminateEnd").singleResult();
taskService.complete(task.getId());
assertProcessEnded(pi.getId());
}
@Deployment(resources={
"org/activiti/engine/test/bpmn/event/end/TerminateEndEventTest.testTerminateWithCallActivity.bpmn",
"org/activiti/engine/test/bpmn/event/end/TerminateEndEventTest.subProcessNoTerminate.bpmn"
})
public void testTerminateWithCallActivity() throws Exception {
ProcessInstance pi = runtimeService.startProcessInstanceByKey("terminateEndEventExample");
long executionEntities = runtimeService.createExecutionQuery().processInstanceId(pi.getId()).count();
assertEquals(4, executionEntities);
Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).taskDefinitionKey("preTerminateEnd").singleResult();
taskService.complete(task.getId());
assertProcessEnded(pi.getId());
}
@Deployment
public void testTerminateInSubProcess() throws Exception {
serviceTaskInvokedCount = 0;
ProcessInstance pi = runtimeService.startProcessInstanceByKey("terminateEndEventExample");
// should terminate the subprocess and continue the parent
long executionEntities = runtimeService.createExecutionQuery().processInstanceId(pi.getId()).count();
assertEquals(1, executionEntities);
Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).taskDefinitionKey("preNormalEnd").singleResult();
taskService.complete(task.getId());
assertProcessEnded(pi.getId());
}
@Deployment
public void testTerminateInSubProcessConcurrent() throws Exception {
ProcessInstance pi = runtimeService.startProcessInstanceByKey("terminateEndEventExample");
long executionEntities = runtimeService.createExecutionQuery().count();
assertEquals(1, executionEntities);
Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).taskDefinitionKey("preNormalEnd").singleResult();
taskService.complete(task.getId());
assertProcessEnded(pi.getId());
}
@Deployment
public void testTerminateInSubProcessConcurrentMultiInstance() throws Exception {
serviceTaskInvokedCount = 0;
ProcessInstance pi = runtimeService.startProcessInstanceByKey("terminateEndEventExample");
long executionEntities = runtimeService.createExecutionQuery().count();
assertEquals(12, executionEntities);
Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).taskDefinitionKey("preNormalEnd").singleResult();
taskService.complete(task.getId());
long executionEntities2 = runtimeService.createExecutionQuery().count();
assertEquals(10, executionEntities2);
List<Task> tasks = taskService.createTaskQuery().list();
for (Task t : tasks) {
taskService.complete(t.getId());
}
assertProcessEnded(pi.getId());
}
@Deployment(resources = "org/activiti/engine/test/bpmn/event/end/TerminateEndEventTest.testTerminateInSubProcessConcurrentMultiInstance.bpmn")
public void testTerminateInSubProcessConcurrentMultiInstance_clarification() throws Exception {
serviceTaskInvokedCount = 0;
ProcessInstance pi = runtimeService.startProcessInstanceByKey("terminateEndEventExample");
assertProcessEnded(pi.getId());
}
@Deployment
public void testTerminateInSubProcessMultiInstance() throws Exception {
serviceTaskInvokedCount = 0;
ProcessInstance pi = runtimeService.startProcessInstanceByKey("terminateEndEventExample");
long executionEntities = runtimeService.createExecutionQuery().count();
assertEquals(1, executionEntities);
Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).taskDefinitionKey("preNormalEnd").singleResult();
taskService.complete(task.getId());
assertProcessEnded(pi.getId());
}
@Deployment
public void testTerminateInSubProcessSequentialConcurrentMultiInstance() throws Exception {
serviceTaskInvokedCount = 0;
serviceTaskInvokedCount2 = 0;
// Starting multi instance with 5 instances; terminating 2, finishing 3
ProcessInstance pi = runtimeService.startProcessInstanceByKey("terminateEndEventExample");
long remainingExecutions = runtimeService.createExecutionQuery().count();
// outer execution still available
assertEquals(1, remainingExecutions);
// three finished
assertEquals(3, serviceTaskInvokedCount2);
Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).taskDefinitionKey("preNormalEnd").singleResult();
taskService.complete(task.getId());
// last task remaining
assertProcessEnded(pi.getId());
}
@Deployment(resources={
"org/activiti/engine/test/bpmn/event/end/TerminateEndEventTest.testTerminateInCallActivity.bpmn",
"org/activiti/engine/test/bpmn/event/end/TerminateEndEventTest.subProcessTerminate.bpmn"
})
public void testTerminateInCallActivity() throws Exception {
ProcessInstance pi = runtimeService.startProcessInstanceByKey("terminateEndEventExample");
// should terminate the called process and continue the parent
long executionEntities = runtimeService.createExecutionQuery().count();
assertEquals(1, executionEntities);
Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).taskDefinitionKey("preNormalEnd").singleResult();
taskService.complete(task.getId());
assertProcessEnded(pi.getId());
}
@Deployment(resources={
"org/activiti/engine/test/bpmn/event/end/TerminateEndEventTest.testTerminateInCallActivityMulitInstance.bpmn",
"org/activiti/engine/test/bpmn/event/end/TerminateEndEventTest.subProcessTerminate.bpmn"
})
public void testTerminateInCallActivityMulitInstance() throws Exception {
ProcessInstance pi = runtimeService.startProcessInstanceByKey("terminateEndEventExample");
// should terminate the called process and continue the parent
long executionEntities = runtimeService.createExecutionQuery().count();
assertEquals(1, executionEntities);
Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).taskDefinitionKey("preNormalEnd").singleResult();
taskService.complete(task.getId());
assertProcessEnded(pi.getId());
}
@Deployment(resources={
"org/activiti/engine/test/bpmn/event/end/TerminateEndEventTest.testTerminateInCallActivityConcurrent.bpmn",
"org/activiti/engine/test/bpmn/event/end/TerminateEndEventTest.subProcessConcurrentTerminate.bpmn"
})
public void testTerminateInCallActivityConcurrent() throws Exception {
ProcessInstance pi = runtimeService.startProcessInstanceByKey("terminateEndEventExample");
// should terminate the called process and continue the parent
long executionEntities = runtimeService.createExecutionQuery().count();
assertEquals(1, executionEntities);
Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).taskDefinitionKey("preNormalEnd").singleResult();
taskService.complete(task.getId());
assertProcessEnded(pi.getId());
}
@Deployment(resources={
"org/activiti/engine/test/bpmn/event/end/TerminateEndEventTest.testTerminateInCallActivityConcurrentMulitInstance.bpmn",
"org/activiti/engine/test/bpmn/event/end/TerminateEndEventTest.subProcessConcurrentTerminate.bpmn"
})
public void testTerminateInCallActivityConcurrentMulitInstance() throws Exception {
ProcessInstance pi = runtimeService.startProcessInstanceByKey("terminateEndEventExample");
// should terminate the called process and continue the parent
long executionEntities = runtimeService.createExecutionQuery().count();
assertEquals(1, executionEntities);
Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).taskDefinitionKey("preNormalEnd").singleResult();
taskService.complete(task.getId());
assertProcessEnded(pi.getId());
}
} | modules/activiti-engine/src/test/java/org/activiti/engine/test/bpmn/event/end/TerminateEndEventTest.java | /* 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 org.activiti.engine.test.bpmn.event.end;
import java.util.List;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;
import org.activiti.engine.impl.test.PluggableActivitiTestCase;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.test.Deployment;
/**
* @author Nico Rehwaldt
*/
public class TerminateEndEventTest extends PluggableActivitiTestCase {
public static int serviceTaskInvokedCount = 0;
public static class CountDelegate implements JavaDelegate {
public void execute(DelegateExecution execution) throws Exception {
serviceTaskInvokedCount++;
// leave only 3 out of n subprocesses
execution.setVariableLocal("terminate", serviceTaskInvokedCount > 3);
}
}
public static int serviceTaskInvokedCount2 = 0;
public static class CountDelegate2 implements JavaDelegate {
public void execute(DelegateExecution execution) throws Exception {
serviceTaskInvokedCount2++;
}
}
@Deployment
public void testProcessTerminate() throws Exception {
ProcessInstance pi = runtimeService.startProcessInstanceByKey("terminateEndEventExample");
long executionEntities = runtimeService.createExecutionQuery().processInstanceId(pi.getId()).count();
assertEquals(3, executionEntities);
Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).taskDefinitionKey("preTerminateTask").singleResult();
taskService.complete(task.getId());
assertProcessEnded(pi.getId());
}
@Deployment
public void testTerminateWithSubProcess() throws Exception {
ProcessInstance pi = runtimeService.startProcessInstanceByKey("terminateEndEventExample");
// should terminate the process and
long executionEntities = runtimeService.createExecutionQuery().processInstanceId(pi.getId()).count();
assertEquals(4, executionEntities);
Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).taskDefinitionKey("preTerminateEnd").singleResult();
taskService.complete(task.getId());
assertProcessEnded(pi.getId());
}
@Deployment(resources={
"org/activiti/engine/test/bpmn/event/end/TerminateEndEventTest.testTerminateWithCallActivity.bpmn",
"org/activiti/engine/test/bpmn/event/end/TerminateEndEventTest.subProcessNoTerminate.bpmn"
})
public void testTerminateWithCallActivity() throws Exception {
ProcessInstance pi = runtimeService.startProcessInstanceByKey("terminateEndEventExample");
long executionEntities = runtimeService.createExecutionQuery().processInstanceId(pi.getId()).count();
assertEquals(4, executionEntities);
Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).taskDefinitionKey("preTerminateEnd").singleResult();
taskService.complete(task.getId());
assertProcessEnded(pi.getId());
}
@Deployment
public void testTerminateInSubProcess() throws Exception {
serviceTaskInvokedCount = 0;
ProcessInstance pi = runtimeService.startProcessInstanceByKey("terminateEndEventExample");
// should terminate the subprocess and continue the parent
long executionEntities = runtimeService.createExecutionQuery().processInstanceId(pi.getId()).count();
assertEquals(1, executionEntities);
Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).taskDefinitionKey("preNormalEnd").singleResult();
taskService.complete(task.getId());
assertProcessEnded(pi.getId());
}
@Deployment
public void testTerminateInSubProcessConcurrent() throws Exception {
ProcessInstance pi = runtimeService.startProcessInstanceByKey("terminateEndEventExample");
long executionEntities = runtimeService.createExecutionQuery().count();
assertEquals(1, executionEntities);
Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).taskDefinitionKey("preNormalEnd").singleResult();
taskService.complete(task.getId());
assertProcessEnded(pi.getId());
}
@Deployment
public void testTerminateInSubProcessConcurrentMultiInstance() throws Exception {
serviceTaskInvokedCount = 0;
ProcessInstance pi = runtimeService.startProcessInstanceByKey("terminateEndEventExample");
long executionEntities = runtimeService.createExecutionQuery().count();
assertEquals(12, executionEntities);
Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).taskDefinitionKey("preNormalEnd").singleResult();
taskService.complete(task.getId());
long executionEntities2 = runtimeService.createExecutionQuery().count();
assertEquals(10, executionEntities2);
List<Task> tasks = taskService.createTaskQuery().list();
for (Task t : tasks) {
taskService.complete(t.getId());
}
assertProcessEnded(pi.getId());
}
@Deployment
public void testTerminateInSubProcessMultiInstance() throws Exception {
serviceTaskInvokedCount = 0;
ProcessInstance pi = runtimeService.startProcessInstanceByKey("terminateEndEventExample");
long executionEntities = runtimeService.createExecutionQuery().count();
assertEquals(1, executionEntities);
Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).taskDefinitionKey("preNormalEnd").singleResult();
taskService.complete(task.getId());
assertProcessEnded(pi.getId());
}
@Deployment
public void testTerminateInSubProcessSequentialConcurrentMultiInstance() throws Exception {
serviceTaskInvokedCount = 0;
serviceTaskInvokedCount2 = 0;
// Starting multi instance with 5 instances; terminating 2, finishing 3
ProcessInstance pi = runtimeService.startProcessInstanceByKey("terminateEndEventExample");
long remainingExecutions = runtimeService.createExecutionQuery().count();
// outer execution still available
assertEquals(1, remainingExecutions);
// three finished
assertEquals(3, serviceTaskInvokedCount2);
Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).taskDefinitionKey("preNormalEnd").singleResult();
taskService.complete(task.getId());
// last task remaining
assertProcessEnded(pi.getId());
}
@Deployment(resources={
"org/activiti/engine/test/bpmn/event/end/TerminateEndEventTest.testTerminateInCallActivity.bpmn",
"org/activiti/engine/test/bpmn/event/end/TerminateEndEventTest.subProcessTerminate.bpmn"
})
public void testTerminateInCallActivity() throws Exception {
ProcessInstance pi = runtimeService.startProcessInstanceByKey("terminateEndEventExample");
// should terminate the called process and continue the parent
long executionEntities = runtimeService.createExecutionQuery().count();
assertEquals(1, executionEntities);
Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).taskDefinitionKey("preNormalEnd").singleResult();
taskService.complete(task.getId());
assertProcessEnded(pi.getId());
}
@Deployment(resources={
"org/activiti/engine/test/bpmn/event/end/TerminateEndEventTest.testTerminateInCallActivityMulitInstance.bpmn",
"org/activiti/engine/test/bpmn/event/end/TerminateEndEventTest.subProcessTerminate.bpmn"
})
public void testTerminateInCallActivityMulitInstance() throws Exception {
ProcessInstance pi = runtimeService.startProcessInstanceByKey("terminateEndEventExample");
// should terminate the called process and continue the parent
long executionEntities = runtimeService.createExecutionQuery().count();
assertEquals(1, executionEntities);
Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).taskDefinitionKey("preNormalEnd").singleResult();
taskService.complete(task.getId());
assertProcessEnded(pi.getId());
}
@Deployment(resources={
"org/activiti/engine/test/bpmn/event/end/TerminateEndEventTest.testTerminateInCallActivityConcurrent.bpmn",
"org/activiti/engine/test/bpmn/event/end/TerminateEndEventTest.subProcessConcurrentTerminate.bpmn"
})
public void testTerminateInCallActivityConcurrent() throws Exception {
ProcessInstance pi = runtimeService.startProcessInstanceByKey("terminateEndEventExample");
// should terminate the called process and continue the parent
long executionEntities = runtimeService.createExecutionQuery().count();
assertEquals(1, executionEntities);
Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).taskDefinitionKey("preNormalEnd").singleResult();
taskService.complete(task.getId());
assertProcessEnded(pi.getId());
}
@Deployment(resources={
"org/activiti/engine/test/bpmn/event/end/TerminateEndEventTest.testTerminateInCallActivityConcurrentMulitInstance.bpmn",
"org/activiti/engine/test/bpmn/event/end/TerminateEndEventTest.subProcessConcurrentTerminate.bpmn"
})
public void testTerminateInCallActivityConcurrentMulitInstance() throws Exception {
ProcessInstance pi = runtimeService.startProcessInstanceByKey("terminateEndEventExample");
// should terminate the called process and continue the parent
long executionEntities = runtimeService.createExecutionQuery().count();
assertEquals(1, executionEntities);
Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).taskDefinitionKey("preNormalEnd").singleResult();
taskService.complete(task.getId());
assertProcessEnded(pi.getId());
}
} | TerminateEvent bug fix
| modules/activiti-engine/src/test/java/org/activiti/engine/test/bpmn/event/end/TerminateEndEventTest.java | TerminateEvent bug fix | |
Java | apache-2.0 | 9e135927816b1340e348397c792ed66f0de18593 | 0 | candyam5522/eureka,candyam5522/eureka,candyam5522/eureka,jsons/eureka | package edu.emory.cci.aiw.cvrg.eureka.servlet.proposition;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MediaType;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import edu.emory.cci.aiw.cvrg.eureka.common.comm.CommUtils;
import edu.emory.cci.aiw.cvrg.eureka.common.comm.PropositionWrapper;
import edu.emory.cci.aiw.cvrg.eureka.common.comm.PropositionWrapper.Type;
import edu.emory.cci.aiw.cvrg.eureka.common.entity.User;
public class SavePropositionServlet extends HttpServlet {
private static final Logger LOGGER = LoggerFactory
.getLogger(SavePropositionServlet.class);
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
LOGGER.debug("SavePropositionServlet");
String id = req.getParameter("id");
String propositions = req.getParameter("proposition");
String type = req.getParameter("type");
String name = req.getParameter("name");
String description = req.getParameter("description");
String eurekaServicesUrl = req.getSession().getServletContext()
.getInitParameter("eureka-services-url");
ObjectMapper mapper = new ObjectMapper();
List<UserProposition> props = null;
try {
props = mapper.readValue(propositions,
new TypeReference<List<UserProposition>>() {
});
} catch (Exception e) {
e.printStackTrace();
}
try {
Client client = CommUtils.getClient();
Principal principal = req.getUserPrincipal();
String userName = principal.getName();
WebResource webResource = client.resource(eurekaServicesUrl);
User user = webResource.path("/api/user/byname/" + userName)
.accept(MediaType.APPLICATION_JSON).get(User.class);
PropositionWrapper pw = new PropositionWrapper();
if (id != null && !id.equals("")) {
pw.setId(Long.valueOf(id));
}
pw.setAbbrevDisplayName(name);
if (type.equals("AND")) {
pw.setType(Type.AND);
} else {
pw.setType(Type.OR);
}
List<PropositionWrapper> children =
new ArrayList<PropositionWrapper>(props.size());
pw.setInSystem(false);
for (UserProposition userProposition : props) {
System.out.println(userProposition.getId());
LOGGER.debug(userProposition.getId());
PropositionWrapper child = new PropositionWrapper();
child.setSummarized(true);
if (userProposition.getType().equals("system")) {
child.setInSystem(true);
child.setKey(userProposition.getId());
} else {
child.setId(Long.valueOf(userProposition.getId()));
}
children.add(child);
}
pw.setChildren(children);
pw.setAbbrevDisplayName(name);
pw.setDisplayName(description);
pw.setUserId(user.getId());
ClientResponse response =
webResource.path("/api/proposition/user/validate/" + user.getId())
.type(MediaType.APPLICATION_JSON)
.post(ClientResponse.class, pw);
int status = response.getClientResponseStatus().getStatusCode();
if (status != HttpServletResponse.SC_OK) {
String msg = response.getEntity(String.class);
req.setAttribute("error", msg);
LOGGER.debug("Error: {}", msg);
}
if (pw.getId() != null) {
webResource.path("/api/proposition/user/update")
.type(MediaType.APPLICATION_JSON)
.accept(MediaType.TEXT_PLAIN)
.put(ClientResponse.class, pw);
} else {
webResource.path("/api/proposition/user/create")
.type(MediaType.APPLICATION_JSON)
.accept(MediaType.TEXT_PLAIN)
.post(ClientResponse.class, pw);
}
} catch (KeyManagementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| eureka-webapp/src/main/java/edu/emory/cci/aiw/cvrg/eureka/servlet/proposition/SavePropositionServlet.java | package edu.emory.cci.aiw.cvrg.eureka.servlet.proposition;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MediaType;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import edu.emory.cci.aiw.cvrg.eureka.common.comm.CommUtils;
import edu.emory.cci.aiw.cvrg.eureka.common.comm.PropositionWrapper;
import edu.emory.cci.aiw.cvrg.eureka.common.comm.PropositionWrapper.Type;
import edu.emory.cci.aiw.cvrg.eureka.common.entity.User;
public class SavePropositionServlet extends HttpServlet {
private static final Logger LOGGER = LoggerFactory
.getLogger(SavePropositionServlet.class);
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
LOGGER.debug("SavePropositionServlet");
String id = req.getParameter("id");
String propositions = req.getParameter("proposition");
String type = req.getParameter("type");
String name = req.getParameter("name");
String description = req.getParameter("description");
String eurekaServicesUrl = req.getSession().getServletContext()
.getInitParameter("eureka-services-url");
ObjectMapper mapper = new ObjectMapper();
List<UserProposition> props = null;
try {
props = mapper.readValue(propositions,
new TypeReference<List<UserProposition>>() {
});
} catch (Exception e) {
e.printStackTrace();
}
try {
Client client = CommUtils.getClient();
Principal principal = req.getUserPrincipal();
String userName = principal.getName();
WebResource webResource = client.resource(eurekaServicesUrl);
User user = webResource.path("/api/user/byname/" + userName)
.accept(MediaType.APPLICATION_JSON).get(User.class);
PropositionWrapper pw = new PropositionWrapper();
pw.setAbbrevDisplayName(name);
if (type.equals("AND")) {
pw.setType(Type.AND);
} else {
pw.setType(Type.OR);
}
List<PropositionWrapper> children =
new ArrayList<PropositionWrapper>(props.size());
pw.setInSystem(false);
for (UserProposition userProposition : props) {
System.out.println(userProposition.getId());
LOGGER.debug(userProposition.getId());
PropositionWrapper child = new PropositionWrapper();
child.setSummarized(true);
if (userProposition.getType().equals("system")) {
child.setInSystem(true);
child.setKey(userProposition.getId());
} else {
child.setId(Long.valueOf(userProposition.getId()));
}
children.add(child);
}
pw.setChildren(children);
pw.setAbbrevDisplayName(name);
pw.setDisplayName(description);
pw.setUserId(user.getId());
ClientResponse response =
webResource.path("/api/proposition/user/validate/" + user.getId())
.type(MediaType.APPLICATION_JSON)
.post(ClientResponse.class, pw);
int status = response.getClientResponseStatus().getStatusCode();
if (status != HttpServletResponse.SC_OK) {
String msg = response.getEntity(String.class);
req.setAttribute("error", msg);
LOGGER.debug("Error: {}", msg);
}
if (id != null && !id.equals("")) {
pw.setId(Long.valueOf(id));
webResource.path("/api/proposition/user/update")
.type(MediaType.APPLICATION_JSON)
.accept(MediaType.TEXT_PLAIN)
.put(ClientResponse.class, pw);
} else {
webResource.path("/api/proposition/user/create")
.type(MediaType.APPLICATION_JSON)
.accept(MediaType.TEXT_PLAIN)
.post(ClientResponse.class, pw);
}
} catch (KeyManagementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| Correctly set the id of the proposition when validating. Previously, it was only set for save/update, but not validation.
| eureka-webapp/src/main/java/edu/emory/cci/aiw/cvrg/eureka/servlet/proposition/SavePropositionServlet.java | Correctly set the id of the proposition when validating. Previously, it was only set for save/update, but not validation. | |
Java | apache-2.0 | 501c607d60bfc5535d7e8258a802cffa075f39a4 | 0 | mhawrylczak/Nicobar,Netflix/Nicobar,gorcz/Nicobar,reversemind/Nicobar,reversemind/Nicobar,mhawrylczak/Nicobar,Netflix/Nicobar,gorcz/Nicobar,Netflix/Nicobar | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nicobar.cassandra;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.Future;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Iterables;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.model.Column;
import com.netflix.astyanax.model.ColumnList;
import com.netflix.astyanax.model.Row;
import com.netflix.astyanax.model.Rows;
import com.netflix.nicobar.cassandra.internal.CassandraGateway;
import com.netflix.nicobar.core.archive.JarScriptArchive;
import com.netflix.nicobar.core.archive.ModuleId;
import com.netflix.nicobar.core.archive.ScriptArchive;
import com.netflix.nicobar.core.archive.ScriptModuleSpec;
import com.netflix.nicobar.core.persistence.ArchiveRepository;
import com.netflix.nicobar.core.persistence.ArchiveSummary;
import com.netflix.nicobar.core.persistence.RepositorySummary;
import com.netflix.nicobar.core.persistence.RepositoryView;
/**
* Data access object of {@link ScriptArchive}s stored in Cassandra.
* This implementation is based on the Astyanax and requires CQL 3 support to be enabled.
* <p>
* The query algorithm attempts to divide up read operations such that they won't overwhelm Cassandra
* if many instances are using this implementation to poll for updates.
* Upon insertion, all archives are assigned a shard number calculated as (moduleId.hashCode() % <number of shard>).
* The shard number is subsequently inserted into a column for which a secondary index has been defined.
* <p>
* The {@link #getArchiveUpdateTimes()} method will first search each shard for any rows with an update timestamp greater than
* the last poll time, and if any are found, the contents of those archives are loaded in small batches.
*
*
*<pre>
* Default Schema:
*
* CREATE TABLE script_repo (
* module_id varchar,
* module_name varchar,
* module_version varchar,
* shard_num int,
* last_update timestamp,
* module_spec varchar,
* archive_content_hash blob,
* archive_content blob,
* PRIMARY KEY (module_id)
* );
*
* CREATE INDEX script_repo_shard_num_index on script_repo (shard_num);
* </pre>
*
* See {@link CassandraArchiveRepositoryConfig} to override the default table name.
* @author James Kojo
* @author Vasanth Asokan
*/
public class CassandraArchiveRepository implements ArchiveRepository {
private final static Logger logger = LoggerFactory.getLogger(CassandraArchiveRepository.class);
/** column names */
public static enum Columns {
module_id,
module_name,
module_version,
shard_num,
last_update,
module_spec,
archive_content_hash,
archive_content;
}
private final CassandraArchiveRepositoryConfig config;
private final CassandraGateway cassandra;
/**
* Construct a instance of the repository with the given configuration
* @param config
*/
public CassandraArchiveRepository(CassandraArchiveRepositoryConfig config) {
this.config = Objects.requireNonNull(config, "config");
this.cassandra = this.config.getCassandraGateway();
}
@Override
public String getRepositoryId() {
return getConfig().getRepositoryId();
}
/**
* No named views supported by this repository!
* Throws UnsupportedOperationException.
*/
@Override
public RepositoryView getView(String view) {
throw new UnsupportedOperationException();
}
/**
* insert a Jar into the script archive
*/
@Override
public void insertArchive(JarScriptArchive jarScriptArchive) throws IOException {
Objects.requireNonNull(jarScriptArchive, "jarScriptArchive");
ScriptModuleSpec moduleSpec = jarScriptArchive.getModuleSpec();
ModuleId moduleId = moduleSpec.getModuleId();
Path jarFilePath;
try {
jarFilePath = Paths.get(jarScriptArchive.getRootUrl().toURI());
} catch (URISyntaxException e) {
throw new IOException(e);
}
int shardNum = calculateShardNum(moduleId);
byte[] jarBytes = Files.readAllBytes(jarFilePath);
byte[] hash = calculateHash(jarBytes);
Map<String, Object> columns = new HashMap<String, Object>();
columns.put(Columns.module_id.name(), moduleId.toString());
columns.put(Columns.module_name.name(), moduleId.getName());
columns.put(Columns.module_version.name(), moduleId.getVersion());
columns.put(Columns.shard_num.name(), shardNum);
columns.put(Columns.last_update.name(), jarScriptArchive.getCreateTime());
columns.put(Columns.archive_content_hash.name(), hash);
columns.put(Columns.archive_content.name(), jarBytes);
String serialized = getConfig().getModuleSpecSerializer().serialize(moduleSpec);
columns.put(Columns.module_spec.name(), serialized);
try {
cassandra.upsert(moduleId.toString(), columns);
} catch (Exception e) {
throw new IOException(e);
}
}
/**
* Get the last update times of all of the script archives managed by this Repository.
* @return map of moduleId to last update time
*/
public Map<ModuleId, Long> getArchiveUpdateTimes() throws IOException {
Iterable<Row<String, String>> rows;
try {
rows = getRows(EnumSet.of(Columns.module_id, Columns.last_update));
} catch (Exception e) {
throw new IOException(e);
}
Map<ModuleId, Long> updateTimes = new LinkedHashMap<ModuleId, Long>();
for (Row<String, String> row : rows) {
String moduleId = row.getKey();
Column<String> lastUpdateColumn = row.getColumns().getColumnByName(Columns.last_update.name());
Long updateTime = lastUpdateColumn != null ? lastUpdateColumn.getLongValue() : null;
if (StringUtils.isNotBlank(moduleId) && updateTime != null) {
updateTimes.put(ModuleId.fromString(moduleId), updateTime);
}
}
return updateTimes;
}
@Override
public RepositorySummary getRepositorySummary() throws IOException {
Map<ModuleId, Long> updateTimes = getArchiveUpdateTimes();
int archiveCount = updateTimes.size();
long maxUpdateTime = 0;
for (Long updateTime : updateTimes.values()) {
if (updateTime > maxUpdateTime) {
maxUpdateTime = updateTime;
}
}
String description = String.format("Cassandra Keyspace: %s Column Family: %s",
cassandra.getKeyspace().getKeyspaceName(), cassandra.getColumnFamily());
RepositorySummary repositorySummary = new RepositorySummary(getRepositoryId(),
description, archiveCount, maxUpdateTime);
return repositorySummary;
}
/**
* Get a summary of all archives in this Repository
* @return List of summaries
*/
@Override
public List<ArchiveSummary> getArchiveSummaries() throws IOException {
List<ArchiveSummary> summaries = new LinkedList<ArchiveSummary>();
Iterable<Row<String, String>> rows;
try {
rows = getRows(EnumSet.of(Columns.module_id, Columns.last_update, Columns.module_spec));
} catch (Exception e) {
throw new IOException(e);
}
for (Row<String, String> row : rows) {
String moduleId = row.getKey();
ColumnList<String> columns = row.getColumns();
Column<String> lastUpdateColumn = columns.getColumnByName(Columns.last_update.name());
long updateTime = lastUpdateColumn != null ? lastUpdateColumn.getLongValue() : 0;
ScriptModuleSpec moduleSpec = getModuleSpec(columns);
ArchiveSummary summary = new ArchiveSummary(ModuleId.fromString(moduleId), moduleSpec, updateTime);
summaries.add(summary);
}
return summaries;
}
/**
* Get all of the rows in in the table. Attempts to reduce the load on cassandra by splitting up the query into smaller sub-queries
* @param columns which columns to select
* @return result rows
*/
public Iterable<Row<String, String>> getRows(EnumSet<?> columns) throws Exception {
int shardCount = config.getShardCount();
List<Future<Rows<String, String>>> futures = new ArrayList<Future<Rows<String, String>>>();
for (int i = 0; i < shardCount; i++) {
futures.add(cassandra.selectAsync(generateSelectByShardCql(columns, i)));
}
List<Row<String, String>> rows = new LinkedList<Row<String, String>>();
for (Future<Rows<String, String>> f: futures) {
Rows<String, String> shardRows = f.get();
Iterables.addAll(rows, shardRows);
}
return rows;
}
/**
* Get all of the {@link ScriptArchive}s for the given set of moduleIds. Will perform the operation in batches
* as specified by {@link CassandraArchiveRepositoryConfig#getArchiveFetchBatchSize()} and outputs the jar files in
* the path specified by {@link CassandraArchiveRepositoryConfig#getArchiveOutputDirectory()}.
*
* @param moduleIds keys to search for
* @return set of ScriptArchives retrieved from the database
*/
@Override
public Set<ScriptArchive> getScriptArchives(Set<ModuleId> moduleIds) throws IOException {
Set<ScriptArchive> archives = new LinkedHashSet<ScriptArchive>(moduleIds.size()*2);
Path archiveOuputDir = getConfig().getArchiveOutputDirectory();
List<ModuleId> moduleIdList = new LinkedList<ModuleId>(moduleIds);
int batchSize = getConfig().getArchiveFetchBatchSize();
int start = 0;
try {
while (start < moduleIdList.size()) {
int end = Math.min(moduleIdList.size(), start + batchSize);
List<ModuleId> batchModuleIds = moduleIdList.subList(start, end);
List<String> rowKeys = new ArrayList<String>(batchModuleIds.size());
for (ModuleId batchModuleId:batchModuleIds) {
rowKeys.add(batchModuleId.toString());
}
Rows<String, String> rows = cassandra.getRows(rowKeys.toArray(new String[0]));
for (Row<String, String> row : rows) {
String moduleId = row.getKey();
ColumnList<String> columns = row.getColumns();
Column<String> lastUpdateColumn = columns.getColumnByName(Columns.last_update.name());
Column<String> hashColumn = columns.getColumnByName(Columns.archive_content_hash.name());
Column<String> contentColumn = columns.getColumnByName(Columns.archive_content.name());
if (lastUpdateColumn == null || hashColumn == null || contentColumn == null) {
continue;
}
ScriptModuleSpec moduleSpec = getModuleSpec(columns);
long lastUpdateTime = lastUpdateColumn.getLongValue();
byte[] hash = hashColumn.getByteArrayValue();
byte[] content = contentColumn.getByteArrayValue();
// verify the hash
if (hash != null && hash.length > 0 && !verifyHash(hash, content)) {
logger.warn("Content hash validation failed for moduleId {}. size: {}", moduleId, content.length);
continue;
}
String fileName = new StringBuilder().append(moduleId).append("-").append(lastUpdateTime).append(".jar").toString();
Path jarFile = archiveOuputDir.resolve(fileName);
Files.write(jarFile, content);
JarScriptArchive scriptArchive = new JarScriptArchive.Builder(jarFile)
.setModuleSpec(moduleSpec)
.setCreateTime(lastUpdateTime)
.build();
archives.add(scriptArchive);
}
start = end;
}
} catch (Exception e) {
throw new IOException(e);
}
return archives;
}
/**
* Delete an archive by ID
* @param moduleId module id to delete
* @throws ConnectionException
*/
@Override
public void deleteArchive(ModuleId moduleId) throws IOException {
Objects.requireNonNull(moduleId, "moduleId");
cassandra.deleteRow(moduleId.toString());
}
@Override
public void addDeploySpecs(ModuleId moduleId, Map<String, Object> deploySpecs) {
throw new UnsupportedOperationException();
}
/**
* Generate the CQL to select specific columns by shard number.
* SELECT <columns>... FROM script_repo WHERE shard_num = ?
*/
protected String generateSelectByShardCql(EnumSet<?> columns, Integer shardNum) {
StringBuilder sb = new StringBuilder()
.append("SELECT ");
boolean first = true;
for (Enum<?> column : columns) {
if (first) {
first = false;
} else {
sb.append(",");
}
sb.append(column.name());
}
sb.append("\n")
.append("FROM ").append(cassandra.getColumnFamily())
.append("\n").append("WHERE ").append(Columns.shard_num.name())
.append(" = ").append(shardNum).append("\n");
return sb.toString();
}
protected boolean verifyHash(byte[] expectedHashCode, byte[] content) {
byte[] hashCode = calculateHash(content);
return Arrays.equals(expectedHashCode, hashCode);
}
protected byte[] calculateHash(byte[] content) {
MessageDigest digester;
try {
digester = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
// should never happen
return null;
}
byte[] hashCode = digester.digest(content);
return hashCode;
}
protected int calculateShardNum(ModuleId moduleId) {
return Math.abs(moduleId.hashCode() % getConfig().getShardCount());
}
private ScriptModuleSpec getModuleSpec(ColumnList<String> columns) {
ScriptModuleSpec moduleSpec = null;
if (columns != null) {
Column<String> moduleSpecColumn = columns.getColumnByName(Columns.module_spec.name());
if (moduleSpecColumn != null && moduleSpecColumn.hasValue()) {
String moduleSpecString = moduleSpecColumn.getStringValue();
moduleSpec = getConfig().getModuleSpecSerializer().deserialize(moduleSpecString);
}
}
return moduleSpec;
}
/**
* @return configuration settings for this repository
*/
public CassandraArchiveRepositoryConfig getConfig() {
return config;
}
}
| nicobar-cassandra/src/main/java/com/netflix/nicobar/cassandra/CassandraArchiveRepository.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nicobar.cassandra;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.Future;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Iterables;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.model.Column;
import com.netflix.astyanax.model.ColumnList;
import com.netflix.astyanax.model.Row;
import com.netflix.astyanax.model.Rows;
import com.netflix.nicobar.cassandra.internal.CassandraGateway;
import com.netflix.nicobar.core.archive.JarScriptArchive;
import com.netflix.nicobar.core.archive.ModuleId;
import com.netflix.nicobar.core.archive.ScriptArchive;
import com.netflix.nicobar.core.archive.ScriptModuleSpec;
import com.netflix.nicobar.core.persistence.ArchiveRepository;
import com.netflix.nicobar.core.persistence.ArchiveSummary;
import com.netflix.nicobar.core.persistence.RepositorySummary;
import com.netflix.nicobar.core.persistence.RepositoryView;
/**
* Data access object of {@link ScriptArchive}s stored in Cassandra.
* This implementation is based on the Astyanax and requires CQL 3 support to be enabled.
* <p>
* The query algorithm attempts to divide up read operations such that they won't overwhelm Cassandra
* if many instances are using this implementation to poll for updates.
* Upon insertion, all archives are assigned a shard number calculated as (moduleId.hashCode() % <number of shard>).
* The shard number is subsequently inserted into a column for which a secondary index has been defined.
* <p>
* The {@link #getArchiveUpdateTimes()} method will first search each shard for any rows with an update timestamp greater than
* the last poll time, and if any are found, the contents of those archives are loaded in small batches.
*
*
*<pre>
* Default Schema:
*
* CREATE TABLE script_repo (
* module_id varchar,
* shard_num int,
* last_update timestamp,
* module_spec varchar,
* archive_content_hash blob,
* archive_content blob,
* PRIMARY KEY (module_id)
* );
*
* CREATE INDEX script_repo_shard_num_index on script_repo (shard_num);
* </pre>
*
* See {@link CassandraArchiveRepositoryConfig} to override the default table name.
* @author James Kojo
* @author Vasanth Asokan
*/
public class CassandraArchiveRepository implements ArchiveRepository {
private final static Logger logger = LoggerFactory.getLogger(CassandraArchiveRepository.class);
/** column names */
public static enum Columns {
module_id,
shard_num,
last_update,
module_spec,
archive_content_hash,
archive_content;
}
private final CassandraArchiveRepositoryConfig config;
private final CassandraGateway cassandra;
/**
* Construct a instance of the repository with the given configuration
* @param config
*/
public CassandraArchiveRepository(CassandraArchiveRepositoryConfig config) {
this.config = Objects.requireNonNull(config, "config");
this.cassandra = this.config.getCassandraGateway();
}
@Override
public String getRepositoryId() {
return getConfig().getRepositoryId();
}
/**
* No named views supported by this repository!
* Throws UnsupportedOperationException.
*/
@Override
public RepositoryView getView(String view) {
throw new UnsupportedOperationException();
}
/**
* insert a Jar into the script archive
*/
@Override
public void insertArchive(JarScriptArchive jarScriptArchive) throws IOException {
Objects.requireNonNull(jarScriptArchive, "jarScriptArchive");
ScriptModuleSpec moduleSpec = jarScriptArchive.getModuleSpec();
ModuleId moduleId = moduleSpec.getModuleId();
Path jarFilePath;
try {
jarFilePath = Paths.get(jarScriptArchive.getRootUrl().toURI());
} catch (URISyntaxException e) {
throw new IOException(e);
}
int shardNum = calculateShardNum(moduleId);
byte[] jarBytes = Files.readAllBytes(jarFilePath);
byte[] hash = calculateHash(jarBytes);
Map<String, Object> columns = new HashMap<String, Object>();
columns.put(Columns.shard_num.name(), shardNum);
columns.put(Columns.last_update.name(), jarScriptArchive.getCreateTime());
columns.put(Columns.archive_content_hash.name(), hash);
columns.put(Columns.archive_content.name(), jarBytes);
String serialized = getConfig().getModuleSpecSerializer().serialize(moduleSpec);
columns.put(Columns.module_spec.name(), serialized);
try {
cassandra.upsert(moduleId.toString(), columns);
} catch (Exception e) {
throw new IOException(e);
}
}
/**
* Get the last update times of all of the script archives managed by this Repository.
* @return map of moduleId to last update time
*/
public Map<ModuleId, Long> getArchiveUpdateTimes() throws IOException {
Iterable<Row<String, String>> rows;
try {
rows = getRows(EnumSet.of(Columns.module_id, Columns.last_update));
} catch (Exception e) {
throw new IOException(e);
}
Map<ModuleId, Long> updateTimes = new LinkedHashMap<ModuleId, Long>();
for (Row<String, String> row : rows) {
String moduleId = row.getKey();
Column<String> lastUpdateColumn = row.getColumns().getColumnByName(Columns.last_update.name());
Long updateTime = lastUpdateColumn != null ? lastUpdateColumn.getLongValue() : null;
if (StringUtils.isNotBlank(moduleId) && updateTime != null) {
updateTimes.put(ModuleId.fromString(moduleId), updateTime);
}
}
return updateTimes;
}
@Override
public RepositorySummary getRepositorySummary() throws IOException {
Map<ModuleId, Long> updateTimes = getArchiveUpdateTimes();
int archiveCount = updateTimes.size();
long maxUpdateTime = 0;
for (Long updateTime : updateTimes.values()) {
if (updateTime > maxUpdateTime) {
maxUpdateTime = updateTime;
}
}
String description = String.format("Cassandra Keyspace: %s Column Family: %s",
cassandra.getKeyspace().getKeyspaceName(), cassandra.getColumnFamily());
RepositorySummary repositorySummary = new RepositorySummary(getRepositoryId(),
description, archiveCount, maxUpdateTime);
return repositorySummary;
}
/**
* Get a summary of all archives in this Repository
* @return List of summaries
*/
@Override
public List<ArchiveSummary> getArchiveSummaries() throws IOException {
List<ArchiveSummary> summaries = new LinkedList<ArchiveSummary>();
Iterable<Row<String, String>> rows;
try {
rows = getRows(EnumSet.of(Columns.module_id, Columns.last_update, Columns.module_spec));
} catch (Exception e) {
throw new IOException(e);
}
for (Row<String, String> row : rows) {
String moduleId = row.getKey();
ColumnList<String> columns = row.getColumns();
Column<String> lastUpdateColumn = columns.getColumnByName(Columns.last_update.name());
long updateTime = lastUpdateColumn != null ? lastUpdateColumn.getLongValue() : 0;
ScriptModuleSpec moduleSpec = getModuleSpec(columns);
ArchiveSummary summary = new ArchiveSummary(ModuleId.fromString(moduleId), moduleSpec, updateTime);
summaries.add(summary);
}
return summaries;
}
/**
* Get all of the rows in in the table. Attempts to reduce the load on cassandra by splitting up the query into smaller sub-queries
* @param columns which columns to select
* @return result rows
*/
public Iterable<Row<String, String>> getRows(EnumSet<?> columns) throws Exception {
int shardCount = config.getShardCount();
List<Future<Rows<String, String>>> futures = new ArrayList<Future<Rows<String, String>>>();
for (int i = 0; i < shardCount; i++) {
futures.add(cassandra.selectAsync(generateSelectByShardCql(columns, i)));
}
List<Row<String, String>> rows = new LinkedList<Row<String, String>>();
for (Future<Rows<String, String>> f: futures) {
Rows<String, String> shardRows = f.get();
Iterables.addAll(rows, shardRows);
}
return rows;
}
/**
* Get all of the {@link ScriptArchive}s for the given set of moduleIds. Will perform the operation in batches
* as specified by {@link CassandraArchiveRepositoryConfig#getArchiveFetchBatchSize()} and outputs the jar files in
* the path specified by {@link CassandraArchiveRepositoryConfig#getArchiveOutputDirectory()}.
*
* @param moduleIds keys to search for
* @return set of ScriptArchives retrieved from the database
*/
@Override
public Set<ScriptArchive> getScriptArchives(Set<ModuleId> moduleIds) throws IOException {
Set<ScriptArchive> archives = new LinkedHashSet<ScriptArchive>(moduleIds.size()*2);
Path archiveOuputDir = getConfig().getArchiveOutputDirectory();
List<ModuleId> moduleIdList = new LinkedList<ModuleId>(moduleIds);
int batchSize = getConfig().getArchiveFetchBatchSize();
int start = 0;
try {
while (start < moduleIdList.size()) {
int end = Math.min(moduleIdList.size(), start + batchSize);
List<ModuleId> batchModuleIds = moduleIdList.subList(start, end);
List<String> rowKeys = new ArrayList<String>(batchModuleIds.size());
for (ModuleId batchModuleId:batchModuleIds) {
rowKeys.add(batchModuleId.toString());
}
Rows<String, String> rows = cassandra.getRows(rowKeys.toArray(new String[0]));
for (Row<String, String> row : rows) {
String moduleId = row.getKey();
ColumnList<String> columns = row.getColumns();
Column<String> lastUpdateColumn = columns.getColumnByName(Columns.last_update.name());
Column<String> hashColumn = columns.getColumnByName(Columns.archive_content_hash.name());
Column<String> contentColumn = columns.getColumnByName(Columns.archive_content.name());
if (lastUpdateColumn == null || hashColumn == null || contentColumn == null) {
continue;
}
ScriptModuleSpec moduleSpec = getModuleSpec(columns);
long lastUpdateTime = lastUpdateColumn.getLongValue();
byte[] hash = hashColumn.getByteArrayValue();
byte[] content = contentColumn.getByteArrayValue();
// verify the hash
if (hash != null && hash.length > 0 && !verifyHash(hash, content)) {
logger.warn("Content hash validation failed for moduleId {}. size: {}", moduleId, content.length);
continue;
}
String fileName = new StringBuilder().append(moduleId).append("-").append(lastUpdateTime).append(".jar").toString();
Path jarFile = archiveOuputDir.resolve(fileName);
Files.write(jarFile, content);
JarScriptArchive scriptArchive = new JarScriptArchive.Builder(jarFile)
.setModuleSpec(moduleSpec)
.setCreateTime(lastUpdateTime)
.build();
archives.add(scriptArchive);
}
start = end;
}
} catch (Exception e) {
throw new IOException(e);
}
return archives;
}
/**
* Delete an archive by ID
* @param moduleId module id to delete
* @throws ConnectionException
*/
@Override
public void deleteArchive(ModuleId moduleId) throws IOException {
Objects.requireNonNull(moduleId, "moduleId");
cassandra.deleteRow(moduleId.toString());
}
@Override
public void addDeploySpecs(ModuleId moduleId, Map<String, Object> deploySpecs) {
throw new UnsupportedOperationException();
}
/**
* Generate the CQL to select specific columns by shard number.
* SELECT <columns>... FROM script_repo WHERE shard_num = ?
*/
protected String generateSelectByShardCql(EnumSet<?> columns, Integer shardNum) {
StringBuilder sb = new StringBuilder()
.append("SELECT ");
boolean first = true;
for (Enum<?> column : columns) {
if (first) {
first = false;
} else {
sb.append(",");
}
sb.append(column.name());
}
sb.append("\n")
.append("FROM ").append(cassandra.getColumnFamily())
.append("\n").append("WHERE ").append(Columns.shard_num.name())
.append(" = ").append(shardNum).append("\n");
return sb.toString();
}
protected boolean verifyHash(byte[] expectedHashCode, byte[] content) {
byte[] hashCode = calculateHash(content);
return Arrays.equals(expectedHashCode, hashCode);
}
protected byte[] calculateHash(byte[] content) {
MessageDigest digester;
try {
digester = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
// should never happen
return null;
}
byte[] hashCode = digester.digest(content);
return hashCode;
}
protected int calculateShardNum(ModuleId moduleId) {
return Math.abs(moduleId.hashCode() % getConfig().getShardCount());
}
private ScriptModuleSpec getModuleSpec(ColumnList<String> columns) {
ScriptModuleSpec moduleSpec = null;
if (columns != null) {
Column<String> moduleSpecColumn = columns.getColumnByName(Columns.module_spec.name());
if (moduleSpecColumn != null && moduleSpecColumn.hasValue()) {
String moduleSpecString = moduleSpecColumn.getStringValue();
moduleSpec = getConfig().getModuleSpecSerializer().deserialize(moduleSpecString);
}
}
return moduleSpec;
}
/**
* @return configuration settings for this repository
*/
public CassandraArchiveRepositoryConfig getConfig() {
return config;
}
}
| Include module id, module name and module version in cassandra columns
| nicobar-cassandra/src/main/java/com/netflix/nicobar/cassandra/CassandraArchiveRepository.java | Include module id, module name and module version in cassandra columns | |
Java | apache-2.0 | 5369c5d873dd237e165c797653d2e07695dd9f9c | 0 | sdgdsffdsfff/stagemonitor,sdgdsffdsfff/stagemonitor,trampi/stagemonitor,glamarre360/stagemonitor,stagemonitor/stagemonitor,hexdecteam/stagemonitor,marcust/stagemonitor,elevennl/stagemonitor,glamarre360/stagemonitor,marcust/stagemonitor,glamarre360/stagemonitor,hexdecteam/stagemonitor,trampi/stagemonitor,elevennl/stagemonitor,stagemonitor/stagemonitor,elevennl/stagemonitor,trampi/stagemonitor,sdgdsffdsfff/stagemonitor,glamarre360/stagemonitor,stagemonitor/stagemonitor,elevennl/stagemonitor,hexdecteam/stagemonitor,trampi/stagemonitor,marcust/stagemonitor,sdgdsffdsfff/stagemonitor,stagemonitor/stagemonitor,hexdecteam/stagemonitor,marcust/stagemonitor | package org.stagemonitor.requestmonitor;
import static com.codahale.metrics.MetricRegistry.name;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.stagemonitor.core.CorePlugin;
import org.stagemonitor.core.MeasurementSession;
import org.stagemonitor.core.Stagemonitor;
import org.stagemonitor.core.configuration.Configuration;
import org.stagemonitor.core.util.GraphiteSanitizer;
import org.stagemonitor.requestmonitor.profiler.CallStackElement;
import org.stagemonitor.requestmonitor.profiler.Profiler;
public class RequestMonitor {
private static final Logger logger = LoggerFactory.getLogger(RequestMonitor.class);
private static final String REQUEST = "request";
/**
* Helps to detect, if this request is the 'real' one or just the forwarding one.
* Example: /a is forwarding the request to /b. /a is the forwarding request /b is the real or forwarded request.
* Only /b will be measured, /a will be ignored.
* <p/>
* To enable this behaviour in a web environment, make sure to set stagemonitor.web.monitorOnlyForwardedRequests to true.
*/
private static ThreadLocal<RequestInformation<? extends RequestTrace>> request = new ThreadLocal<RequestInformation<? extends RequestTrace>>();
private static final List<RequestTraceReporter> requestTraceReporters = new CopyOnWriteArrayList<RequestTraceReporter>() {{
add(new LogRequestTraceReporter());
add(new ElasticsearchRequestTraceReporter());
}};
private static ExecutorService asyncRequestTraceReporterPool = Executors.newSingleThreadExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
thread.setName("async-request-reporter");
return thread;
}
});
private int warmupRequests = 0;
private AtomicBoolean warmedUp = new AtomicBoolean(false);
private AtomicInteger noOfRequests = new AtomicInteger(0);
private MetricRegistry metricRegistry;
private CorePlugin corePlugin;
private RequestMonitorPlugin requestMonitorPlugin;
private ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
private final boolean isCurrentThreadCpuTimeSupported = threadMXBean.isCurrentThreadCpuTimeSupported();
private Date endOfWarmup;
public RequestMonitor() {
this(Stagemonitor.getConfiguration());
}
public RequestMonitor(Configuration configuration) {
this(configuration, Stagemonitor.getMetricRegistry());
}
public RequestMonitor(Configuration configuration, MetricRegistry registry) {
this(configuration.getConfig(CorePlugin.class), registry, configuration.getConfig(RequestMonitorPlugin.class));
}
public RequestMonitor(CorePlugin corePlugin, MetricRegistry registry, RequestMonitorPlugin requestMonitorPlugin) {
this.metricRegistry = registry;
this.corePlugin = corePlugin;
this.requestMonitorPlugin = requestMonitorPlugin;
warmupRequests = requestMonitorPlugin.getNoOfWarmupRequests();
endOfWarmup = new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(requestMonitorPlugin.getWarmupSeconds()));
}
public <T extends RequestTrace> void monitorStart(MonitoredRequest<T> monitoredRequest) {
final long start = System.nanoTime();
RequestInformation<T> info = new RequestInformation<T>();
info.monitoredRequest = monitoredRequest;
detectForwardedRequest(info);
request.set(info);
try {
if (!corePlugin.isStagemonitorActive()) {
return;
}
if (Stagemonitor.getMeasurementSession().isNull()) {
createMeasurementSession();
}
info.firstRequest = noOfRequests.get() == 0;
if (Stagemonitor.getMeasurementSession().getInstanceName() == null) {
getInstanceNameFromExecution(monitoredRequest);
}
if (info.monitorThisRequest()) {
if (!Stagemonitor.isStarted()) {
info.startup = Stagemonitor.startMonitoring();
}
beforeExecution(monitoredRequest, info);
}
} finally {
info.overhead1 = System.nanoTime() - start;
}
}
public <T extends RequestTrace> void monitorStop() {
long overhead2 = System.nanoTime();
final RequestInformation<T> info = (RequestInformation<T>) request.get();
request.set(info.parent);
if (info.monitorThisRequest() && info.hasRequestName()) {
try {
if (info.startup != null) {
info.startup.get();
}
monitorAfterExecution(info.monitoredRequest, info);
} catch (Exception e) {
logger.warn(e.getMessage() + " (this exception is ignored) " + info.toString(), e);
}
} else {
removeTimerIfCountIsZero(info);
}
cleanUpAfter(info);
if (!info.firstRequest) {
trackOverhead(info.overhead1, overhead2);
}
}
private <T extends RequestTrace> void cleanUpAfter(RequestInformation<T> info) {
if (info.requestTrace != null) {
Profiler.clearMethodCallParent();
}
}
public <T extends RequestTrace> RequestInformation<T> monitor(MonitoredRequest<T> monitoredRequest) throws Exception {
try {
monitorStart(monitoredRequest);
final RequestInformation<T> info = (RequestInformation<T>) request.get();
info.executionResult = monitoredRequest.execute();
return info;
} catch (Exception e) {
recordException(e);
throw e;
} finally {
monitorStop();
}
}
public void recordException(Exception e) {
final RequestInformation<? extends RequestTrace> info = request.get();
if (info.requestTrace != null) {
info.requestTrace.setException(e);
}
}
private void trackOverhead(long overhead1, long overhead2) {
if (corePlugin.isInternalMonitoringActive()) {
overhead2 = System.nanoTime() - overhead2;
metricRegistry.timer("internal.overhead.RequestMonitor").update(overhead2 + overhead1, NANOSECONDS);
}
}
/*
* In case the instance name is not set by configuration, try to read from monitored execution
* (e.g. the domain name from a HTTP request)
*/
private synchronized void getInstanceNameFromExecution(MonitoredRequest<?> monitoredRequest) {
final MeasurementSession measurementSession = Stagemonitor.getMeasurementSession();
if (measurementSession.getInstanceName() == null) {
MeasurementSession session = new MeasurementSession(measurementSession.getApplicationName(), measurementSession.getHostName(),
monitoredRequest.getInstanceName());
Stagemonitor.setMeasurementSession(session);
}
}
private synchronized void createMeasurementSession() {
if (Stagemonitor.getMeasurementSession().isNull()) {
MeasurementSession session = new MeasurementSession(corePlugin.getApplicationName(), MeasurementSession.getNameOfLocalHost(),
corePlugin.getInstanceName());
Stagemonitor.setMeasurementSession(session);
}
}
private <T extends RequestTrace> void beforeExecution(MonitoredRequest<T> monitoredRequest, RequestInformation<T> info) {
info.requestTrace = monitoredRequest.createRequestTrace();
try {
if (info.profileThisRequest()) {
final CallStackElement root = Profiler.activateProfiling("total");
info.requestTrace.setCallStack(root);
}
} catch (RuntimeException e) {
logger.warn(e.getMessage() + " (this exception is ignored) " + info.toString(), e);
}
}
private <T extends RequestTrace> void detectForwardedRequest(RequestInformation<T> info) {
if (request.get() != null) {
// there is already an request set in this thread -> this execution must have been forwarded
info.parent = (RequestInformation<T>) request.get();
info.parent.child = info;
}
}
private <T extends RequestTrace> void monitorAfterExecution(MonitoredRequest<T> monitoredRequest, RequestInformation<T> info) {
final T requestTrace = info.requestTrace;
final long executionTime = System.nanoTime() - info.start;
final long cpuTime = getCpuTime() - info.startCpu;
requestTrace.setExecutionTime(NANOSECONDS.toMillis(executionTime));
requestTrace.setExecutionTimeCpu(NANOSECONDS.toMillis(cpuTime));
monitoredRequest.onPostExecute(info);
if (requestTrace.getCallStack() != null) {
Profiler.stop();
requestTrace.getCallStack().setSignature(requestTrace.getName());
reportRequestTrace(requestTrace);
}
trackMetrics(info, executionTime, cpuTime);
}
private <T extends RequestTrace> void removeTimerIfCountIsZero(RequestInformation<T> info) {
if (info.timerCreated) {
String timerMetricName = getTimerMetricName(info.getTimerName());
if (info.getRequestTimer().getCount() == 0 && metricRegistry.getMetrics().get(timerMetricName) != null) {
metricRegistry.remove(timerMetricName);
}
}
}
private <T extends RequestTrace> void trackMetrics(RequestInformation<T> info, long executionTime, long cpuTime) {
T requestTrace = info.requestTrace;
String timerName = info.getTimerName();
info.getRequestTimer().update(executionTime, NANOSECONDS);
metricRegistry.timer(getTimerMetricName("All")).update(executionTime, NANOSECONDS);
if (requestMonitorPlugin.isCollectCpuTime()) {
metricRegistry.timer(name(REQUEST, timerName, "server.cpu-time.total")).update(cpuTime, NANOSECONDS);
metricRegistry.timer("request.All.server.cpu-time.total").update(cpuTime, NANOSECONDS);
}
if (requestTrace.isError()) {
metricRegistry.meter(name(REQUEST, timerName, "server.meter.error")).mark();
metricRegistry.meter("request.All.server.meter.error").mark();
}
trackDbMetrics(timerName, requestTrace);
}
private <T extends RequestTrace> void trackDbMetrics(String timerName, T requestTrace) {
if (requestTrace.getExecutionCountDb() > 0) {
if (requestMonitorPlugin.isCollectDbTimePerRequest()) {
metricRegistry.timer(name(REQUEST, timerName, "server.time.db")).update(requestTrace.getExecutionTimeDb(), MILLISECONDS);
metricRegistry.timer(name("request.All.server.time.db")).update(requestTrace.getExecutionTimeDb(), MILLISECONDS);
}
metricRegistry.meter(name(REQUEST, timerName, "server.meter.db")).mark(requestTrace.getExecutionCountDb());
metricRegistry.meter("request.All.server.meter.db").mark(requestTrace.getExecutionCountDb());
}
}
private <T extends RequestTrace> String getTimerMetricName(String timerName) {
return name(REQUEST, timerName, "server.time.total");
}
private <T extends RequestTrace> void reportRequestTrace(final T requestTrace) {
try {
asyncRequestTraceReporterPool.submit(new Runnable() {
@Override
public void run() {
for (RequestTraceReporter requestTraceReporter : requestTraceReporters) {
if (requestTraceReporter.isActive()) {
try {
requestTraceReporter.reportRequestTrace(requestTrace);
} catch (Exception e) {
logger.warn(e.getMessage() + " (this exception is ignored)", e);
}
}
}
}
});
} catch (RejectedExecutionException e) {
logger.warn(e.getMessage() + " (this exception is ignored)", e);
}
}
public boolean isWarmedUp() {
if (!warmedUp.get()) {
warmedUp.set(warmupRequests < noOfRequests.incrementAndGet() && new Date(System.currentTimeMillis() + 1).after(endOfWarmup));
return warmedUp.get();
} else {
return true;
}
}
private long getCpuTime() {
return isCurrentThreadCpuTimeSupported ? threadMXBean.getCurrentThreadCpuTime() : 0L;
}
public class RequestInformation<T extends RequestTrace> {
private boolean timerCreated = false;
T requestTrace = null;
private long start = System.nanoTime();
private long startCpu = getCpuTime();
private Object executionResult = null;
private Future<?> startup;
private long overhead1;
private MonitoredRequest<T> monitoredRequest;
private boolean firstRequest;
private RequestInformation<T> parent;
private RequestInformation<T> child;
/**
* If the request has no name it means that it should not be monitored.
*
* @return <code>true</code>, if the request trace has a name, <code>false</code> otherwise
*/
private boolean hasRequestName() {
return requestTrace != null && requestTrace.getName() != null && !requestTrace.getName().isEmpty();
}
private boolean monitorThisRequest() {
if (!requestMonitorPlugin.isCollectRequestStats() || !isWarmedUp()) {
return false;
}
if (isForwarded() && isForwarding()) {
return false;
}
if (isForwarded()) {
return monitoredRequest.isMonitorForwardedExecutions();
}
if (isForwarding()) {
return !monitoredRequest.isMonitorForwardedExecutions();
}
return true;
}
public String getTimerName() {
return name(GraphiteSanitizer.sanitizeGraphiteMetricSegment(requestTrace.getName()));
}
/**
* Returns the request trace or <code>null</code>, if
* {@link org.stagemonitor.requestmonitor.RequestMonitor#isWarmedUp()} is <code>false</code>
*
* @return the request trace or <code>null</code>, if
* {@link org.stagemonitor.requestmonitor.RequestMonitor#isWarmedUp()} is <code>false</code>
*/
public T getRequestTrace() {
return requestTrace;
}
public Timer getRequestTimer() {
timerCreated = true;
return metricRegistry.timer(getTimerMetricName(getTimerName()));
}
private boolean profileThisRequest() {
if (!requestMonitorPlugin.isProfilerActive()) {
return false;
}
int callStackEveryXRequestsToGroup = requestMonitorPlugin.getCallStackEveryXRequestsToGroup();
if (callStackEveryXRequestsToGroup == 1) {
return true;
}
if (callStackEveryXRequestsToGroup < 1) {
return false;
}
Timer requestTimer = getRequestTimer();
if (requestTimer.getCount() == 0) {
return false;
}
return requestTimer.getCount() % callStackEveryXRequestsToGroup == 0;
}
/**
* A forwarding request is one that forwards a request to another execution.
* <p/>
* Examples:
* <p/>
* - web environment: request to /a makes a
* {@link javax.servlet.RequestDispatcher#forward(ServletRequest, ServletResponse)} to /b.
* /a is the forwarding execution, /b is the forwarded execution
* <p/>
* - plain method calls: monitored method a() calls monitored method b()
* (monitored means monitored by {@link RequestMonitor}).
* Method a() is the forwarding execution, Method b() is the forwarded execution.
*
* @return true, if this request is a forwarding request, false otherwise
*/
private boolean isForwarding() {
return child != null;
}
public Object getExecutionResult() {
return executionResult;
}
@Override
public String toString() {
return "RequestInformation{" +
"requestTrace=" + requestTrace +
", start=" + start +
", startCpu=" + startCpu +
", forwardedExecution=" + isForwarded() +
", executionResult=" + executionResult +
'}';
}
public boolean isForwarded() {
return parent != null;
}
}
/**
* @return the {@link RequestTrace} of the current request
*/
public static RequestTrace getRequest() {
final RequestInformation<? extends RequestTrace> requestInformation = request.get();
return requestInformation != null ? requestInformation.getRequestTrace() : null;
}
/**
* Adds a {@link RequestTraceReporter}
*
* @param requestTraceReporter the {@link RequestTraceReporter} to add
*/
public static void addRequestTraceReporter(RequestTraceReporter requestTraceReporter) {
requestTraceReporters.add(0, requestTraceReporter);
}
}
| stagemonitor-requestmonitor/src/main/java/org/stagemonitor/requestmonitor/RequestMonitor.java | package org.stagemonitor.requestmonitor;
import static com.codahale.metrics.MetricRegistry.name;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.stagemonitor.core.CorePlugin;
import org.stagemonitor.core.MeasurementSession;
import org.stagemonitor.core.Stagemonitor;
import org.stagemonitor.core.configuration.Configuration;
import org.stagemonitor.core.util.GraphiteSanitizer;
import org.stagemonitor.requestmonitor.profiler.CallStackElement;
import org.stagemonitor.requestmonitor.profiler.Profiler;
public class RequestMonitor {
private static final Logger logger = LoggerFactory.getLogger(RequestMonitor.class);
private static final String REQUEST = "request";
/**
* Helps to detect, if this request is the 'real' one or just the forwarding one.
* Example: /a is forwarding the request to /b. /a is the forwarding request /b is the real or forwarded request.
* Only /b will be measured, /a will be ignored.
* <p/>
* To enable this behaviour in a web environment, make sure to set stagemonitor.web.monitorOnlyForwardedRequests to true.
*/
private static ThreadLocal<RequestInformation<? extends RequestTrace>> request = new ThreadLocal<RequestInformation<? extends RequestTrace>>();
private static final List<RequestTraceReporter> requestTraceReporters = new CopyOnWriteArrayList<RequestTraceReporter>() {{
add(new LogRequestTraceReporter());
add(new ElasticsearchRequestTraceReporter());
}};
private static ExecutorService asyncRequestTraceReporterPool = Executors.newSingleThreadExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
thread.setName("async-request-reporter");
return thread;
}
});
private int warmupRequests = 0;
private AtomicBoolean warmedUp = new AtomicBoolean(false);
private AtomicInteger noOfRequests = new AtomicInteger(0);
private MetricRegistry metricRegistry;
private CorePlugin corePlugin;
private RequestMonitorPlugin requestMonitorPlugin;
private ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
private final boolean isCurrentThreadCpuTimeSupported = threadMXBean.isCurrentThreadCpuTimeSupported();
private Date endOfWarmup;
public RequestMonitor() {
this(Stagemonitor.getConfiguration());
}
public RequestMonitor(Configuration configuration) {
this(configuration, Stagemonitor.getMetricRegistry());
}
public RequestMonitor(Configuration configuration, MetricRegistry registry) {
this(configuration.getConfig(CorePlugin.class), registry, configuration.getConfig(RequestMonitorPlugin.class));
}
public RequestMonitor(CorePlugin corePlugin, MetricRegistry registry, RequestMonitorPlugin requestMonitorPlugin) {
this.metricRegistry = registry;
this.corePlugin = corePlugin;
this.requestMonitorPlugin = requestMonitorPlugin;
warmupRequests = requestMonitorPlugin.getNoOfWarmupRequests();
endOfWarmup = new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(requestMonitorPlugin.getWarmupSeconds()));
}
public <T extends RequestTrace> void monitorStart(MonitoredRequest<T> monitoredRequest) {
final long start = System.nanoTime();
RequestInformation<T> info = new RequestInformation<T>();
info.monitoredRequest = monitoredRequest;
detectForwardedRequest(info);
request.set(info);
try {
if (!corePlugin.isStagemonitorActive()) {
return;
}
if (Stagemonitor.getMeasurementSession().isNull()) {
createMeasurementSession();
}
info.firstRequest = noOfRequests.get() == 0;
if (Stagemonitor.getMeasurementSession().getInstanceName() == null) {
getInstanceNameFromExecution(monitoredRequest);
}
if (info.monitorThisRequest()) {
if (!Stagemonitor.isStarted()) {
info.startup = Stagemonitor.startMonitoring();
}
beforeExecution(monitoredRequest, info);
}
} finally {
info.overhead1 = System.nanoTime() - start;
}
}
public <T extends RequestTrace> void monitorStop() {
long overhead2 = System.nanoTime();
final RequestInformation<T> info = (RequestInformation<T>) request.get();
request.set(info.parent);
if (info.monitorThisRequest() && info.hasRequestName()) {
try {
if (info.startup != null) {
info.startup.get();
}
monitorAfterExecution(info.monitoredRequest, info);
} catch (Exception e) {
logger.warn(e.getMessage() + " (this exception is ignored) " + info.toString(), e);
}
} else {
removeTimerIfCountIsZero(info);
}
cleanUpAfter(info);
if (!info.firstRequest) {
trackOverhead(info.overhead1, overhead2);
}
}
private <T extends RequestTrace> void cleanUpAfter(RequestInformation<T> info) {
if (info.requestTrace != null) {
Profiler.clearMethodCallParent();
}
}
public <T extends RequestTrace> RequestInformation<T> monitor(MonitoredRequest<T> monitoredRequest) throws Exception {
try {
monitorStart(monitoredRequest);
final RequestInformation<T> info = (RequestInformation<T>) request.get();
info.executionResult = monitoredRequest.execute();
return info;
} catch (Exception e) {
recordException(e);
throw e;
} finally {
monitorStop();
}
}
public void recordException(Exception e) throws Exception {
final RequestInformation<? extends RequestTrace> info = request.get();
if (info.requestTrace != null) {
info.requestTrace.setException(e);
}
}
private void trackOverhead(long overhead1, long overhead2) {
if (corePlugin.isInternalMonitoringActive()) {
overhead2 = System.nanoTime() - overhead2;
metricRegistry.timer("internal.overhead.RequestMonitor").update(overhead2 + overhead1, NANOSECONDS);
}
}
/*
* In case the instance name is not set by configuration, try to read from monitored execution
* (e.g. the domain name from a HTTP request)
*/
private synchronized void getInstanceNameFromExecution(MonitoredRequest<?> monitoredRequest) {
final MeasurementSession measurementSession = Stagemonitor.getMeasurementSession();
if (measurementSession.getInstanceName() == null) {
MeasurementSession session = new MeasurementSession(measurementSession.getApplicationName(), measurementSession.getHostName(),
monitoredRequest.getInstanceName());
Stagemonitor.setMeasurementSession(session);
}
}
private synchronized void createMeasurementSession() {
if (Stagemonitor.getMeasurementSession().isNull()) {
MeasurementSession session = new MeasurementSession(corePlugin.getApplicationName(), MeasurementSession.getNameOfLocalHost(),
corePlugin.getInstanceName());
Stagemonitor.setMeasurementSession(session);
}
}
private <T extends RequestTrace> void beforeExecution(MonitoredRequest<T> monitoredRequest, RequestInformation<T> info) {
info.requestTrace = monitoredRequest.createRequestTrace();
try {
if (info.profileThisRequest()) {
final CallStackElement root = Profiler.activateProfiling("total");
info.requestTrace.setCallStack(root);
}
} catch (RuntimeException e) {
logger.warn(e.getMessage() + " (this exception is ignored) " + info.toString(), e);
}
}
private <T extends RequestTrace> void detectForwardedRequest(RequestInformation<T> info) {
if (request.get() != null) {
// there is already an request set in this thread -> this execution must have been forwarded
info.parent = (RequestInformation<T>) request.get();
info.parent.child = info;
}
}
private <T extends RequestTrace> void monitorAfterExecution(MonitoredRequest<T> monitoredRequest, RequestInformation<T> info) {
final T requestTrace = info.requestTrace;
final long executionTime = System.nanoTime() - info.start;
final long cpuTime = getCpuTime() - info.startCpu;
requestTrace.setExecutionTime(NANOSECONDS.toMillis(executionTime));
requestTrace.setExecutionTimeCpu(NANOSECONDS.toMillis(cpuTime));
monitoredRequest.onPostExecute(info);
if (requestTrace.getCallStack() != null) {
Profiler.stop();
requestTrace.getCallStack().setSignature(requestTrace.getName());
reportRequestTrace(requestTrace);
}
trackMetrics(info, executionTime, cpuTime);
}
private <T extends RequestTrace> void removeTimerIfCountIsZero(RequestInformation<T> info) {
if (info.timerCreated) {
String timerMetricName = getTimerMetricName(info.getTimerName());
if (info.getRequestTimer().getCount() == 0 && metricRegistry.getMetrics().get(timerMetricName) != null) {
metricRegistry.remove(timerMetricName);
}
}
}
private <T extends RequestTrace> void trackMetrics(RequestInformation<T> info, long executionTime, long cpuTime) {
T requestTrace = info.requestTrace;
String timerName = info.getTimerName();
info.getRequestTimer().update(executionTime, NANOSECONDS);
metricRegistry.timer(getTimerMetricName("All")).update(executionTime, NANOSECONDS);
if (requestMonitorPlugin.isCollectCpuTime()) {
metricRegistry.timer(name(REQUEST, timerName, "server.cpu-time.total")).update(cpuTime, NANOSECONDS);
metricRegistry.timer("request.All.server.cpu-time.total").update(cpuTime, NANOSECONDS);
}
if (requestTrace.isError()) {
metricRegistry.meter(name(REQUEST, timerName, "server.meter.error")).mark();
metricRegistry.meter("request.All.server.meter.error").mark();
}
trackDbMetrics(timerName, requestTrace);
}
private <T extends RequestTrace> void trackDbMetrics(String timerName, T requestTrace) {
if (requestTrace.getExecutionCountDb() > 0) {
if (requestMonitorPlugin.isCollectDbTimePerRequest()) {
metricRegistry.timer(name(REQUEST, timerName, "server.time.db")).update(requestTrace.getExecutionTimeDb(), MILLISECONDS);
metricRegistry.timer(name("request.All.server.time.db")).update(requestTrace.getExecutionTimeDb(), MILLISECONDS);
}
metricRegistry.meter(name(REQUEST, timerName, "server.meter.db")).mark(requestTrace.getExecutionCountDb());
metricRegistry.meter("request.All.server.meter.db").mark(requestTrace.getExecutionCountDb());
}
}
private <T extends RequestTrace> String getTimerMetricName(String timerName) {
return name(REQUEST, timerName, "server.time.total");
}
private <T extends RequestTrace> void reportRequestTrace(final T requestTrace) {
try {
asyncRequestTraceReporterPool.submit(new Runnable() {
@Override
public void run() {
for (RequestTraceReporter requestTraceReporter : requestTraceReporters) {
if (requestTraceReporter.isActive()) {
try {
requestTraceReporter.reportRequestTrace(requestTrace);
} catch (Exception e) {
logger.warn(e.getMessage() + " (this exception is ignored)", e);
}
}
}
}
});
} catch (RejectedExecutionException e) {
logger.warn(e.getMessage() + " (this exception is ignored)", e);
}
}
public boolean isWarmedUp() {
if (!warmedUp.get()) {
warmedUp.set(warmupRequests < noOfRequests.incrementAndGet() && new Date(System.currentTimeMillis() + 1).after(endOfWarmup));
return warmedUp.get();
} else {
return true;
}
}
private long getCpuTime() {
return isCurrentThreadCpuTimeSupported ? threadMXBean.getCurrentThreadCpuTime() : 0L;
}
public class RequestInformation<T extends RequestTrace> {
private boolean timerCreated = false;
T requestTrace = null;
private long start = System.nanoTime();
private long startCpu = getCpuTime();
private Object executionResult = null;
private Future<?> startup;
private long overhead1;
private MonitoredRequest<T> monitoredRequest;
private boolean firstRequest;
private RequestInformation<T> parent;
private RequestInformation<T> child;
/**
* If the request has no name it means that it should not be monitored.
*
* @return <code>true</code>, if the request trace has a name, <code>false</code> otherwise
*/
private boolean hasRequestName() {
return requestTrace != null && requestTrace.getName() != null && !requestTrace.getName().isEmpty();
}
private boolean monitorThisRequest() {
if (!requestMonitorPlugin.isCollectRequestStats() || !isWarmedUp()) {
return false;
}
if (isForwarded() && isForwarding()) {
return false;
}
if (isForwarded()) {
return monitoredRequest.isMonitorForwardedExecutions();
}
if (isForwarding()) {
return !monitoredRequest.isMonitorForwardedExecutions();
}
return true;
}
public String getTimerName() {
return name(GraphiteSanitizer.sanitizeGraphiteMetricSegment(requestTrace.getName()));
}
/**
* Returns the request trace or <code>null</code>, if
* {@link org.stagemonitor.requestmonitor.RequestMonitor#isWarmedUp()} is <code>false</code>
*
* @return the request trace or <code>null</code>, if
* {@link org.stagemonitor.requestmonitor.RequestMonitor#isWarmedUp()} is <code>false</code>
*/
public T getRequestTrace() {
return requestTrace;
}
public Timer getRequestTimer() {
timerCreated = true;
return metricRegistry.timer(getTimerMetricName(getTimerName()));
}
private boolean profileThisRequest() {
if (!requestMonitorPlugin.isProfilerActive()) {
return false;
}
int callStackEveryXRequestsToGroup = requestMonitorPlugin.getCallStackEveryXRequestsToGroup();
if (callStackEveryXRequestsToGroup == 1) {
return true;
}
if (callStackEveryXRequestsToGroup < 1) {
return false;
}
Timer requestTimer = getRequestTimer();
if (requestTimer.getCount() == 0) {
return false;
}
return requestTimer.getCount() % callStackEveryXRequestsToGroup == 0;
}
/**
* A forwarding request is one that forwards a request to another execution.
* <p/>
* Examples:
* <p/>
* - web environment: request to /a makes a
* {@link javax.servlet.RequestDispatcher#forward(ServletRequest, ServletResponse)} to /b.
* /a is the forwarding execution, /b is the forwarded execution
* <p/>
* - plain method calls: monitored method a() calls monitored method b()
* (monitored means monitored by {@link RequestMonitor}).
* Method a() is the forwarding execution, Method b() is the forwarded execution.
*
* @return true, if this request is a forwarding request, false otherwise
*/
private boolean isForwarding() {
return child != null;
}
public Object getExecutionResult() {
return executionResult;
}
@Override
public String toString() {
return "RequestInformation{" +
"requestTrace=" + requestTrace +
", start=" + start +
", startCpu=" + startCpu +
", forwardedExecution=" + isForwarded() +
", executionResult=" + executionResult +
'}';
}
public boolean isForwarded() {
return parent != null;
}
}
/**
* @return the {@link RequestTrace} of the current request
*/
public static RequestTrace getRequest() {
final RequestInformation<? extends RequestTrace> requestInformation = request.get();
return requestInformation != null ? requestInformation.getRequestTrace() : null;
}
/**
* Adds a {@link RequestTraceReporter}
*
* @param requestTraceReporter the {@link RequestTraceReporter} to add
*/
public static void addRequestTraceReporter(RequestTraceReporter requestTraceReporter) {
requestTraceReporters.add(0, requestTraceReporter);
}
}
| RequestMonitor#recordException should not throw Exception
| stagemonitor-requestmonitor/src/main/java/org/stagemonitor/requestmonitor/RequestMonitor.java | RequestMonitor#recordException should not throw Exception | |
Java | apache-2.0 | 1ccb31d7f2538fa9cb69ebedd9cd042f8cfe1b76 | 0 | michael-rapp/AndroidPreferenceActivity | /*
* Copyright 2014 - 2017 Michael Rapp
*
* 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 de.mrapp.android.preference.activity.adapter;
import android.content.Context;
import android.database.DataSetObserver;
import android.preference.Preference;
import android.preference.PreferenceCategory;
import android.support.annotation.CallSuper;
import android.support.annotation.ColorInt;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.util.Pair;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import de.mrapp.android.preference.activity.R;
import static de.mrapp.android.util.Condition.ensureAtLeast;
import static de.mrapp.android.util.Condition.ensureNotNull;
/**
* A list adapter, which encapsulates another adapter in order to add items, which are
* visualized as dividers, above preference categories.
*
* @author Michael Rapp
* @since 5.0.0
*/
public class PreferenceGroupAdapter extends BaseAdapter {
/**
* The item, which represents a divider.
*/
private static final Object DIVIDER = new Object();
/**
* The context, which is used by the adapter.
*/
private final Context context;
/**
* The encapsulated adapter.
*/
private final ListAdapter encapsulatedAdapter;
/**
* The color of the divider's which are shown above preference categories.
*/
private int dividerColor;
/**
* Creates and returns a data set observer, which notifies the adapter, when the
* encapsulated adapter's data set has been changed or invalidated.
*
* @return The data set observer, which has been created, as an instance of the class {@link
* DataSetObserver}. The data set observer may not be null
*/
@NonNull
private DataSetObserver createDataSetObserver() {
return new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
PreferenceGroupAdapter.this.notifyDataSetChanged();
}
@Override
public void onInvalidated() {
super.onInvalidated();
PreferenceGroupAdapter.this.notifyDataSetInvalidated();
}
};
}
/**
* Adapts the background color of a divider.
*
* @param divider
* The divider, whose background color should be adapted, as an instance of the class
* {@link View}. The view may not be null
*/
private void adaptDividerColor(@NonNull final View divider) {
int color = dividerColor;
if (color == -1) {
color = ContextCompat.getColor(context, R.color.preference_divider_color_light);
}
divider.setBackgroundColor(color);
}
/**
* Returns the context, which is used by the adapter.
*
* @return The context, which is used by the adapter, as an instance of the class {@link
* Context}
*/
@NonNull
protected Context getContext() {
return context;
}
/**
* Returns the encapsulated adapter.
*
* @return The encapsulated adapter as an instance of the type {@link ListAdapter}. The adapter
* may not be nul
*/
@NonNull
protected ListAdapter getEncapsulatedAdapter() {
return encapsulatedAdapter;
}
/**
* The method, which is invoked, when a specific item is visualized. This method may be
* overridden by subclasses in order to modify the item beforehand.
*
* @param item
* The item, which is visualized, as an instance of the class {@link Object}. The item
* may not be null
*/
@CallSuper
protected void onVisualizeItem(@NonNull final Object item) {
if (item instanceof Preference) {
Preference preference = (Preference) item;
int currentLayout = preference.getLayoutResource();
String resourceName = context.getResources().getResourceName(currentLayout);
if (resourceName.startsWith("android:layout")) {
int layout = item instanceof PreferenceCategory ? R.layout.preference_category :
R.layout.preference;
preference.setLayoutResource(layout);
}
}
}
/**
* The method, which is invoked, when a specific item has been visualized. This method may be
* overridden by subclasses in order to adapt the appearance of the inflated view.
*
* @param item
* The item, which has been visualized, as an instance of the class {@link Object}. The
* item may not be null
* @param view
* The view, which has been inflated, as an instance of the class {@link View}. The view
* may not be null
*/
protected void onVisualizedItem(@NonNull final Object item, @NonNull final View view) {
}
/**
* Creates a new list adapter, which encapsulates another adapter in order to add items,
* which are visualized as dividers, above preference categories.
*
* @param context
* The context, which should be used by the adapter, as an instance of the class {@link
* Context}. The context may not be null
* @param encapsulatedAdapter
* The adapter, which should be encapsulated, as an instance of the type {@link
* ListAdapter}. The adapter may not be null
*/
public PreferenceGroupAdapter(@NonNull final Context context,
@NonNull final ListAdapter encapsulatedAdapter) {
ensureNotNull(context, "The context may not be null");
ensureNotNull(encapsulatedAdapter, "The encapsulated adapter may not be null");
this.context = context;
this.encapsulatedAdapter = encapsulatedAdapter;
encapsulatedAdapter.registerDataSetObserver(createDataSetObserver());
}
/**
* Returns a pair, which contains the item, which corresponds to the given position, as well
* as the item's position in the encapsulated adapter, if the item is not a divider.
*
* @param position
* The position of the item, which should be returned, as an {@link Integer} value
* @return A pair, which contains the item, which corresponds to the given position, as well as
* the item's position in the encapsulated adapter, if the item is not a divider, as an instance
* of the class Pair. The pair may not be null
*/
@NonNull
public final Pair<Object, Integer> getItemInternal(final int position) {
ensureAtLeast(position, 0, null, IndexOutOfBoundsException.class);
Object item = null;
int offset = 0;
int i = 0;
while (i <= position) {
item = encapsulatedAdapter.getItem(i - offset);
if (i > 0 && item instanceof PreferenceCategory) {
if (i == position) {
return Pair.create(DIVIDER, -1);
} else {
offset++;
i++;
}
}
i++;
}
ensureNotNull(item, null, IndexOutOfBoundsException.class);
return Pair.create(item, i - 1 - offset);
}
/**
* Sets the color of the dividers, which are shown above preference categories.
*
* @param color
* The color, which should be set, as an {@link Integer} value or -1, if the default
* color should be used
*/
public final void setDividerColor(@ColorInt final int color) {
this.dividerColor = color;
notifyDataSetChanged();
}
@Override
public final int getCount() {
int encapsulatedAdapterCount = encapsulatedAdapter.getCount();
int count = encapsulatedAdapterCount;
for (int i = 0; i < encapsulatedAdapterCount; i++) {
Object item = encapsulatedAdapter.getItem(i);
if (i > 0 && item instanceof PreferenceCategory) {
count++;
}
}
return count;
}
@Override
public final Object getItem(final int position) {
return getItemInternal(position).first;
}
@Override
public final long getItemId(final int position) {
return position;
}
@Override
public final boolean hasStableIds() {
return false;
}
@Override
public final View getView(final int position, final View convertView, final ViewGroup parent) {
Pair<Object, Integer> pair = getItemInternal(position);
onVisualizeItem(pair.first);
View view;
if (pair.first == DIVIDER) {
view = convertView;
if (view == null) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
view = layoutInflater.inflate(R.layout.preference_divider, parent, false);
}
adaptDividerColor(view);
} else if (pair.first instanceof PreferenceCategory &&
TextUtils.isEmpty(((PreferenceCategory) pair.first).getTitle())) {
view = new View(context);
} else {
view = encapsulatedAdapter.getView(pair.second, convertView, parent);
}
onVisualizedItem(pair.first, view);
return view;
}
@CallSuper
@Override
public boolean isEnabled(final int position) {
Pair<Object, Integer> pair = getItemInternal(position);
return pair.first != DIVIDER && encapsulatedAdapter.isEnabled(pair.second);
}
@Override
public final int getItemViewType(final int position) {
Pair<Object, Integer> pair = getItemInternal(position);
return pair.first == DIVIDER ? IGNORE_ITEM_VIEW_TYPE :
encapsulatedAdapter.getItemViewType(pair.second);
}
@Override
public final int getViewTypeCount() {
return encapsulatedAdapter.getViewTypeCount();
}
} | library/src/main/java/de/mrapp/android/preference/activity/adapter/PreferenceGroupAdapter.java | /*
* Copyright 2014 - 2017 Michael Rapp
*
* 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 de.mrapp.android.preference.activity.adapter;
import android.content.Context;
import android.database.DataSetObserver;
import android.preference.Preference;
import android.preference.PreferenceCategory;
import android.support.annotation.CallSuper;
import android.support.annotation.ColorInt;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.util.Pair;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import de.mrapp.android.preference.activity.R;
import static de.mrapp.android.util.Condition.ensureAtLeast;
import static de.mrapp.android.util.Condition.ensureNotNull;
/**
* A list adapter, which encapsulates another adapter in order to add items, which are
* visualized as dividers, above preference categories.
*
* @author Michael Rapp
* @since 5.0.0
*/
public class PreferenceGroupAdapter extends BaseAdapter {
/**
* The item, which represents a divider.
*/
private static final Object DIVIDER = new Object();
/**
* The context, which is used by the adapter.
*/
private final Context context;
/**
* The encapsulated adapter.
*/
private final ListAdapter encapsulatedAdapter;
/**
* The color of the divider's which are shown above preference categories.
*/
private int dividerColor;
/**
* Creates and returns a data set observer, which notifies the adapter, when the
* encapsulated adapter's data set has been changed or invalidated.
*
* @return The data set observer, which has been created, as an instance of the class {@link
* DataSetObserver}. The data set observer may not be null
*/
@NonNull
private DataSetObserver createDataSetObserver() {
return new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
PreferenceGroupAdapter.this.notifyDataSetChanged();
}
@Override
public void onInvalidated() {
super.onInvalidated();
PreferenceGroupAdapter.this.notifyDataSetInvalidated();
}
};
}
/**
* Adapts the background color of a divider.
*
* @param divider
* The divider, whose background color should be adapted, as an instance of the class
* {@link View}. The view may not be null
*/
private void adaptDividerColor(@NonNull final View divider) {
int color = dividerColor;
if (color == -1) {
color = ContextCompat.getColor(context, R.color.preference_divider_color_light);
}
divider.setBackgroundColor(color);
}
/**
* Returns the context, which is used by the adapter.
*
* @return The context, which is used by the adapter, as an instance of the class {@link
* Context}
*/
@NonNull
protected Context getContext() {
return context;
}
/**
* Returns the encapsulated adapter.
*
* @return The encapsulated adapter as an instance of the type {@link ListAdapter}. The adapter
* may not be nul
*/
@NonNull
protected ListAdapter getEncapsulatedAdapter() {
return encapsulatedAdapter;
}
/**
* The method, which is invoked, when a specific item is visualized. This method may be
* overridden by subclasses in order to modify the item beforehand.
*
* @param item
* The item, which is visualized, as an instance of the class {@link Object}. The item
* may not be null
*/
@CallSuper
protected void onVisualizeItem(@NonNull final Object item) {
if (item instanceof Preference) {
Preference preference = (Preference) item;
int currentLayout = preference.getLayoutResource();
String resourceName = context.getResources().getResourceName(currentLayout);
if (resourceName.startsWith("android:layout")) {
int layout = item instanceof PreferenceCategory ? R.layout.preference_category :
R.layout.preference;
preference.setLayoutResource(layout);
}
}
}
/**
* The method, which is invoked, when a specific item has been visualized. This method may be
* overridden by subclasses in order to adapt the appearance of the inflated view.
*
* @param item
* The item, which has been visualized, as an instance of the class {@link Object}. The
* item may not be null
* @param view
* The view, which has been inflated, as an instance of the class {@link View}. The view
* may not be null
*/
protected void onVisualizedItem(@NonNull final Object item, @NonNull final View view) {
}
/**
* Creates a new list adapter, which encapsulates another adapter in order to add items,
* which are visualized as dividers, above preference categories.
*
* @param context
* The context, which should be used by the adapter, as an instance of the class {@link
* Context}. The context may not be null
* @param encapsulatedAdapter
* The adapter, which should be encapsulated, as an instance of the type {@link
* ListAdapter}. The adapter may not be null
*/
public PreferenceGroupAdapter(@NonNull final Context context,
@NonNull final ListAdapter encapsulatedAdapter) {
ensureNotNull(context, "The context may not be null");
ensureNotNull(encapsulatedAdapter, "The encapsulated adapter may not be null");
this.context = context;
this.encapsulatedAdapter = encapsulatedAdapter;
encapsulatedAdapter.registerDataSetObserver(createDataSetObserver());
}
/**
* Returns a pair, which contains the item, which corresponds to the given position, as well
* as the item's position in the encapsulated adapter, if the item is not a divider.
*
* @param position
* The position of the item, which should be returned, as an {@link Integer} value
* @return A pair, which contains the item, which corresponds to the given position, as well as
* the item's position in the encapsulated adapter, if the item is not a divider, as an instance
* of the class Pair. The pair may not be null
*/
@NonNull
public final Pair<Object, Integer> getItemInternal(final int position) {
if (position == 0) {
System.out.println("gotcha");
}
ensureAtLeast(position, 0, null, IndexOutOfBoundsException.class);
Object item = null;
int offset = 0;
int i = 0;
while (i <= position) {
item = encapsulatedAdapter.getItem(i - offset);
if (i > 0 && item instanceof PreferenceCategory) {
if (i == position) {
return Pair.create(DIVIDER, -1);
} else {
offset++;
i++;
}
}
i++;
}
ensureNotNull(item, null, IndexOutOfBoundsException.class);
return Pair.create(item, i - 1 - offset);
}
/**
* Sets the color of the dividers, which are shown above preference categories.
*
* @param color
* The color, which should be set, as an {@link Integer} value or -1, if the default
* color should be used
*/
public final void setDividerColor(@ColorInt final int color) {
this.dividerColor = color;
notifyDataSetChanged();
}
@Override
public final int getCount() {
int encapsulatedAdapterCount = encapsulatedAdapter.getCount();
int count = encapsulatedAdapterCount;
for (int i = 0; i < encapsulatedAdapterCount; i++) {
Object item = encapsulatedAdapter.getItem(i);
if (i > 0 && item instanceof PreferenceCategory) {
count++;
}
}
return count;
}
@Override
public final Object getItem(final int position) {
return getItemInternal(position).first;
}
@Override
public final long getItemId(final int position) {
return position;
}
@Override
public final boolean hasStableIds() {
return false;
}
@Override
public final View getView(final int position, final View convertView, final ViewGroup parent) {
Pair<Object, Integer> pair = getItemInternal(position);
onVisualizeItem(pair.first);
View view;
if (pair.first == DIVIDER) {
view = convertView;
if (view == null) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
view = layoutInflater.inflate(R.layout.preference_divider, parent, false);
}
adaptDividerColor(view);
} else if (pair.first instanceof PreferenceCategory &&
TextUtils.isEmpty(((PreferenceCategory) pair.first).getTitle())) {
view = new View(context);
} else {
view = encapsulatedAdapter.getView(pair.second, convertView, parent);
}
onVisualizedItem(pair.first, view);
return view;
}
@CallSuper
@Override
public boolean isEnabled(final int position) {
Pair<Object, Integer> pair = getItemInternal(position);
return pair.first != DIVIDER && encapsulatedAdapter.isEnabled(pair.second);
}
@Override
public final int getItemViewType(final int position) {
Pair<Object, Integer> pair = getItemInternal(position);
return pair.first == DIVIDER ? IGNORE_ITEM_VIEW_TYPE :
encapsulatedAdapter.getItemViewType(pair.second);
}
@Override
public final int getViewTypeCount() {
return encapsulatedAdapter.getViewTypeCount();
}
} | Remove debug statement.
| library/src/main/java/de/mrapp/android/preference/activity/adapter/PreferenceGroupAdapter.java | Remove debug statement. | |
Java | apache-2.0 | e913dd4effb993d097942522ed52e210acec2a23 | 0 | apache/logging-log4j2,apache/logging-log4j2,jinxuan/logging-log4j2,lqbweb/logging-log4j2,lqbweb/logging-log4j2,lburgazzoli/logging-log4j2,pisfly/logging-log4j2,xnslong/logging-log4j2,GFriedrich/logging-log4j2,lqbweb/logging-log4j2,lburgazzoli/apache-logging-log4j2,codescale/logging-log4j2,MagicWiz/log4j2,apache/logging-log4j2,pisfly/logging-log4j2,lburgazzoli/apache-logging-log4j2,lburgazzoli/apache-logging-log4j2,ChetnaChaudhari/logging-log4j2,neuro-sys/logging-log4j2,jsnikhil/nj-logging-log4j2,lburgazzoli/logging-log4j2,ChetnaChaudhari/logging-log4j2,xnslong/logging-log4j2,renchunxiao/logging-log4j2,codescale/logging-log4j2,GFriedrich/logging-log4j2,codescale/logging-log4j2,renchunxiao/logging-log4j2,GFriedrich/logging-log4j2,jinxuan/logging-log4j2,jsnikhil/nj-logging-log4j2,lburgazzoli/logging-log4j2,xnslong/logging-log4j2,neuro-sys/logging-log4j2,MagicWiz/log4j2 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.logging.log4j.core.appender.db.jdbc;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttr;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.core.helpers.NameUtil;
import org.apache.logging.log4j.core.helpers.Strings;
import org.apache.logging.log4j.status.StatusLogger;
/**
* A {@link JDBCAppender} connection source that uses a standard JDBC URL, username, and password to connect to the
* database.
*/
@Plugin(name = "DriverManager", category = "Core", elementType = "connectionSource", printObject = true)
public final class DriverManagerConnectionSource implements ConnectionSource {
private static final Logger LOGGER = StatusLogger.getLogger();
private final String databasePassword;
private final String databaseUrl;
private final String databaseUsername;
private final String description;
private DriverManagerConnectionSource(final String databaseUrl, final String databaseUsername,
final String databasePassword) {
this.databaseUrl = databaseUrl;
this.databaseUsername = databaseUsername;
this.databasePassword = databasePassword;
this.description = "driverManager{ url=" + this.databaseUrl + ", username=" + this.databaseUsername
+ ", passwordHash=" + NameUtil.md5(this.databasePassword + this.getClass().getName()) + " }";
}
@Override
public Connection getConnection() throws SQLException {
if (this.databaseUsername == null) {
return DriverManager.getConnection(this.databaseUrl);
}
return DriverManager.getConnection(this.databaseUrl, this.databaseUsername, this.databasePassword);
}
@Override
public String toString() {
return this.description;
}
/**
* Factory method for creating a connection source within the plugin manager.
*
* @param url The JDBC URL to use to connect to the logging database. A driver that can accept this URL must be on
* the classpath.
* @param username The username with which to log in to the database, if applicable.
* @param password The password with which to log in to the database, if applicable.
* @return the created connection source.
*/
@PluginFactory
public static DriverManagerConnectionSource createConnectionSource(@PluginAttr("url") final String url,
@PluginAttr("username") String username,
@PluginAttr("password") String password) {
if (Strings.isEmpty(url)) {
LOGGER.error("No JDBC URL specified for the database.", url);
return null;
}
Driver driver;
try {
driver = DriverManager.getDriver(url);
} catch (final SQLException e) {
LOGGER.error("No matching driver found for database URL [" + url + "].", e);
return null;
}
if (driver == null) {
LOGGER.error("No matching driver found for database URL [" + url + "].");
return null;
}
if (username == null || username.trim().length() == 0) {
username = null;
password = null;
}
return new DriverManagerConnectionSource(url, username, password);
}
}
| core/src/main/java/org/apache/logging/log4j/core/appender/db/jdbc/DriverManagerConnectionSource.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.logging.log4j.core.appender.db.jdbc;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttr;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.core.helpers.NameUtil;
import org.apache.logging.log4j.core.helpers.Strings;
import org.apache.logging.log4j.status.StatusLogger;
/**
* A {@link JDBCAppender} connection source that uses a standard JDBC URL, username, and password to connect to the
* database.
*/
@Plugin(name = "DriverManager", category = "Core", elementType = "connectionSource", printObject = true)
public final class DriverManagerConnectionSource implements ConnectionSource {
private static final Logger LOGGER = StatusLogger.getLogger();
private final String databasePassword;
private final String databaseUrl;
private final String databaseUsername;
private final String description;
private DriverManagerConnectionSource(final String databaseUrl, final String databaseUsername,
final String databasePassword) {
this.databaseUrl = databaseUrl;
this.databaseUsername = databaseUsername;
this.databasePassword = databasePassword;
this.description = "driverManager{ url=" + this.databaseUrl + ", username=" + this.databaseUsername
+ ", passwordHash=" + NameUtil.md5(this.databasePassword + this.getClass().getName()) + " }";
}
@Override
public Connection getConnection() throws SQLException {
if (this.databaseUsername == null) {
return DriverManager.getConnection(this.databaseUrl);
}
return DriverManager.getConnection(this.databaseUrl, this.databaseUsername, this.databasePassword);
}
@Override
public String toString() {
return this.description;
}
/**
* Factory method for creating a connection source within the plugin manager.
*
* @param url The JDBC URL to use to connect to the logging database. A driver that can accept this URL must be on
* the classpath.
* @param username The username with which to log in to the database, if applicable.
* @param password The password with which to log in to the database, if applicable.
* @return the created connection source.
*/
@PluginFactory
public static DriverManagerConnectionSource createConnectionSource(@PluginAttr("url") final String url,
@PluginAttr("username") String username,
@PluginAttr("password") String password) {
if (url == null || url.length() == 0) {
LOGGER.error("No JDBC URL specified for the database.", url);
return null;
}
Driver driver;
try {
driver = DriverManager.getDriver(url);
} catch (final SQLException e) {
LOGGER.error("No matching driver found for database URL [" + url + "].", e);
return null;
}
if (driver == null) {
LOGGER.error("No matching driver found for database URL [" + url + "].");
return null;
}
if (username == null || username.trim().length() == 0) {
username = null;
password = null;
}
return new DriverManagerConnectionSource(url, username, password);
}
}
| Refactor String pattern 'foo == null || foo.length() == 0' into a new helper API Strings.isEmpty(CharSequence) copied from Apache Commons Lang.
git-svn-id: de5ce936019686f47409c93bcc5e202a9739563b@1501221 13f79535-47bb-0310-9956-ffa450edef68
| core/src/main/java/org/apache/logging/log4j/core/appender/db/jdbc/DriverManagerConnectionSource.java | Refactor String pattern 'foo == null || foo.length() == 0' into a new helper API Strings.isEmpty(CharSequence) copied from Apache Commons Lang. | |
Java | apache-2.0 | 9e008809c12b27909e8268d4fa5790696c63a9e8 | 0 | hs-jenkins-bot/Singularity,HubSpot/Singularity,hs-jenkins-bot/Singularity,HubSpot/Singularity,HubSpot/Singularity,hs-jenkins-bot/Singularity,hs-jenkins-bot/Singularity,HubSpot/Singularity,HubSpot/Singularity,hs-jenkins-bot/Singularity | package com.hubspot.singularity.helpers;
import com.google.inject.Inject;
import com.hubspot.singularity.SingularityManagedScheduledExecutorServiceFactory;
import com.hubspot.singularity.SingularityManagedThreadPoolFactory;
import com.hubspot.singularity.SingularityPendingTaskId;
import com.hubspot.singularity.config.SingularityConfiguration;
import com.hubspot.singularity.data.TaskManager;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
public class TaskLagGuardrail {
private final TaskManager taskManager;
private final SingularityConfiguration configuration;
private final ScheduledExecutorService executor;
private ConcurrentMap<String, Integer> lateTasksByRequestId;
@Inject
public TaskLagGuardrail(
SingularityConfiguration configuration,
SingularityManagedScheduledExecutorServiceFactory factory,
TaskManager taskManager
) {
this.configuration = configuration;
this.taskManager = taskManager;
this.lateTasksByRequestId = new ConcurrentHashMap<>();
this.executor = factory.getSingleThreaded(getClass().getSimpleName());
executor.scheduleWithFixedDelay(
this::updateLateTasksByRequestId,
0,
configuration.getRequestCacheTtl(),
TimeUnit.SECONDS
);
}
public boolean isLagged(String requestId) {
return lateTasksByRequestId.containsKey(requestId);
}
private void updateLateTasksByRequestId() {
long now = System.currentTimeMillis();
List<SingularityPendingTaskId> allPendingTaskIds = taskManager.getPendingTaskIds();
// not a thread safe assignment, but should be fine for periodic updates
this.lateTasksByRequestId =
allPendingTaskIds
.stream()
.filter(
p ->
now - p.getNextRunAt() > configuration.getDeltaAfterWhichTasksAreLateMillis()
)
.collect(
Collectors.toConcurrentMap(
SingularityPendingTaskId::getRequestId,
p -> 1,
Integer::sum
)
);
}
}
| SingularityService/src/main/java/com/hubspot/singularity/helpers/TaskLagGuardrail.java | package com.hubspot.singularity.helpers;
import com.google.inject.Inject;
import com.hubspot.singularity.SingularityPendingTaskId;
import com.hubspot.singularity.config.SingularityConfiguration;
import com.hubspot.singularity.data.TaskManager;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
public class TaskLagGuardrail {
private final TaskManager taskManager;
private final SingularityConfiguration configuration;
private ConcurrentMap<String, Integer> lateTasksByRequestId;
private long lastUpdate;
@Inject
public TaskLagGuardrail(
SingularityConfiguration configuration,
TaskManager taskManager
) {
this.configuration = configuration;
this.taskManager = taskManager;
this.lateTasksByRequestId = new ConcurrentHashMap<>();
this.lastUpdate = 0;
}
public boolean isLagged(String requestId) {
updateLateTasksByRequestId();
return lateTasksByRequestId.containsKey(requestId);
}
private void updateLateTasksByRequestId() {
long now = System.currentTimeMillis();
if (now - lastUpdate > 1000L * configuration.getRequestCacheTtl()) {
List<SingularityPendingTaskId> allPendingTaskIds = taskManager.getPendingTaskIds();
this.lateTasksByRequestId =
allPendingTaskIds
.stream()
.filter(
p ->
now -
p.getNextRunAt() >
configuration.getDeltaAfterWhichTasksAreLateMillis()
)
.collect(
Collectors.toConcurrentMap(
SingularityPendingTaskId::getRequestId,
p -> 1,
Integer::sum
)
);
this.lastUpdate = System.currentTimeMillis();
}
}
}
| scheduled executor for updating requests with task lag
| SingularityService/src/main/java/com/hubspot/singularity/helpers/TaskLagGuardrail.java | scheduled executor for updating requests with task lag | |
Java | apache-2.0 | 42b92565e4bc31c80d0ab1f4e33f47d2856aa0a8 | 0 | roywant/uribeacon,don/uribeacon,roywant/uribeacon,perja12/uribeacon,dinhviethoa/uribeacon,kstechnologies/uribeacon,perja12/uribeacon,dennisg/uribeacon,dennisg/uribeacon,kstechnologies/uribeacon,kstechnologies/uribeacon,roywant/uribeacon,dennisg/uribeacon,tommythorsen/uribeacon,kstechnologies/uribeacon,don/uribeacon,dinhviethoa/uribeacon,dennisg/uribeacon,perja12/uribeacon,don/uribeacon,dinhviethoa/uribeacon,don/uribeacon,dennisg/uribeacon,dinhviethoa/uribeacon,tommythorsen/uribeacon,roywant/uribeacon,tommythorsen/uribeacon,dennisg/uribeacon,perja12/uribeacon,perja12/uribeacon,dinhviethoa/uribeacon,kstechnologies/uribeacon,tommythorsen/uribeacon,dinhviethoa/uribeacon,tommythorsen/uribeacon,roywant/uribeacon,perja12/uribeacon,don/uribeacon,tommythorsen/uribeacon,roywant/uribeacon,kstechnologies/uribeacon,don/uribeacon | /*
* Copyright 2015 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.uribeacon.validator;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spanned;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ShareActionProvider;
import android.widget.Toast;
import org.uribeacon.validator.TestRunner.DataCallback;
import java.util.ArrayList;
import java.util.Arrays;
public class TestActivity extends Activity {
private static final String TAG = TestActivity.class.getCanonicalName();
private TestRunner mTestRunner;
private final DataCallback mDataCallback = new DataCallback() {
ProgressDialog progress;
@Override
public void dataUpdated() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (progress != null) {
progress.dismiss();
}
mAdapter.notifyDataSetChanged();
setShareIntent();
}
});
}
@Override
public void waitingForConfigMode() {
runOnUiThread(new Runnable() {
@Override
public void run() {
progress = new ProgressDialog(TestActivity.this);
progress.setMessage(getString(R.string.put_beacon_in_config_mode));
progress.show();
progress.setCanceledOnTouchOutside(false);
progress.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
mTestRunner.stop();
}
});
}
});
}
@Override
public void connectedToBeacon() {
progress.dismiss();
}
@Override
public void testsCompleted(final boolean failed) {
runOnUiThread(new Runnable() {
@Override
public void run() {
int message;
if (failed) {
message = R.string.test_failed;
} else {
message = R.string.test_success;
}
Toast.makeText(TestActivity.this, message, Toast.LENGTH_SHORT).show();
}
});
}
};
private RecyclerView.Adapter mAdapter;
private ShareActionProvider mShareActionProvider;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
boolean optionalImplemented = getIntent().getBooleanExtra(MainActivity.LOCK_IMPLEMENTED, false);
String testType = getIntent().getStringExtra(MainActivity.TEST_TYPE);
mTestRunner = new TestRunner(this, mDataCallback, testType, optionalImplemented);
ArrayList<TestHelper> mUriBeaconTests = mTestRunner.getUriBeaconTests();
RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView_tests);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new TestsAdapter(mUriBeaconTests);
mRecyclerView.setAdapter(mAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.tests_activity_actions, menu);
MenuItem item = menu.findItem(R.id.menu_item_share);
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
setShareIntent();
return true;
}
private void setShareIntent() {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("message/rfc822");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "UriBeacon Test Results");
Spanned body = createTestResults();
shareIntent.putExtra(Intent.EXTRA_TEXT, body);
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareIntent);
}
}
private Spanned createTestResults() {
String results = "<h1>UriBeacon Results</h1>\n";
for (TestHelper test : mTestRunner.getUriBeaconTests()) {
results += "<h3>" + test.getName() + "</h3>";
results += "<p>Status: ";
if (!test.isStarted()) {
results += "Didn't run</p>";
} else if (!test.isFinished()) {
results += "Running</p>";
} else if (!test.isFailed()) {
results += "<font color=\"#4CAF50\">Success</font></p>";
} else {
results += "<font color=\"#F44336\">Failed</font></p>";
results += getReasonTestFailed(test);
}
}
return Html.fromHtml(results);
}
private String getReasonTestFailed(TestHelper test) {
String steps = "<h6>Steps:</h6>";
for (int i = 0; i < test.getTestSteps().size(); i++) {
TestAction action = test.getTestSteps().get(i);
if (action.actionType == TestAction.LAST) {
continue;
}
steps += "<p>" + (i + 1) + ". ";
if (action.failed) {
steps += "<font color=\"#F44336\">";
}
switch (action.actionType) {
case TestAction.CONNECT:
steps += "Connect";
break;
case TestAction.WRITE:
steps += "Write: " + Arrays.toString(action.transmittedValue);
break;
case TestAction.ASSERT:
steps += "Assert: " + Arrays.toString(action.transmittedValue);
break;
case TestAction.DISCONNECT:
steps += "Disconnect</p>";
break;
case TestAction.ADV_FLAGS:
steps += "Read Adv Flags: " + Arrays.toString(action.transmittedValue);
break;
case TestAction.ADV_TX_POWER:
steps += "Read Adv Tx Power: " + Arrays.toString(action.transmittedValue);
break;
case TestAction.ADV_URI:
steps += "Read Adv URI: " + Arrays.toString(action.transmittedValue);
break;
case TestAction.ADV_PACKET:
steps += "Scan Adv Packet";
break;
}
if (action.failed) {
steps += "</font></p><p><font color=\"#F44336\">Reason: " + action.reason + "</font></p>";
} else {
steps += "</p>";
}
}
return steps;
}
@Override
protected void onResume() {
super.onResume();
mTestRunner.start(null, null);
}
@Override
protected void onDestroy() {
super.onDestroy();
mTestRunner.stop();
}
}
| android-uribeacon/uribeacon-validator/src/main/java/org/uribeacon/validator/TestActivity.java | /*
* Copyright 2015 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.uribeacon.validator;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ShareActionProvider;
import android.widget.Toast;
import org.uribeacon.validator.TestRunner.DataCallback;
import java.util.ArrayList;
import java.util.Arrays;
public class TestActivity extends Activity {
private static final String TAG = TestActivity.class.getCanonicalName();
private TestRunner mTestRunner;
private final DataCallback mDataCallback = new DataCallback() {
ProgressDialog progress;
@Override
public void dataUpdated() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (progress != null) {
progress.dismiss();
}
mAdapter.notifyDataSetChanged();
setShareIntent();
}
});
}
@Override
public void waitingForConfigMode() {
runOnUiThread(new Runnable() {
@Override
public void run() {
progress = new ProgressDialog(TestActivity.this);
progress.setMessage(getString(R.string.put_beacon_in_config_mode));
progress.show();
progress.setCanceledOnTouchOutside(false);
progress.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
mTestRunner.stop();
}
});
}
});
}
@Override
public void connectedToBeacon() {
progress.dismiss();
}
@Override
public void testsCompleted(final boolean failed) {
runOnUiThread(new Runnable() {
@Override
public void run() {
int message;
if (failed) {
message = R.string.test_failed;
} else {
message = R.string.test_success;
}
Toast.makeText(TestActivity.this, message, Toast.LENGTH_SHORT).show();
}
});
}
};
private RecyclerView.Adapter mAdapter;
private ShareActionProvider mShareActionProvider;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
boolean optionalImplemented = getIntent().getBooleanExtra(MainActivity.LOCK_IMPLEMENTED, false);
String testType = getIntent().getStringExtra(MainActivity.TEST_TYPE);
mTestRunner = new TestRunner(this, mDataCallback, testType, optionalImplemented);
ArrayList<TestHelper> mUriBeaconTests = mTestRunner.getUriBeaconTests();
RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView_tests);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new TestsAdapter(mUriBeaconTests);
mRecyclerView.setAdapter(mAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.tests_activity_actions, menu);
MenuItem item = menu.findItem(R.id.menu_item_share);
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
Log.d(TAG, "INTENT INTENT");
setShareIntent();
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "OPTIONS SELECTED");
setShareIntent();
return super.onOptionsItemSelected(item);
}
private void setShareIntent() {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("message/rfc822");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "UriBeacon Test Results");
Spanned body = createTestResults();
shareIntent.putExtra(Intent.EXTRA_TEXT, body);
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareIntent);
}
}
private Spanned createTestResults() {
String results = "<h1>UriBeacon Results</h1>\n";
for (TestHelper test : mTestRunner.getUriBeaconTests()) {
results += "<h3>" + test.getName() + "</h3>";
results += "<p>Status: ";
if (!test.isStarted()) {
results += "Didn't run</p>";
} else if (!test.isFinished()) {
results += "Running</p>";
} else if (!test.isFailed()) {
results += "<font color=\"#4CAF50\">Success</font></p>";
} else {
results += "<font color=\"#F44336\">Failed</font></p>";
results += getReasonTestFailed(test);
}
}
return Html.fromHtml(results);
}
private String getReasonTestFailed(TestHelper test) {
String steps = "<h6>Steps:</h6>";
for (int i = 0; i < test.getTestSteps().size(); i++) {
TestAction action = test.getTestSteps().get(i);
if (action.actionType == TestAction.LAST) {
continue;
}
steps += "<p>" + (i + 1) + ". ";
if (action.failed) {
steps += "<font color=\"#F44336\">";
}
switch (action.actionType) {
case TestAction.CONNECT:
steps += "Connect";
break;
case TestAction.WRITE:
steps += "Write: " + Arrays.toString(action.transmittedValue);
break;
case TestAction.ASSERT:
steps += "Assert: " + Arrays.toString(action.transmittedValue);
break;
case TestAction.DISCONNECT:
steps += "Disconnect</p>";
break;
case TestAction.ADV_FLAGS:
steps += "Read Adv Flags: " + Arrays.toString(action.transmittedValue);
break;
case TestAction.ADV_TX_POWER:
steps += "Read Adv Tx Power: " + Arrays.toString(action.transmittedValue);
break;
case TestAction.ADV_URI:
steps += "Read Adv URI: " + Arrays.toString(action.transmittedValue);
break;
case TestAction.ADV_PACKET:
steps += "Scan Adv Packet";
break;
}
if (action.failed) {
steps += "</font></p><p><font color=\"#F44336\">Reason: " + action.reason + "</font></p>";
} else {
steps += "</p>";
}
}
return steps;
}
@Override
protected void onResume() {
super.onResume();
mTestRunner.start(null, null);
}
@Override
protected void onDestroy() {
super.onDestroy();
mTestRunner.stop();
}
}
| Removed debug statements
| android-uribeacon/uribeacon-validator/src/main/java/org/uribeacon/validator/TestActivity.java | Removed debug statements | |
Java | apache-2.0 | 59a66f3e9a2bac6a1cc8749fec93f3e8fc20e045 | 0 | arnost-starosta/midpoint,arnost-starosta/midpoint,arnost-starosta/midpoint,arnost-starosta/midpoint,arnost-starosta/midpoint | /*
* Copyright (c) 2010-2018 Evolveum et al.
*
* 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.evolveum.midpoint.web.page.admin.cases;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.function.Function;
import javax.xml.datatype.XMLGregorianCalendar;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder;
import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import com.evolveum.midpoint.gui.api.page.PageBase;
import com.evolveum.midpoint.gui.api.util.WebComponentUtil;
import com.evolveum.midpoint.model.api.ModelAuthorizationAction;
import com.evolveum.midpoint.prism.PrismConstants;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.prism.query.builder.QueryBuilder;
import com.evolveum.midpoint.prism.query.builder.S_FilterEntryOrEmpty;
import com.evolveum.midpoint.schema.util.ObjectTypeUtil;
import com.evolveum.midpoint.util.exception.CommunicationException;
import com.evolveum.midpoint.util.exception.ConfigurationException;
import com.evolveum.midpoint.util.exception.ExpressionEvaluationException;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SecurityViolationException;
import com.evolveum.midpoint.util.exception.SystemException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.web.component.AjaxButton;
import com.evolveum.midpoint.web.component.DateLabelComponent;
import com.evolveum.midpoint.web.component.data.BoxedTablePanel;
import com.evolveum.midpoint.web.component.data.Table;
import com.evolveum.midpoint.web.component.data.column.IsolatedCheckBoxPanel;
import com.evolveum.midpoint.web.component.data.column.LinkColumn;
import com.evolveum.midpoint.web.component.form.multivalue.MultiValueChoosePanel;
import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour;
import com.evolveum.midpoint.web.page.admin.cases.dto.CaseWorkItemDto;
import com.evolveum.midpoint.web.page.admin.cases.dto.CaseWorkItemDtoProvider;
import com.evolveum.midpoint.web.page.admin.cases.dto.SearchingUtils;
import com.evolveum.midpoint.web.page.admin.dto.ObjectViewDto;
import com.evolveum.midpoint.web.page.admin.reports.component.SingleValueChoosePanel;
import com.evolveum.midpoint.web.security.SecurityUtils;
import com.evolveum.midpoint.web.session.UserProfileStorage;
import com.evolveum.midpoint.web.util.TooltipBehavior;
import com.evolveum.midpoint.wf.util.QueryUtils;
import com.evolveum.midpoint.xml.ns._public.common.common_3.CaseType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.CaseWorkItemType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.OtherPrivilegesLimitationType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;
/**
* @author bpowers
*/
public abstract class PageCaseWorkItems extends PageAdminCaseWorkItems {
private static final long serialVersionUID = 1L;
private static final Trace LOGGER = TraceManager.getTrace(PageCaseWorkItems.class);
private static final String DOT_CLASS = PageCaseWorkItems.class.getName() + ".";
private static final String PARAMETER_CASE_ID = "caseId";
private static final String PARAMETER_CASE_WORK_ITEM_ID = "caseWorkItemId";
// Search Form
private static final String ID_SEARCH_FILTER_FORM = "searchFilterForm";
private static final String ID_SEARCH_FILTER_RESOURCE = "filterResource";
private static final String ID_SEARCH_FILTER_ASSIGNEE_CONTAINER = "filterAssigneeContainer";
private static final String ID_SEARCH_FILTER_ASSIGNEE = "filterAssignee";
private static final String ID_SEARCH_FILTER_INCLUDE_CLOSED_CASES = "filterIncludeClosedCases";
// Data Table
private static final String ID_CASE_WORK_ITEMS_TABLE = "caseWorkItemsTable";
private static final String ID_BUTTON_BAR = "buttonBar";
// Buttons
private static final String ID_CREATE_CASE_BUTTON = "createCaseButton";
private boolean all;
public PageCaseWorkItems(boolean all) {
this.all = all;
initLayout();
}
//region Data
private CaseWorkItemDtoProvider createProvider() {
CaseWorkItemDtoProvider provider = new CaseWorkItemDtoProvider(PageCaseWorkItems.this);
try {
provider.setQuery(createQuery());
} catch (SchemaException | ObjectNotFoundException | ExpressionEvaluationException | CommunicationException
| ConfigurationException | SecurityViolationException e) {
// TODO handle more cleanly
throw new SystemException("Couldn't create case work item query", e);
}
provider.setSort(SearchingUtils.WORK_ITEM_DEADLINE, SortOrder.ASCENDING);// default sorting
return provider;
}
private ObjectQuery createQuery() throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, SecurityViolationException {
ObjectQuery query;
boolean authorizedToSeeAll = isAuthorized(ModelAuthorizationAction.READ_ALL_WORK_ITEMS.getUrl());
S_FilterEntryOrEmpty q = QueryBuilder.queryFor(CaseWorkItemType.class, getPrismContext());
// S_AtomicFilterExit query = queryStart.asc(PrismConstants.T_PARENT, CaseType.F_METADATA, MetadataType.F_CREATE_TIMESTAMP).;
if (all && authorizedToSeeAll) {
query = q.build();
} else {
// not authorized to see all => sees only allocated to him (not quite what is expected, but sufficient for the time being)
query = QueryUtils.filterForAssignees(q, SecurityUtils.getPrincipalUser(),
OtherPrivilegesLimitationType.F_APPROVAL_WORK_ITEMS)
.and().item(CaseWorkItemType.F_CLOSE_TIMESTAMP).isNull().build();
}
IsolatedCheckBoxPanel includeClosedCases = (IsolatedCheckBoxPanel) getCaseWorkItemsSearchField(ID_SEARCH_FILTER_INCLUDE_CLOSED_CASES);
if (includeClosedCases == null || !includeClosedCases.getValue()) {
query.addFilter(
QueryBuilder.queryFor(CaseWorkItemType.class, getPrismContext())
.item(PrismConstants.T_PARENT, CaseType.F_STATE).eq("open").build().getFilter()
);
}
// Resource Filter
SingleValueChoosePanel<ObjectReferenceType, ObjectType> resourceChoice = (SingleValueChoosePanel) getCaseWorkItemsSearchField(ID_SEARCH_FILTER_RESOURCE);
if (resourceChoice != null) {
List<ObjectType> resources = resourceChoice.getModelObject();
if (resources != null && resources.size() > 0) {
ObjectType resource = resources.get(0);
if (resource != null) {
query.addFilter(
QueryBuilder.queryFor(CaseWorkItemType.class, getPrismContext())
.item(PrismConstants.T_PARENT, CaseType.F_OBJECT_REF).ref(ObjectTypeUtil.createObjectRef(resource).asReferenceValue()).buildFilter()
);
}
}
}
// Assignee Filter
SingleValueChoosePanel<ObjectReferenceType, ObjectType> assigneeChoice = (SingleValueChoosePanel) getCaseWorkItemsSearchField(createComponentPath(ID_SEARCH_FILTER_ASSIGNEE_CONTAINER, ID_SEARCH_FILTER_ASSIGNEE));
if (assigneeChoice != null) {
List<ObjectType> assignees = assigneeChoice.getModelObject();
if (assignees != null && assignees.size() > 0) {
ObjectType assignee = assignees.get(0);
if (assignee != null) {
query.addFilter(
QueryBuilder.queryFor(CaseWorkItemType.class, getPrismContext())
.item(CaseWorkItemType.F_ASSIGNEE_REF).ref(ObjectTypeUtil.createObjectRef(assignee).asReferenceValue()).buildFilter()
);
}
}
}
return query;
}
private String getCurrentUserOid() {
try {
return getSecurityContextManager().getPrincipal().getOid();
} catch (SecurityViolationException e) {
// TODO handle more cleanly
throw new SystemException("Couldn't get currently logged user OID", e);
}
}
//endregion
//region Layout
private void initLayout() {
CaseWorkItemDtoProvider provider = createProvider();
int itemsPerPage = (int) getItemsPerPage(UserProfileStorage.TableId.PAGE_CASE_WORK_ITEMS_PANEL);
BoxedTablePanel<CaseWorkItemDto> table = new BoxedTablePanel<CaseWorkItemDto>(ID_CASE_WORK_ITEMS_TABLE, provider, initColumns(),
UserProfileStorage.TableId.PAGE_CASE_WORK_ITEMS_PANEL, itemsPerPage) {
@Override
protected WebMarkupContainer createButtonToolbar(String id) {
return new ButtonBar(id, ID_BUTTON_BAR, PageCaseWorkItems.this);
}
};
table.setShowPaging(true);
table.setOutputMarkupId(true);
table.setItemsPerPage(itemsPerPage); // really don't know why this is necessary, as e.g. in PageRoles the size setting works without it
add(table);
initSearch();
}
private List<IColumn<CaseWorkItemDto, String>> initColumns() {
List<IColumn<CaseWorkItemDto, String>> columns = new ArrayList<>();
IColumn<CaseWorkItemDto, String> column;
column = new LinkColumn<CaseWorkItemDto>(createStringResource("PageCaseWorkItems.table.description"), CaseWorkItemDto.F_DESCRIPTION) {
@Override
public void onClick(AjaxRequestTarget target, IModel<CaseWorkItemDto> rowModel) {
PageParameters parameters = new PageParameters();
parameters.add(PARAMETER_CASE_ID, rowModel.getObject().getCase().getOid());
parameters.add(PARAMETER_CASE_WORK_ITEM_ID, rowModel.getObject().getWorkItemId());
navigateToNext(PageCaseWorkItem.class, parameters);
}
};
columns.add(column);
column = new PropertyColumn<>(
createStringResource("PageCaseWorkItems.table.objectName"),
SearchingUtils.CASE_OBJECT_NAME, CaseWorkItemDto.F_OBJECT_NAME);
columns.add(column);
column = new PropertyColumn<>(createStringResource("PageCaseWorkItems.table.actor"), CaseWorkItemDto.F_ASSIGNEES);
columns.add(column);
column = new PropertyColumn<CaseWorkItemDto, String>(
createStringResource("PageCaseWorkItems.table.openTimestamp"),
SearchingUtils.CASE_OPEN_TIMESTAMP, CaseWorkItemDto.F_OPEN_TIMESTAMP) {
@Override
public void populateItem(Item<ICellPopulator<CaseWorkItemDto>> item, String componentId, IModel<CaseWorkItemDto> rowModel) {
CaseWorkItemDto dto = rowModel.getObject();
XMLGregorianCalendar createdCal = dto.getOpenTimestamp();
final Date created;
if (createdCal != null) {
created = createdCal.toGregorianCalendar().getTime();
item.add(AttributeModifier.replace("title", WebComponentUtil.getLocalizedDate(created, DateLabelComponent.LONG_MEDIUM_STYLE)));
item.add(new TooltipBehavior());
} else {
created = null;
}
item.add(new Label(componentId, new AbstractReadOnlyModel<String>() {
@Override
public String getObject() {
return WebComponentUtil.getLocalizedDate(created, DateLabelComponent.LONG_MEDIUM_STYLE);
}
}));
}
};
columns.add(column);
column = new PropertyColumn<CaseWorkItemDto, String>(
createStringResource("PageCaseWorkItems.table.deadline"),
SearchingUtils.WORK_ITEM_DEADLINE, CaseWorkItemDto.F_DEADLINE) {
@Override
public void populateItem(Item<ICellPopulator<CaseWorkItemDto>> item, String componentId, IModel<CaseWorkItemDto> rowModel) {
CaseWorkItemDto dto = rowModel.getObject();
XMLGregorianCalendar deadlineCal = dto.getDeadline();
final Date deadline;
if (deadlineCal != null) {
deadline = deadlineCal.toGregorianCalendar().getTime();
item.add(AttributeModifier.replace("title", WebComponentUtil.getLocalizedDate(deadline, DateLabelComponent.LONG_MEDIUM_STYLE)));
item.add(new TooltipBehavior());
} else {
deadline = null;
}
item.add(new Label(componentId, new AbstractReadOnlyModel<String>() {
@Override
public String getObject() {
return WebComponentUtil.getLocalizedDate(deadline, DateLabelComponent.LONG_MEDIUM_STYLE);
}
}));
}
};
columns.add(column);
column = new PropertyColumn<CaseWorkItemDto, String>(
createStringResource("PageCaseWorkItems.table.closeTimestamp"),
SearchingUtils.WORK_ITEM_CLOSE_TIMESTAMP, CaseWorkItemDto.F_CLOSE_TIMESTAMP) {
@Override
public void populateItem(Item<ICellPopulator<CaseWorkItemDto>> item, String componentId, IModel<CaseWorkItemDto> rowModel) {
CaseWorkItemDto dto = rowModel.getObject();
XMLGregorianCalendar closedCal = dto.getCloseTimestamp();
final Date closed;
if (closedCal != null) {
closed = closedCal.toGregorianCalendar().getTime();
item.add(AttributeModifier.replace("title", WebComponentUtil.getLocalizedDate(closed, DateLabelComponent.LONG_MEDIUM_STYLE)));
item.add(new TooltipBehavior());
} else {
closed = null;
}
item.add(new Label(componentId, new AbstractReadOnlyModel<String>() {
@Override
public String getObject() {
return WebComponentUtil.getLocalizedDate(closed, DateLabelComponent.LONG_MEDIUM_STYLE);
}
}));
}
};
columns.add(column);
column = new PropertyColumn<>(
createStringResource("PageCaseWorkItems.table.state"), CaseWorkItemDto.F_STATE);
columns.add(column);
return columns;
}
private Table getCaseWorkItemsTable() {
return (Table) get(createComponentPath(ID_CASE_WORK_ITEMS_TABLE));
}
private Panel getCaseWorkItemsSearchField(String itemPath) {
return (Panel) get(createComponentPath(ID_SEARCH_FILTER_FORM, itemPath));
}
private void initSearch() {
final Form searchFilterForm = new Form(ID_SEARCH_FILTER_FORM);
add(searchFilterForm);
searchFilterForm.setOutputMarkupId(true);
List<Class<? extends ObjectType>> allowedClasses = new ArrayList<>();
allowedClasses.add(ResourceType.class);
MultiValueChoosePanel<ObjectType> resource = new SingleValueChoosePanel<ObjectReferenceType, ObjectType>(
ID_SEARCH_FILTER_RESOURCE, allowedClasses, objectReferenceTransformer,
new PropertyModel<ObjectReferenceType>(Model.of(new ObjectViewDto()), ObjectViewDto.F_NAME)){
@Override
protected void choosePerformedHook(AjaxRequestTarget target, List<ObjectType> selected) {
super.choosePerformedHook(target, selected);
searchFilterPerformed(target);
}
@Override
protected void removePerformedHook(AjaxRequestTarget target, ObjectType value) {
super.removePerformedHook(target, value);
searchFilterPerformed(target);
}
};
searchFilterForm.add(resource);
allowedClasses = new ArrayList<>();
allowedClasses.add(UserType.class);
WebMarkupContainer assigneeContainer = new WebMarkupContainer(ID_SEARCH_FILTER_ASSIGNEE_CONTAINER);
MultiValueChoosePanel<ObjectType> assignee = new SingleValueChoosePanel<ObjectReferenceType, ObjectType>(
ID_SEARCH_FILTER_ASSIGNEE, allowedClasses, objectReferenceTransformer,
new PropertyModel<ObjectReferenceType>(Model.of(new ObjectViewDto()), ObjectViewDto.F_NAME)){
@Override
protected void choosePerformedHook(AjaxRequestTarget target, List<ObjectType> selected) {
super.choosePerformedHook(target, selected);
searchFilterPerformed(target);
}
@Override
protected void removePerformedHook(AjaxRequestTarget target, ObjectType value) {
super.removePerformedHook(target, value);
searchFilterPerformed(target);
}
};
assigneeContainer.add(assignee);
assigneeContainer.add(new VisibleEnableBehaviour() {
private static final long serialVersionUID = 1L;
@Override
public boolean isVisible() {
return isAuthorizedToSeeAllCases();
}
});
searchFilterForm.add(assigneeContainer);
IsolatedCheckBoxPanel includeClosedCases = new IsolatedCheckBoxPanel(ID_SEARCH_FILTER_INCLUDE_CLOSED_CASES, new Model<Boolean>(false)) {
private static final long serialVersionUID = 1L;
public void onUpdate(AjaxRequestTarget target) {
searchFilterPerformed(target);
}
};
searchFilterForm.add(includeClosedCases);
}
private boolean isAuthorizedToSeeAllCases() {
boolean authorizedToSeeAll;
try {
authorizedToSeeAll = isAuthorized(ModelAuthorizationAction.READ_ALL_WORK_ITEMS.getUrl());
return all && authorizedToSeeAll;
} catch (SchemaException | ObjectNotFoundException | ExpressionEvaluationException
| CommunicationException | ConfigurationException | SecurityViolationException e) {
// TODO handle more cleanly
throw new SystemException("Couldn't evaluate authoriztion: "+e.getMessage(), e);
}
}
//endregion
//region Actions
private void searchFilterPerformed(AjaxRequestTarget target) {
ObjectQuery query;
try {
query = createQuery();
} catch (SchemaException | ObjectNotFoundException | ExpressionEvaluationException | CommunicationException
| ConfigurationException | SecurityViolationException e) {
// TODO handle more cleanly
throw new SystemException("Couldn't create case work item query", e);
}
Table panel = getCaseWorkItemsTable();
DataTable table = panel.getDataTable();
CaseWorkItemDtoProvider provider = (CaseWorkItemDtoProvider) table.getDataProvider();
provider.setQuery(query);
table.setCurrentPage(0);
target.add(getFeedbackPanel());
target.add((Component) getCaseWorkItemsTable());
}
//endregion
private Function<ObjectType, ObjectReferenceType> objectReferenceTransformer =
(Function<ObjectType, ObjectReferenceType> & Serializable) (ObjectType o) ->
ObjectTypeUtil.createObjectRef(o);
private static class ButtonBar extends Fragment {
private static final long serialVersionUID = 1L;
public <O extends ObjectType> ButtonBar(String id, String markupId, PageCaseWorkItems page) {
super(id, markupId, page);
initLayout(page);
}
private <O extends ObjectType> void initLayout(final PageCaseWorkItems page) {
AjaxButton createCase = new AjaxButton(ID_CREATE_CASE_BUTTON, page.createStringResource("PageCaseWorkItems.button.createCase")) {
@Override
public void onClick(AjaxRequestTarget target) {
page.navigateToNext(PageCase.class);
}
};
createCase.add(new VisibleEnableBehaviour(){
private static final long serialVersionUID = 1L;
@Override
public boolean isVisible(){
boolean isVisible = false;
try {
PrismObject<CaseType> objectToCreate = new CaseType().asPrismObject();
if (objectToCreate != null) {
page.getMidpointApplication().getPrismContext().adopt(objectToCreate);
}
isVisible = ((PageBase) getPage()).isAuthorized(ModelAuthorizationAction.ADD.getUrl(),
null, objectToCreate, null, null, null);
} catch (SchemaException | ObjectNotFoundException | ExpressionEvaluationException | CommunicationException
| ConfigurationException | SecurityViolationException ex) {
LOGGER.error("Failed to check authorization for ADD action on new object of " + CaseType.class.getSimpleName()
+ " type, ", ex);
}
return isVisible;
}
});
createCase.add(new VisibleEnableBehaviour() {
private static final long serialVersionUID = 1L;
@Override
public boolean isVisible() {
return page.isAuthorizedToSeeAllCases();
}
});
add(createCase);
}
}
}
| gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/cases/PageCaseWorkItems.java | /*
* Copyright (c) 2010-2018 Evolveum et al.
*
* 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.evolveum.midpoint.web.page.admin.cases;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.function.Function;
import javax.xml.datatype.XMLGregorianCalendar;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder;
import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import com.evolveum.midpoint.gui.api.page.PageBase;
import com.evolveum.midpoint.gui.api.util.WebComponentUtil;
import com.evolveum.midpoint.model.api.ModelAuthorizationAction;
import com.evolveum.midpoint.prism.PrismConstants;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.prism.query.builder.QueryBuilder;
import com.evolveum.midpoint.prism.query.builder.S_FilterEntryOrEmpty;
import com.evolveum.midpoint.schema.util.ObjectTypeUtil;
import com.evolveum.midpoint.util.exception.CommunicationException;
import com.evolveum.midpoint.util.exception.ConfigurationException;
import com.evolveum.midpoint.util.exception.ExpressionEvaluationException;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SecurityViolationException;
import com.evolveum.midpoint.util.exception.SystemException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.web.component.AjaxButton;
import com.evolveum.midpoint.web.component.DateLabelComponent;
import com.evolveum.midpoint.web.component.data.BoxedTablePanel;
import com.evolveum.midpoint.web.component.data.Table;
import com.evolveum.midpoint.web.component.data.column.CheckBoxPanel;
import com.evolveum.midpoint.web.component.data.column.LinkColumn;
import com.evolveum.midpoint.web.component.form.multivalue.MultiValueChoosePanel;
import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour;
import com.evolveum.midpoint.web.page.admin.cases.dto.CaseWorkItemDto;
import com.evolveum.midpoint.web.page.admin.cases.dto.CaseWorkItemDtoProvider;
import com.evolveum.midpoint.web.page.admin.cases.dto.SearchingUtils;
import com.evolveum.midpoint.web.page.admin.dto.ObjectViewDto;
import com.evolveum.midpoint.web.page.admin.reports.component.SingleValueChoosePanel;
import com.evolveum.midpoint.web.security.SecurityUtils;
import com.evolveum.midpoint.web.session.UserProfileStorage;
import com.evolveum.midpoint.web.util.TooltipBehavior;
import com.evolveum.midpoint.wf.util.QueryUtils;
import com.evolveum.midpoint.xml.ns._public.common.common_3.CaseType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.CaseWorkItemType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.OtherPrivilegesLimitationType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;
/**
* @author bpowers
*/
public abstract class PageCaseWorkItems extends PageAdminCaseWorkItems {
private static final Trace LOGGER = TraceManager.getTrace(PageCaseWorkItems.class);
private static final String DOT_CLASS = PageCaseWorkItems.class.getName() + ".";
private static final String PARAMETER_CASE_ID = "caseId";
private static final String PARAMETER_CASE_WORK_ITEM_ID = "caseWorkItemId";
// Search Form
private static final String ID_SEARCH_FILTER_FORM = "searchFilterForm";
private static final String ID_SEARCH_FILTER_RESOURCE = "filterResource";
private static final String ID_SEARCH_FILTER_ASSIGNEE_CONTAINER = "filterAssigneeContainer";
private static final String ID_SEARCH_FILTER_ASSIGNEE = "filterAssignee";
private static final String ID_SEARCH_FILTER_INCLUDE_CLOSED_CASES = "filterIncludeClosedCases";
// Data Table
private static final String ID_CASE_WORK_ITEMS_TABLE = "caseWorkItemsTable";
private static final String ID_BUTTON_BAR = "buttonBar";
// Buttons
private static final String ID_CREATE_CASE_BUTTON = "createCaseButton";
private boolean all;
public PageCaseWorkItems(boolean all) {
this.all = all;
initLayout();
}
//region Data
private CaseWorkItemDtoProvider createProvider() {
CaseWorkItemDtoProvider provider = new CaseWorkItemDtoProvider(PageCaseWorkItems.this);
try {
provider.setQuery(createQuery());
} catch (SchemaException | ObjectNotFoundException | ExpressionEvaluationException | CommunicationException
| ConfigurationException | SecurityViolationException e) {
// TODO handle more cleanly
throw new SystemException("Couldn't create case work item query", e);
}
provider.setSort(SearchingUtils.WORK_ITEM_DEADLINE, SortOrder.ASCENDING);// default sorting
return provider;
}
private ObjectQuery createQuery() throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, SecurityViolationException {
ObjectQuery query;
boolean authorizedToSeeAll = isAuthorized(ModelAuthorizationAction.READ_ALL_WORK_ITEMS.getUrl());
S_FilterEntryOrEmpty q = QueryBuilder.queryFor(CaseWorkItemType.class, getPrismContext());
// S_AtomicFilterExit query = queryStart.asc(PrismConstants.T_PARENT, CaseType.F_METADATA, MetadataType.F_CREATE_TIMESTAMP).;
if (all && authorizedToSeeAll) {
query = q.build();
} else {
// not authorized to see all => sees only allocated to him (not quite what is expected, but sufficient for the time being)
query = QueryUtils.filterForAssignees(q, SecurityUtils.getPrincipalUser(),
OtherPrivilegesLimitationType.F_APPROVAL_WORK_ITEMS)
.and().item(CaseWorkItemType.F_CLOSE_TIMESTAMP).isNull().build();
}
CheckBoxPanel includeClosedCases = (CheckBoxPanel) getCaseWorkItemsSearchField(ID_SEARCH_FILTER_INCLUDE_CLOSED_CASES);
if (includeClosedCases == null || !includeClosedCases.getValue()) {
query.addFilter(
QueryBuilder.queryFor(CaseWorkItemType.class, getPrismContext())
.item(PrismConstants.T_PARENT, CaseType.F_STATE).eq("open").build().getFilter()
);
}
// Resource Filter
SingleValueChoosePanel<ObjectReferenceType, ObjectType> resourceChoice = (SingleValueChoosePanel) getCaseWorkItemsSearchField(ID_SEARCH_FILTER_RESOURCE);
if (resourceChoice != null) {
List<ObjectType> resources = resourceChoice.getModelObject();
if (resources != null && resources.size() > 0) {
ObjectType resource = resources.get(0);
if (resource != null) {
query.addFilter(
QueryBuilder.queryFor(CaseWorkItemType.class, getPrismContext())
.item(PrismConstants.T_PARENT, CaseType.F_OBJECT_REF).ref(ObjectTypeUtil.createObjectRef(resource).asReferenceValue()).buildFilter()
);
}
}
}
// Assignee Filter
SingleValueChoosePanel<ObjectReferenceType, ObjectType> assigneeChoice = (SingleValueChoosePanel) getCaseWorkItemsSearchField(createComponentPath(ID_SEARCH_FILTER_ASSIGNEE_CONTAINER, ID_SEARCH_FILTER_ASSIGNEE));
if (assigneeChoice != null) {
List<ObjectType> assignees = assigneeChoice.getModelObject();
if (assignees != null && assignees.size() > 0) {
ObjectType assignee = assignees.get(0);
if (assignee != null) {
query.addFilter(
QueryBuilder.queryFor(CaseWorkItemType.class, getPrismContext())
.item(CaseWorkItemType.F_ASSIGNEE_REF).ref(ObjectTypeUtil.createObjectRef(assignee).asReferenceValue()).buildFilter()
);
}
}
}
return query;
}
private String getCurrentUserOid() {
try {
return getSecurityContextManager().getPrincipal().getOid();
} catch (SecurityViolationException e) {
// TODO handle more cleanly
throw new SystemException("Couldn't get currently logged user OID", e);
}
}
//endregion
//region Layout
private void initLayout() {
CaseWorkItemDtoProvider provider = createProvider();
int itemsPerPage = (int) getItemsPerPage(UserProfileStorage.TableId.PAGE_CASE_WORK_ITEMS_PANEL);
BoxedTablePanel<CaseWorkItemDto> table = new BoxedTablePanel<CaseWorkItemDto>(ID_CASE_WORK_ITEMS_TABLE, provider, initColumns(),
UserProfileStorage.TableId.PAGE_CASE_WORK_ITEMS_PANEL, itemsPerPage) {
@Override
protected WebMarkupContainer createButtonToolbar(String id) {
return new ButtonBar(id, ID_BUTTON_BAR, PageCaseWorkItems.this);
}
};
table.setShowPaging(true);
table.setOutputMarkupId(true);
table.setItemsPerPage(itemsPerPage); // really don't know why this is necessary, as e.g. in PageRoles the size setting works without it
add(table);
initSearch();
}
private List<IColumn<CaseWorkItemDto, String>> initColumns() {
List<IColumn<CaseWorkItemDto, String>> columns = new ArrayList<>();
IColumn<CaseWorkItemDto, String> column;
column = new LinkColumn<CaseWorkItemDto>(createStringResource("PageCaseWorkItems.table.description"), CaseWorkItemDto.F_DESCRIPTION) {
@Override
public void onClick(AjaxRequestTarget target, IModel<CaseWorkItemDto> rowModel) {
PageParameters parameters = new PageParameters();
parameters.add(PARAMETER_CASE_ID, rowModel.getObject().getCase().getOid());
parameters.add(PARAMETER_CASE_WORK_ITEM_ID, rowModel.getObject().getWorkItemId());
navigateToNext(PageCaseWorkItem.class, parameters);
}
};
columns.add(column);
column = new PropertyColumn<>(
createStringResource("PageCaseWorkItems.table.objectName"),
SearchingUtils.CASE_OBJECT_NAME, CaseWorkItemDto.F_OBJECT_NAME);
columns.add(column);
column = new PropertyColumn<>(createStringResource("PageCaseWorkItems.table.actor"), CaseWorkItemDto.F_ASSIGNEES);
columns.add(column);
column = new PropertyColumn<CaseWorkItemDto, String>(
createStringResource("PageCaseWorkItems.table.openTimestamp"),
SearchingUtils.CASE_OPEN_TIMESTAMP, CaseWorkItemDto.F_OPEN_TIMESTAMP) {
@Override
public void populateItem(Item<ICellPopulator<CaseWorkItemDto>> item, String componentId, IModel<CaseWorkItemDto> rowModel) {
CaseWorkItemDto dto = rowModel.getObject();
XMLGregorianCalendar createdCal = dto.getOpenTimestamp();
final Date created;
if (createdCal != null) {
created = createdCal.toGregorianCalendar().getTime();
item.add(AttributeModifier.replace("title", WebComponentUtil.getLocalizedDate(created, DateLabelComponent.LONG_MEDIUM_STYLE)));
item.add(new TooltipBehavior());
} else {
created = null;
}
item.add(new Label(componentId, new AbstractReadOnlyModel<String>() {
@Override
public String getObject() {
return WebComponentUtil.getLocalizedDate(created, DateLabelComponent.LONG_MEDIUM_STYLE);
}
}));
}
};
columns.add(column);
column = new PropertyColumn<CaseWorkItemDto, String>(
createStringResource("PageCaseWorkItems.table.deadline"),
SearchingUtils.WORK_ITEM_DEADLINE, CaseWorkItemDto.F_DEADLINE) {
@Override
public void populateItem(Item<ICellPopulator<CaseWorkItemDto>> item, String componentId, IModel<CaseWorkItemDto> rowModel) {
CaseWorkItemDto dto = rowModel.getObject();
XMLGregorianCalendar deadlineCal = dto.getDeadline();
final Date deadline;
if (deadlineCal != null) {
deadline = deadlineCal.toGregorianCalendar().getTime();
item.add(AttributeModifier.replace("title", WebComponentUtil.getLocalizedDate(deadline, DateLabelComponent.LONG_MEDIUM_STYLE)));
item.add(new TooltipBehavior());
} else {
deadline = null;
}
item.add(new Label(componentId, new AbstractReadOnlyModel<String>() {
@Override
public String getObject() {
return WebComponentUtil.getLocalizedDate(deadline, DateLabelComponent.LONG_MEDIUM_STYLE);
}
}));
}
};
columns.add(column);
column = new PropertyColumn<CaseWorkItemDto, String>(
createStringResource("PageCaseWorkItems.table.closeTimestamp"),
SearchingUtils.WORK_ITEM_CLOSE_TIMESTAMP, CaseWorkItemDto.F_CLOSE_TIMESTAMP) {
@Override
public void populateItem(Item<ICellPopulator<CaseWorkItemDto>> item, String componentId, IModel<CaseWorkItemDto> rowModel) {
CaseWorkItemDto dto = rowModel.getObject();
XMLGregorianCalendar closedCal = dto.getCloseTimestamp();
final Date closed;
if (closedCal != null) {
closed = closedCal.toGregorianCalendar().getTime();
item.add(AttributeModifier.replace("title", WebComponentUtil.getLocalizedDate(closed, DateLabelComponent.LONG_MEDIUM_STYLE)));
item.add(new TooltipBehavior());
} else {
closed = null;
}
item.add(new Label(componentId, new AbstractReadOnlyModel<String>() {
@Override
public String getObject() {
return WebComponentUtil.getLocalizedDate(closed, DateLabelComponent.LONG_MEDIUM_STYLE);
}
}));
}
};
columns.add(column);
column = new PropertyColumn<>(
createStringResource("PageCaseWorkItems.table.state"), CaseWorkItemDto.F_STATE);
columns.add(column);
return columns;
}
private Table getCaseWorkItemsTable() {
return (Table) get(createComponentPath(ID_CASE_WORK_ITEMS_TABLE));
}
private Panel getCaseWorkItemsSearchField(String itemPath) {
return (Panel) get(createComponentPath(ID_SEARCH_FILTER_FORM, itemPath));
}
private void initSearch() {
final Form searchFilterForm = new Form(ID_SEARCH_FILTER_FORM);
add(searchFilterForm);
searchFilterForm.setOutputMarkupId(true);
List<Class<? extends ObjectType>> allowedClasses = new ArrayList<>();
allowedClasses.add(ResourceType.class);
MultiValueChoosePanel<ObjectType> resource = new SingleValueChoosePanel<ObjectReferenceType, ObjectType>(
ID_SEARCH_FILTER_RESOURCE, allowedClasses, objectReferenceTransformer,
new PropertyModel<ObjectReferenceType>(Model.of(new ObjectViewDto()), ObjectViewDto.F_NAME)){
@Override
protected void choosePerformedHook(AjaxRequestTarget target, List<ObjectType> selected) {
super.choosePerformedHook(target, selected);
searchFilterPerformed(target);
}
@Override
protected void removePerformedHook(AjaxRequestTarget target, ObjectType value) {
super.removePerformedHook(target, value);
searchFilterPerformed(target);
}
};
searchFilterForm.add(resource);
allowedClasses = new ArrayList<>();
allowedClasses.add(UserType.class);
WebMarkupContainer assigneeContainer = new WebMarkupContainer(ID_SEARCH_FILTER_ASSIGNEE_CONTAINER);
MultiValueChoosePanel<ObjectType> assignee = new SingleValueChoosePanel<ObjectReferenceType, ObjectType>(
ID_SEARCH_FILTER_ASSIGNEE, allowedClasses, objectReferenceTransformer,
new PropertyModel<ObjectReferenceType>(Model.of(new ObjectViewDto()), ObjectViewDto.F_NAME)){
@Override
protected void choosePerformedHook(AjaxRequestTarget target, List<ObjectType> selected) {
super.choosePerformedHook(target, selected);
searchFilterPerformed(target);
}
@Override
protected void removePerformedHook(AjaxRequestTarget target, ObjectType value) {
super.removePerformedHook(target, value);
searchFilterPerformed(target);
}
};
assigneeContainer.add(assignee);
assigneeContainer.add(new VisibleEnableBehaviour() {
private static final long serialVersionUID = 1L;
@Override
public boolean isVisible() {
return isAuthorizedToSeeAllCases();
}
});
searchFilterForm.add(assigneeContainer);
CheckBoxPanel includeClosedCases = new CheckBoxPanel(ID_SEARCH_FILTER_INCLUDE_CLOSED_CASES, new Model<Boolean>(false)) {
private static final long serialVersionUID = 1L;
public void onUpdate(AjaxRequestTarget target) {
searchFilterPerformed(target);
}
};
searchFilterForm.add(includeClosedCases);
}
private boolean isAuthorizedToSeeAllCases() {
boolean authorizedToSeeAll;
try {
authorizedToSeeAll = isAuthorized(ModelAuthorizationAction.READ_ALL_WORK_ITEMS.getUrl());
return all && authorizedToSeeAll;
} catch (SchemaException | ObjectNotFoundException | ExpressionEvaluationException
| CommunicationException | ConfigurationException | SecurityViolationException e) {
// TODO handle more cleanly
throw new SystemException("Couldn't evaluate authoriztion: "+e.getMessage(), e);
}
}
//endregion
//region Actions
private void searchFilterPerformed(AjaxRequestTarget target) {
ObjectQuery query;
try {
query = createQuery();
} catch (SchemaException | ObjectNotFoundException | ExpressionEvaluationException | CommunicationException
| ConfigurationException | SecurityViolationException e) {
// TODO handle more cleanly
throw new SystemException("Couldn't create case work item query", e);
}
Table panel = getCaseWorkItemsTable();
DataTable table = panel.getDataTable();
CaseWorkItemDtoProvider provider = (CaseWorkItemDtoProvider) table.getDataProvider();
provider.setQuery(query);
table.setCurrentPage(0);
target.add(getFeedbackPanel());
target.add((Component) getCaseWorkItemsTable());
}
//endregion
private Function<ObjectType, ObjectReferenceType> objectReferenceTransformer =
(Function<ObjectType, ObjectReferenceType> & Serializable) (ObjectType o) ->
ObjectTypeUtil.createObjectRef(o);
private static class ButtonBar extends Fragment {
private static final long serialVersionUID = 1L;
public <O extends ObjectType> ButtonBar(String id, String markupId, PageCaseWorkItems page) {
super(id, markupId, page);
initLayout(page);
}
private <O extends ObjectType> void initLayout(final PageCaseWorkItems page) {
AjaxButton createCase = new AjaxButton(ID_CREATE_CASE_BUTTON, page.createStringResource("PageCaseWorkItems.button.createCase")) {
@Override
public void onClick(AjaxRequestTarget target) {
page.navigateToNext(PageCase.class);
}
};
createCase.add(new VisibleEnableBehaviour(){
private static final long serialVersionUID = 1L;
@Override
public boolean isVisible(){
boolean isVisible = false;
try {
PrismObject<CaseType> objectToCreate = new CaseType().asPrismObject();
if (objectToCreate != null) {
page.getMidpointApplication().getPrismContext().adopt(objectToCreate);
}
isVisible = ((PageBase) getPage()).isAuthorized(ModelAuthorizationAction.ADD.getUrl(),
null, objectToCreate, null, null, null);
} catch (SchemaException | ObjectNotFoundException | ExpressionEvaluationException | CommunicationException
| ConfigurationException | SecurityViolationException ex) {
LOGGER.error("Failed to check authorization for ADD action on new object of " + CaseType.class.getSimpleName()
+ " type, ", ex);
}
return isVisible;
}
});
createCase.add(new VisibleEnableBehaviour() {
private static final long serialVersionUID = 1L;
@Override
public boolean isVisible() {
return page.isAuthorizedToSeeAllCases();
}
});
add(createCase);
}
}
}
| Aligning with current master
| gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/cases/PageCaseWorkItems.java | Aligning with current master | |
Java | apache-2.0 | c62275f2b59d75856f5d984b4e11a29229b84f8b | 0 | baishuo/cglib,wangf111/cglib,chuz/cglib,lukesandberg/cglib,HubSpot/cglib,ligzy/cglib,evertrue/cglib,lncosie/cglib,liuyb02/cglib,xgbj/cglib,mohanaraosv/cglib,TopicusZorg/cglib,cglib/cglib,yseasony/cglib,292388900/cglib,mcculls/cglib,mcmakev/cglib | /*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache Cocoon" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package net.sf.cglib.proxy;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
import net.sf.cglib.util.*;
/**
*
* this code returns Enhanced Vector to intercept all methods for tracing
* <pre>
* java.util.Vector vector = (java.util.Vector)Enhancer.enhance(
* java.util.Vector.<b>class</b>,
* new Class[]{java.util.List.<b>class</b>},
*
* new MethodInterceptor(){
*
*
* <b>public boolean invokeSuper</b>( Object obj,java.lang.reflect.Method method,
* Object args[])
* throws java.lang.Throwable{
* return true;
* }
*
*
* <b>public</b> Object <b>afterReturn</b>( Object obj, java.lang.reflect.Method method,
* Object args[],
* boolean invokedSuper, Object retValFromSuper,
* java.lang.Throwable e )throws java.lang.Throwable{
* System.out.println(method);
* return retValFromSuper;//return the same as supper
* }
*
* });
* </pre>
*@author Juozas Baliuka <a href="mailto:baliuka@mwm.lt">
* baliuka@mwm.lt</a>
*@version $Id: Enhancer.java,v 1.32 2002/11/18 21:40:21 herbyderby Exp $
*/
public class Enhancer implements ClassFileConstants {
private static final String CLASS_PREFIX = "net.sf.cglib.proxy";
private static final String CLASS_SUFFIX = "$$EnhancedByCGLIB$$";
private static int index = 0;
private static Map factories = new HashMap();
private static Map cache = new WeakHashMap();
private Enhancer() {}
public static MethodInterceptor getMethodInterceptor(Object enhanced){
return ((Factory)enhanced).getInterceptor();
}
/**
* implemented as
* return enhance(cls,interfaces,ih, null);
*/
public static Object enhance(
Class cls,
Class interfaces[],
MethodInterceptor ih)
throws CodeGenerationException {
return enhance(
cls,
interfaces,
ih,
null,
null );
}
public synchronized static Object enhance(
Class cls,
Class interfaces[],
MethodInterceptor ih,
ClassLoader loader )
throws CodeGenerationException {
return enhance(
cls,
interfaces,
ih,
loader,
null );
}
/** enhances public not final class,
* source class must have public or protected no args constructor.
* Code is generated for protected and public not final methods,
* package scope methods supported from source class package.
* Defines new class in source class package, if it not java*.
* @param cls class to extend, uses Object.class if null
* @param interfaces interfaces to implement, can be null
* @param ih valid interceptor implementation
* @param loader classloater for enhanced class, uses "current" if null
* @param wreplace static method to implement writeReplace, must have
* single Object type parameter(to replace) and return object,
* default implementation from InternalReplace is used if
* parameter is null : static public Object InternalReplace.writeReplace(
* Object enhanced )
* throws ObjectStreamException;
* @throws Throwable on error
* @return instanse of enhanced class
*/
public synchronized static Object enhance(Class cls,
Class interfaces[],
MethodInterceptor ih,
ClassLoader loader,
java.lang.reflect.Method wreplace )
throws CodeGenerationException {
if (ih == null) {
throw new NullPointerException("MethodInterceptor is null");
}
if (cls == null) {
cls = Object.class;
}
if (loader == null) {
loader = Enhancer.class.getClassLoader();
}
Object key = new Key(cls, interfaces, wreplace);
Map map = (Map)cache.get(loader);
if (map == null) {
map = new Hashtable();
cache.put(loader, map);
}
Class result = (Class) map.get(key);
if ( result == null ) {
String class_name = cls.getName() + CLASS_SUFFIX;
if (class_name.startsWith("java")) {
class_name = CLASS_PREFIX + class_name;
}
class_name += index++;
result = new EnhancerGenerator(class_name, cls, interfaces, ih, loader, wreplace).define();
map.put(key, result);
}
Factory factory = (Factory)factories.get(result);
if (factory == null) {
try {
Class mi = Class.forName(MethodInterceptor.class.getName(), true, loader);
factory = (Factory)result.getConstructor(new Class[]{ mi }).newInstance(new Object[] { null });
factories.put(result,factory);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new CodeGenerationException(e);
}
}
return factory.newInstance(ih);
}
private static final class Key {
private static final int hashConstant = 13; // positive and odd
private int hash = 41; // positive and odd
private Class cls;
private Class[] interfaces;
private Method wreplace;
public Key(Class cls, Class[] interfaces, Method wreplace) {
this.cls = cls;
this.interfaces = interfaces;
this.wreplace = wreplace;
hash = hash * hashConstant + cls.hashCode();
if (interfaces != null) {
for (int i = 0, size = interfaces.length; i < size; i++) {
hash = hash * hashConstant + interfaces[i].hashCode();
}
}
if (wreplace != null)
hash = hash * hashConstant + wreplace.hashCode();
}
public boolean equals(Object obj) {
Key other = (Key)obj;
return cls.equals(other.cls) &&
(wreplace == null ? other.wreplace == null : wreplace.equals(other.wreplace)) &&
Arrays.equals(interfaces, other.interfaces);
}
public int hashCode() {
return hash;
}
}
public static class InternalReplace implements Serializable {
private String parentClassName;
private String [] interfaceNames;
private MethodInterceptor mi;
public InternalReplace() {
}
private InternalReplace(String parentClassName, String[] interfaces,
MethodInterceptor mi) {
this.parentClassName = parentClassName;
this.interfaceNames = interfaceNames;
this.mi = mi;
}
public static Object writeReplace(Object enhanced) throws ObjectStreamException {
MethodInterceptor mi = Enhancer.getMethodInterceptor(enhanced);
String parentClassName = enhanced.getClass().getSuperclass().getName();
Class interfaces[] = enhanced.getClass().getInterfaces();
String [] interfaceNames = new String[interfaces.length];
for (int i = 0; i < interfaces.length; i++) {
interfaceNames[i] = interfaces[i].getName();
}
return new InternalReplace(parentClassName, interfaceNames, mi);
}
private Object readResolve() throws ObjectStreamException {
try {
ClassLoader loader = getClass().getClassLoader();
Class parent = loader.loadClass(parentClassName);
Class interfaces[] = null;
if (interfaceNames != null) {
interfaces = new Class[interfaceNames.length];
for (int i = 0; i< interfaceNames.length; i++) {
interfaces[i] = loader.loadClass(interfaceNames[i]);
}
}
return Enhancer.enhance(parent, interfaces, mi, loader);
} catch (ClassNotFoundException e) {
throw new ReadResolveException(e);
} catch (CodeGenerationException e) {
throw new ReadResolveException(e.getCause());
}
}
}
public static class ReadResolveException extends ObjectStreamException {
private Throwable cause;
public ReadResolveException(Throwable cause) {
super(cause.getMessage());
this.cause = cause;
}
public Throwable getCause() {
return cause;
}
}
}
| src/proxy/net/sf/cglib/proxy/Enhancer.java | /*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache Cocoon" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package net.sf.cglib.proxy;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
import net.sf.cglib.util.*;
/**
*
* this code returns Enhanced Vector to intercept all methods for tracing
* <pre>
* java.util.Vector vector = (java.util.Vector)Enhancer.enhance(
* java.util.Vector.<b>class</b>,
* new Class[]{java.util.List.<b>class</b>},
*
* new MethodInterceptor(){
*
*
* <b>public boolean invokeSuper</b>( Object obj,java.lang.reflect.Method method,
* Object args[])
* throws java.lang.Throwable{
* return true;
* }
*
*
* <b>public</b> Object <b>afterReturn</b>( Object obj, java.lang.reflect.Method method,
* Object args[],
* boolean invokedSuper, Object retValFromSuper,
* java.lang.Throwable e )throws java.lang.Throwable{
* System.out.println(method);
* return retValFromSuper;//return the same as supper
* }
*
* });
* </pre>
*@author Juozas Baliuka <a href="mailto:baliuka@mwm.lt">
* baliuka@mwm.lt</a>
*@version $Id: Enhancer.java,v 1.31 2002/11/16 19:20:10 herbyderby Exp $
*/
public class Enhancer implements ClassFileConstants {
private static final String CLASS_PREFIX = "net.sf.cglib.proxy";
private static final String CLASS_SUFFIX = "$$EnhancedByCGLIB$$";
private static int index = 0;
private static Map factories = new HashMap();
private static Map cache = new WeakHashMap();
private Enhancer() {}
public static MethodInterceptor getMethodInterceptor(Object enhanced){
return ((Factory)enhanced).getInterceptor();
}
/**
* implemented as
* return enhance(cls,interfaces,ih, null);
*/
public static Object enhance(
Class cls,
Class interfaces[],
MethodInterceptor ih)
throws CodeGenerationException {
return enhance(
cls,
interfaces,
ih,
null,
null );
}
public synchronized static Object enhance(
Class cls,
Class interfaces[],
MethodInterceptor ih,
ClassLoader loader )
throws CodeGenerationException {
return enhance(
cls,
interfaces,
ih,
loader,
null );
}
/** enhances public not final class,
* source class must have public or protected no args constructor.
* Code is generated for protected and public not final methods,
* package scope methods supported from source class package.
* Defines new class in source class package, if it not java*.
* @param cls class to extend, uses Object.class if null
* @param interfaces interfaces to implement, can be null
* @param ih valid interceptor implementation
* @param loader classloater for enhanced class, uses "current" if null
* @param wreplace static method to implement writeReplace, must have
* single Object type parameter(to replace) and return object,
* default implementation from InternalReplace is used if
* parameter is null : static public Object InternalReplace.writeReplace(
* Object enhanced )
* throws ObjectStreamException;
* @throws Throwable on error
* @return instanse of enhanced class
*/
public synchronized static Object enhance(Class cls,
Class interfaces[],
MethodInterceptor ih,
ClassLoader loader,
java.lang.reflect.Method wreplace )
throws CodeGenerationException {
if (ih == null) {
throw new NullPointerException("MethodInterceptor is null");
}
if (cls == null) {
cls = Object.class;
}
if (loader == null) {
loader = Enhancer.class.getClassLoader();
}
Object key = new Key(cls, interfaces, wreplace);
Map map = (Map)cache.get(loader);
if (map == null) {
map = new Hashtable();
cache.put(loader, map);
}
Class result = (Class) map.get(key);
if ( result == null ) {
String class_name = cls.getName() + CLASS_SUFFIX;
if (class_name.startsWith("java")) {
class_name = CLASS_PREFIX + class_name;
}
class_name += index++;
result = new EnhancerGenerator(class_name, cls, interfaces, ih, loader, wreplace).define();
map.put(key, result);
}
Factory factory = (Factory)factories.get(result);
if (factory == null) {
try {
Class mi = Class.forName(MethodInterceptor.class.getName(), true, loader);
factory = (Factory)result.getConstructor(new Class[]{ mi }).newInstance(new Object[] { null });
factories.put(result,factory);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new CodeGenerationException(e);
}
}
return factory.newInstance(ih);
}
private static final class Key {
private static final int hashConstant = 13; // positive and odd
private int hash = 41; // positive and odd
private Class cls;
private Class[] interfaces;
private Method wreplace;
public Key(Class cls, Class[] interfaces, Method wreplace) {
this.cls = cls;
this.interfaces = interfaces;
this.wreplace = wreplace;
hash = hash * hashConstant + cls.hashCode();
if (interfaces != null) {
for (int i = 0, size = interfaces.length; i < size; i++) {
hash = hash * hashConstant + interfaces[i].hashCode();
}
}
if (wreplace != null)
hash = hash * hashConstant + wreplace.hashCode();
}
public boolean equals(Object obj) {
Key other = (Key)obj;
return cls.equals(other.cls) &&
(wreplace == null ? other.wreplace == null : wreplace.equals(other.wreplace)) &&
Arrays.equals(interfaces, other.interfaces);
}
public int hashCode() {
return hash;
}
}
static public class InternalReplace implements Serializable {
private String parentClassName;
private String [] interfaceNames;
private MethodInterceptor mi;
public InternalReplace() {
}
private InternalReplace(String parentClassName, String[] interfaces,
MethodInterceptor mi) {
this.parentClassName = parentClassName;
this.interfaceNames = interfaceNames;
this.mi = mi;
}
public static Object writeReplace(Object enhanced) throws ObjectStreamException {
MethodInterceptor mi = Enhancer.getMethodInterceptor(enhanced);
String parentClassName = enhanced.getClass().getSuperclass().getName();
Class interfaces[] = enhanced.getClass().getInterfaces();
String [] interfaceNames = new String[interfaces.length];
for (int i = 0; i < interfaces.length; i++) {
interfaceNames[i] = interfaces[i].getName();
}
return new InternalReplace(parentClassName, interfaceNames, mi);
}
private Object readResolve() throws ObjectStreamException {
try {
ClassLoader loader = getClass().getClassLoader();
Class parent = loader.loadClass(parentClassName);
Class interfaces[] = null;
if (interfaceNames != null) {
interfaces = new Class[interfaceNames.length];
for (int i = 0; i< interfaceNames.length; i++) {
interfaces[i] = loader.loadClass(interfaceNames[i]);
}
}
return Enhancer.enhance(parent, interfaces, mi, loader);
} catch (Throwable t) { // TODO
// throw new ObjectStreamException(t.getMessage());
throw new RuntimeException("TODO");
}
}
}
}
| Throw ObjectStreamException from readResolve (ObjectStreamException is
abstract (at least in JDK1.4), need to use a subclass)
| src/proxy/net/sf/cglib/proxy/Enhancer.java | Throw ObjectStreamException from readResolve (ObjectStreamException is abstract (at least in JDK1.4), need to use a subclass) | |
Java | apache-2.0 | 17277c4f3611200010e52fd1e3e1ac387d47c4b4 | 0 | Chavjoh/SweetCityMobile | package ch.hesso.master.sweetcity.activity.report;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.api.client.util.DateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import ch.hesso.master.sweetcity.Constants;
import ch.hesso.master.sweetcity.R;
import ch.hesso.master.sweetcity.activity.IntentTag;
import ch.hesso.master.sweetcity.activity.tag.TagSelectionActivity;
import ch.hesso.master.sweetcity.callback.ReportCallbackImpl;
import ch.hesso.master.sweetcity.data.CurrentTagList;
import ch.hesso.master.sweetcity.model.Report;
import ch.hesso.master.sweetcity.model.Tag;
import ch.hesso.master.sweetcity.task.AddReportAsyncTask;
import ch.hesso.master.sweetcity.utils.AuthUtils;
import ch.hesso.master.sweetcity.utils.DialogUtils;
import ch.hesso.master.sweetcity.utils.ImageUtils;
import ch.hesso.master.sweetcity.utils.LayoutUtils;
import ch.hesso.master.sweetcity.utils.ModelUtils;
public class ReportActivity extends Activity {
private TextView tagResume;
private ImageView imageView;
private Bitmap bitmapPicture;
private HashMap<Integer, Tag> tagList;
private Button capture;
private Button tagSelection;
private Button submit;
Location currentLocation;
LocationListener locationListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_report);
this.updateCurrentLocation();
getActionBar().setDisplayHomeAsUpEnabled(true);
findViews();
initButtons();
}
void updateCurrentLocation() {
if (this.locationListener == null)
this.locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
ReportActivity.this.currentLocation = location;
}
@Override
public void onProviderDisabled(String provider) { }
@Override
public void onProviderEnabled(String provider) { }
@Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
};
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(false);
criteria.setHorizontalAccuracy(Criteria.ACCURACY_MEDIUM);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
criteria.setSpeedAccuracy(Criteria.NO_REQUIREMENT);
criteria.setSpeedRequired(false);
LocationManager locationManager = (LocationManager)ReportActivity.this.getSystemService(LOCATION_SERVICE);
locationManager.requestSingleUpdate(criteria, this.locationListener, null);
}
private void findViews() {
tagList = new HashMap<Integer, Tag>();
tagResume = LayoutUtils.findView(this, R.id.tv_tag);
imageView = LayoutUtils.findView(this, R.id.iv_report);
capture = LayoutUtils.findView(this, R.id.btn_picture);
tagSelection = LayoutUtils.findView(this, R.id.btn_tag);
submit = LayoutUtils.findView(this, R.id.btn_submit);
}
private void initButtons() {
capture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, IntentTag.TAKE_PICTURE);
}
});
tagSelection.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent tagIntent = new Intent(getApplicationContext(), TagSelectionActivity.class);
startActivityForResult(tagIntent, IntentTag.TAG_SELECTION);
}
});
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
submitReport();
}
});
}
private void submitReport() {
if (bitmapPicture == null) {
DialogUtils.show(ReportActivity.this, "To submit a report, you need to take an representative image.");
return;
}
if (this.currentLocation == null) {
LocationManager locationManager = (LocationManager)ReportActivity.this.getSystemService(LOCATION_SERVICE);
this.currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (this.currentLocation == null) {
DialogUtils.show(ReportActivity.this, "Unable to get your current location.");
return;
}
}
Report newReport = new Report();
newReport.setLatitude((float) this.currentLocation.getLatitude());
newReport.setLongitude((float) this.currentLocation.getLongitude());
newReport.setSubmitDate(new DateTime(new Date()));
newReport.setUser(AuthUtils.getAccount());
newReport.setListTag(new ArrayList(tagList.values()));
ReportCallbackImpl callback = new ReportCallbackWithResult(ReportActivity.this);
new AddReportAsyncTask(this, callback, AuthUtils.getCredential(), newReport, bitmapPicture).execute();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case IntentTag.TAKE_PICTURE:
if (resultCode == RESULT_OK) {
bitmapPicture = (Bitmap) data.getExtras().get("data");
showPicture();
capture.setText(R.string.retake_picture);
}
break;
case IntentTag.TAG_SELECTION:
if (resultCode == RESULT_OK) {
ArrayList<Integer> result = data.getExtras().getIntegerArrayList("selectedItems");
tagList.clear();
CurrentTagList.getInstance().putAllFromPositions(tagList, result);
showTagList();
tagSelection.setText(R.string.reselect_tags);
}
break;
}
}
public void showTagList() {
tagResume.setText(ModelUtils.listToString(new ArrayList<Tag>(tagList.values())));
}
public void showPicture() {
if (bitmapPicture != null) {
imageView.setImageBitmap(ImageUtils.getRoundedCornerBitmap(bitmapPicture, 64));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_report, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putIntegerArrayList("tagList", new ArrayList<Integer>(tagList.keySet()));
savedInstanceState.putParcelable("image", bitmapPicture);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
bitmapPicture = savedInstanceState.getParcelable("image");
ArrayList<Integer> positionList = savedInstanceState.getIntegerArrayList("tagList");
CurrentTagList.getInstance().putAllFromPositions(tagList, positionList);
Log.d(Constants.PROJECT_NAME, "positionList " + positionList.toString());
showTagList();
showPicture();
}
private class ReportCallbackWithResult extends ReportCallbackImpl {
public ReportCallbackWithResult(Activity context) {
super(context);
}
@Override
public void afterAdding() {
if (!this.isFailed)
ReportActivity.this.setResult(RESULT_OK, new Intent());
super.afterAdding();
}
}
}
| app/src/main/java/ch/hesso/master/sweetcity/activity/report/ReportActivity.java | package ch.hesso.master.sweetcity.activity.report;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.api.client.util.DateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import ch.hesso.master.sweetcity.Constants;
import ch.hesso.master.sweetcity.R;
import ch.hesso.master.sweetcity.activity.IntentTag;
import ch.hesso.master.sweetcity.activity.tag.TagSelectionActivity;
import ch.hesso.master.sweetcity.callback.ReportCallbackImpl;
import ch.hesso.master.sweetcity.data.CurrentTagList;
import ch.hesso.master.sweetcity.model.Report;
import ch.hesso.master.sweetcity.model.Tag;
import ch.hesso.master.sweetcity.task.AddReportAsyncTask;
import ch.hesso.master.sweetcity.utils.AuthUtils;
import ch.hesso.master.sweetcity.utils.DialogUtils;
import ch.hesso.master.sweetcity.utils.ImageUtils;
import ch.hesso.master.sweetcity.utils.LayoutUtils;
import ch.hesso.master.sweetcity.utils.ModelUtils;
public class ReportActivity extends Activity {
private TextView tagResume;
private ImageView imageView;
private Bitmap bitmapPicture;
private HashMap<Integer, Tag> tagList;
private Button capture;
private Button tagSelection;
private Button submit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_report);
getActionBar().setDisplayHomeAsUpEnabled(true);
findViews();
initButtons();
}
private void findViews() {
tagList = new HashMap<Integer, Tag>();
tagResume = LayoutUtils.findView(this, R.id.tv_tag);
imageView = LayoutUtils.findView(this, R.id.iv_report);
capture = LayoutUtils.findView(this, R.id.btn_picture);
tagSelection = LayoutUtils.findView(this, R.id.btn_tag);
submit = LayoutUtils.findView(this, R.id.btn_submit);
}
private void initButtons() {
capture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, IntentTag.TAKE_PICTURE);
}
});
tagSelection.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent tagIntent = new Intent(getApplicationContext(), TagSelectionActivity.class);
startActivityForResult(tagIntent, IntentTag.TAG_SELECTION);
}
});
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
submitReport();
}
});
}
private void submitReport() {
if (bitmapPicture == null) {
DialogUtils.show(ReportActivity.this, "To submit a report, you need to take an representative image.");
return;
}
LocationManager locationManager = (LocationManager) ReportActivity.this.getSystemService(LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Report newReport = new Report();
newReport.setLatitude((float) location.getLatitude());
newReport.setLongitude((float) location.getLongitude());
newReport.setSubmitDate(new DateTime(new Date()));
newReport.setUser(AuthUtils.getAccount());
newReport.setListTag(new ArrayList(tagList.values()));
ReportCallbackImpl callback = new ReportCallbackWithResult(ReportActivity.this);
new AddReportAsyncTask(this, callback, AuthUtils.getCredential(), newReport, bitmapPicture).execute();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case IntentTag.TAKE_PICTURE:
if (resultCode == RESULT_OK) {
bitmapPicture = (Bitmap) data.getExtras().get("data");
showPicture();
capture.setText(R.string.retake_picture);
}
break;
case IntentTag.TAG_SELECTION:
if (resultCode == RESULT_OK) {
ArrayList<Integer> result = data.getExtras().getIntegerArrayList("selectedItems");
tagList.clear();
CurrentTagList.getInstance().putAllFromPositions(tagList, result);
showTagList();
tagSelection.setText(R.string.reselect_tags);
}
break;
}
}
public void showTagList() {
tagResume.setText(ModelUtils.listToString(new ArrayList<Tag>(tagList.values())));
}
public void showPicture() {
if (bitmapPicture != null) {
imageView.setImageBitmap(ImageUtils.getRoundedCornerBitmap(bitmapPicture, 64));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_report, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putIntegerArrayList("tagList", new ArrayList<Integer>(tagList.keySet()));
savedInstanceState.putParcelable("image", bitmapPicture);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
bitmapPicture = savedInstanceState.getParcelable("image");
ArrayList<Integer> positionList = savedInstanceState.getIntegerArrayList("tagList");
CurrentTagList.getInstance().putAllFromPositions(tagList, positionList);
Log.d(Constants.PROJECT_NAME, "positionList " + positionList.toString());
showTagList();
showPicture();
}
private class ReportCallbackWithResult extends ReportCallbackImpl {
public ReportCallbackWithResult(Activity context) {
super(context);
}
@Override
public void afterAdding() {
if (!this.isFailed)
ReportActivity.this.setResult(RESULT_OK, new Intent());
super.afterAdding();
}
}
}
| Try to obtain the current GPS location when submittin a report.
| app/src/main/java/ch/hesso/master/sweetcity/activity/report/ReportActivity.java | Try to obtain the current GPS location when submittin a report. | |
Java | apache-2.0 | 33d48fbebc0378a006f285e846f06d2d12bae9c2 | 0 | lingfliu/dv_omnicontrol_android,lingfliu/dv_omnicontrol_android | package cn.diaovision.omnicontrol.core.message.conference;
import cn.diaovision.omnicontrol.util.ByteUtils;
/**
* Header of MCUMessage
* Created by liulingfeng on 2017/4/13.
*/
public class Header{
int len; // 2 bytes, 消息长度
byte version; //软件版本号
//消息类型 1.Request 2.Response
// 3.Create_conf(创建会议)
// 4.Invite_Term(邀请终端)
// 5.用户登录
// 6.添加会议
// 7.添加终端
// 8.添加终端到地址簿
// 9.删除地址簿
// 10.版本信息
// 11.发言申请消息
// 12.系统配置
byte type;
public Header(int len, byte type) {
this.len = len;
this.type = type;
this.version = 0x01;//TODO: verify version
}
public byte[] toBytes(){
byte[] bytes = new byte[4]; //2+1+1
//len += 4;
byte[] lenHex = ByteUtils.int2bytes(len, 2);
bytes[0] = lenHex[0];
bytes[1] = lenHex[1];
bytes[2] = version;
bytes[3] = type;
return bytes;
}
public boolean verifyHeader(){
return version == McuMessage.VERSION;
}
}
| app/src/main/java/cn/diaovision/omnicontrol/core/message/conference/Header.java | package cn.diaovision.omnicontrol.core.message.conference;
/**
* Created by liulingfeng on 2017/4/13.
*/
public class Header{
int len; // 2 bytes, 消息长度
byte version; //软件版本号
//消息类型 1.Request 2.Response
// 3.Create_conf(创建会议)
// 4.Invite_Term(邀请终端)
// 5.用户登录
// 6.添加会议
// 7.添加终端
// 8.添加终端到地址簿
// 9.删除地址簿
// 10.版本信息
// 11.发言申请消息
// 12.系统配置
byte type;
public Header(int len, byte type) {
this.len = len;
this.type = type;
this.version = 0x01;//TODO: verify version
}
public byte[] toBytes(){
byte[] bytes = new byte[4]; //2+1+1
len += 4;
bytes[0] = (byte) ((len>>8) & 0xff);
bytes[1] = (byte) (len & 0xff);
bytes[2] = version;
bytes[3] = type;
return bytes;
}
public boolean verifyHeader(){
if (version == McuMessage.VERSION){
return true;
}
else {
return false;
}
}
}
| added getters
| app/src/main/java/cn/diaovision/omnicontrol/core/message/conference/Header.java | added getters | |
Java | apache-2.0 | 3c07a427dc23708c35ae088f2f8fd13de1854060 | 0 | diendt/elasticsearch,HonzaKral/elasticsearch,vroyer/elasticassandra,JackyMai/elasticsearch,vroyer/elassandra,brandonkearby/elasticsearch,gmarz/elasticsearch,fforbeck/elasticsearch,spiegela/elasticsearch,henakamaMSFT/elasticsearch,avikurapati/elasticsearch,diendt/elasticsearch,xuzha/elasticsearch,artnowo/elasticsearch,dongjoon-hyun/elasticsearch,gingerwizard/elasticsearch,clintongormley/elasticsearch,naveenhooda2000/elasticsearch,mohit/elasticsearch,njlawton/elasticsearch,martinstuga/elasticsearch,fred84/elasticsearch,shreejay/elasticsearch,tebriel/elasticsearch,glefloch/elasticsearch,dongjoon-hyun/elasticsearch,girirajsharma/elasticsearch,scottsom/elasticsearch,avikurapati/elasticsearch,zkidkid/elasticsearch,ESamir/elasticsearch,nomoa/elasticsearch,fforbeck/elasticsearch,xuzha/elasticsearch,camilojd/elasticsearch,diendt/elasticsearch,StefanGor/elasticsearch,obourgain/elasticsearch,henakamaMSFT/elasticsearch,coding0011/elasticsearch,nilabhsagar/elasticsearch,jchampion/elasticsearch,JervyShi/elasticsearch,yanjunh/elasticsearch,palecur/elasticsearch,nezirus/elasticsearch,episerver/elasticsearch,a2lin/elasticsearch,naveenhooda2000/elasticsearch,dpursehouse/elasticsearch,Helen-Zhao/elasticsearch,obourgain/elasticsearch,awislowski/elasticsearch,tebriel/elasticsearch,JervyShi/elasticsearch,mmaracic/elasticsearch,gfyoung/elasticsearch,gingerwizard/elasticsearch,Helen-Zhao/elasticsearch,dpursehouse/elasticsearch,coding0011/elasticsearch,mikemccand/elasticsearch,gfyoung/elasticsearch,markwalkom/elasticsearch,HonzaKral/elasticsearch,camilojd/elasticsearch,nilabhsagar/elasticsearch,MisterAndersen/elasticsearch,myelin/elasticsearch,mikemccand/elasticsearch,gmarz/elasticsearch,a2lin/elasticsearch,geidies/elasticsearch,camilojd/elasticsearch,markwalkom/elasticsearch,scorpionvicky/elasticsearch,ESamir/elasticsearch,dpursehouse/elasticsearch,spiegela/elasticsearch,yynil/elasticsearch,naveenhooda2000/elasticsearch,masaruh/elasticsearch,awislowski/elasticsearch,winstonewert/elasticsearch,rlugojr/elasticsearch,yanjunh/elasticsearch,fforbeck/elasticsearch,LeoYao/elasticsearch,rlugojr/elasticsearch,davidvgalbraith/elasticsearch,Shepard1212/elasticsearch,wenpos/elasticsearch,a2lin/elasticsearch,wangtuo/elasticsearch,rajanm/elasticsearch,GlenRSmith/elasticsearch,sreeramjayan/elasticsearch,mikemccand/elasticsearch,sneivandt/elasticsearch,ThiagoGarciaAlves/elasticsearch,maddin2016/elasticsearch,alexshadow007/elasticsearch,fernandozhu/elasticsearch,i-am-Nathan/elasticsearch,alexshadow007/elasticsearch,myelin/elasticsearch,jprante/elasticsearch,martinstuga/elasticsearch,bawse/elasticsearch,yanjunh/elasticsearch,kalimatas/elasticsearch,ZTE-PaaS/elasticsearch,jpountz/elasticsearch,elasticdog/elasticsearch,mikemccand/elasticsearch,cwurm/elasticsearch,rajanm/elasticsearch,mmaracic/elasticsearch,fforbeck/elasticsearch,awislowski/elasticsearch,glefloch/elasticsearch,rlugojr/elasticsearch,C-Bish/elasticsearch,lks21c/elasticsearch,myelin/elasticsearch,MaineC/elasticsearch,jchampion/elasticsearch,elasticdog/elasticsearch,coding0011/elasticsearch,mjason3/elasticsearch,henakamaMSFT/elasticsearch,gfyoung/elasticsearch,njlawton/elasticsearch,trangvh/elasticsearch,wenpos/elasticsearch,JervyShi/elasticsearch,sneivandt/elasticsearch,wuranbo/elasticsearch,martinstuga/elasticsearch,umeshdangat/elasticsearch,ZTE-PaaS/elasticsearch,ThiagoGarciaAlves/elasticsearch,wuranbo/elasticsearch,s1monw/elasticsearch,jbertouch/elasticsearch,strapdata/elassandra5-rc,obourgain/elasticsearch,mohit/elasticsearch,spiegela/elasticsearch,C-Bish/elasticsearch,mortonsykes/elasticsearch,gingerwizard/elasticsearch,bawse/elasticsearch,zkidkid/elasticsearch,LeoYao/elasticsearch,obourgain/elasticsearch,pozhidaevak/elasticsearch,geidies/elasticsearch,fernandozhu/elasticsearch,dpursehouse/elasticsearch,alexshadow007/elasticsearch,C-Bish/elasticsearch,JervyShi/elasticsearch,naveenhooda2000/elasticsearch,awislowski/elasticsearch,dongjoon-hyun/elasticsearch,C-Bish/elasticsearch,girirajsharma/elasticsearch,elasticdog/elasticsearch,geidies/elasticsearch,geidies/elasticsearch,fred84/elasticsearch,rlugojr/elasticsearch,tebriel/elasticsearch,uschindler/elasticsearch,ZTE-PaaS/elasticsearch,scottsom/elasticsearch,qwerty4030/elasticsearch,masaruh/elasticsearch,mmaracic/elasticsearch,winstonewert/elasticsearch,avikurapati/elasticsearch,gfyoung/elasticsearch,JackyMai/elasticsearch,jchampion/elasticsearch,C-Bish/elasticsearch,GlenRSmith/elasticsearch,sreeramjayan/elasticsearch,shreejay/elasticsearch,wangtuo/elasticsearch,IanvsPoplicola/elasticsearch,Helen-Zhao/elasticsearch,diendt/elasticsearch,jpountz/elasticsearch,myelin/elasticsearch,strapdata/elassandra,StefanGor/elasticsearch,ESamir/elasticsearch,MaineC/elasticsearch,vroyer/elasticassandra,coding0011/elasticsearch,ZTE-PaaS/elasticsearch,mortonsykes/elasticsearch,GlenRSmith/elasticsearch,yanjunh/elasticsearch,MaineC/elasticsearch,qwerty4030/elasticsearch,tebriel/elasticsearch,i-am-Nathan/elasticsearch,girirajsharma/elasticsearch,trangvh/elasticsearch,jbertouch/elasticsearch,brandonkearby/elasticsearch,ThiagoGarciaAlves/elasticsearch,LewayneNaidoo/elasticsearch,martinstuga/elasticsearch,jpountz/elasticsearch,liweinan0423/elasticsearch,avikurapati/elasticsearch,scorpionvicky/elasticsearch,lks21c/elasticsearch,martinstuga/elasticsearch,MisterAndersen/elasticsearch,uschindler/elasticsearch,i-am-Nathan/elasticsearch,MisterAndersen/elasticsearch,HonzaKral/elasticsearch,maddin2016/elasticsearch,lks21c/elasticsearch,strapdata/elassandra5-rc,kalimatas/elasticsearch,nezirus/elasticsearch,uschindler/elasticsearch,nezirus/elasticsearch,gingerwizard/elasticsearch,scorpionvicky/elasticsearch,wuranbo/elasticsearch,sreeramjayan/elasticsearch,mapr/elasticsearch,mortonsykes/elasticsearch,spiegela/elasticsearch,zkidkid/elasticsearch,mapr/elasticsearch,glefloch/elasticsearch,shreejay/elasticsearch,Stacey-Gammon/elasticsearch,cwurm/elasticsearch,wangtuo/elasticsearch,palecur/elasticsearch,nomoa/elasticsearch,brandonkearby/elasticsearch,scottsom/elasticsearch,mapr/elasticsearch,yanjunh/elasticsearch,wuranbo/elasticsearch,rajanm/elasticsearch,artnowo/elasticsearch,jchampion/elasticsearch,naveenhooda2000/elasticsearch,fred84/elasticsearch,markharwood/elasticsearch,LewayneNaidoo/elasticsearch,jprante/elasticsearch,Stacey-Gammon/elasticsearch,s1monw/elasticsearch,IanvsPoplicola/elasticsearch,s1monw/elasticsearch,mohit/elasticsearch,brandonkearby/elasticsearch,rajanm/elasticsearch,clintongormley/elasticsearch,ricardocerq/elasticsearch,Shepard1212/elasticsearch,dpursehouse/elasticsearch,pozhidaevak/elasticsearch,alexshadow007/elasticsearch,jimczi/elasticsearch,ThiagoGarciaAlves/elasticsearch,avikurapati/elasticsearch,clintongormley/elasticsearch,bawse/elasticsearch,trangvh/elasticsearch,martinstuga/elasticsearch,Stacey-Gammon/elasticsearch,ricardocerq/elasticsearch,mmaracic/elasticsearch,njlawton/elasticsearch,kalimatas/elasticsearch,maddin2016/elasticsearch,ricardocerq/elasticsearch,henakamaMSFT/elasticsearch,cwurm/elasticsearch,Shepard1212/elasticsearch,yynil/elasticsearch,davidvgalbraith/elasticsearch,Stacey-Gammon/elasticsearch,LeoYao/elasticsearch,strapdata/elassandra,a2lin/elasticsearch,masaruh/elasticsearch,xuzha/elasticsearch,davidvgalbraith/elasticsearch,winstonewert/elasticsearch,wenpos/elasticsearch,nknize/elasticsearch,camilojd/elasticsearch,mortonsykes/elasticsearch,elasticdog/elasticsearch,jpountz/elasticsearch,rajanm/elasticsearch,qwerty4030/elasticsearch,obourgain/elasticsearch,JSCooke/elasticsearch,markwalkom/elasticsearch,qwerty4030/elasticsearch,wenpos/elasticsearch,yynil/elasticsearch,clintongormley/elasticsearch,fred84/elasticsearch,scottsom/elasticsearch,sreeramjayan/elasticsearch,vroyer/elassandra,strapdata/elassandra5-rc,myelin/elasticsearch,s1monw/elasticsearch,clintongormley/elasticsearch,jchampion/elasticsearch,winstonewert/elasticsearch,ESamir/elasticsearch,ESamir/elasticsearch,MisterAndersen/elasticsearch,davidvgalbraith/elasticsearch,JackyMai/elasticsearch,strapdata/elassandra,jprante/elasticsearch,scorpionvicky/elasticsearch,mjason3/elasticsearch,masaruh/elasticsearch,Helen-Zhao/elasticsearch,camilojd/elasticsearch,yynil/elasticsearch,gmarz/elasticsearch,liweinan0423/elasticsearch,episerver/elasticsearch,StefanGor/elasticsearch,cwurm/elasticsearch,jimczi/elasticsearch,IanvsPoplicola/elasticsearch,markharwood/elasticsearch,xuzha/elasticsearch,ThiagoGarciaAlves/elasticsearch,glefloch/elasticsearch,sneivandt/elasticsearch,nilabhsagar/elasticsearch,LewayneNaidoo/elasticsearch,jprante/elasticsearch,Stacey-Gammon/elasticsearch,nomoa/elasticsearch,zkidkid/elasticsearch,clintongormley/elasticsearch,episerver/elasticsearch,jbertouch/elasticsearch,winstonewert/elasticsearch,markharwood/elasticsearch,geidies/elasticsearch,diendt/elasticsearch,bawse/elasticsearch,mapr/elasticsearch,GlenRSmith/elasticsearch,gmarz/elasticsearch,liweinan0423/elasticsearch,mapr/elasticsearch,xuzha/elasticsearch,njlawton/elasticsearch,dongjoon-hyun/elasticsearch,gmarz/elasticsearch,masaruh/elasticsearch,jimczi/elasticsearch,gfyoung/elasticsearch,jimczi/elasticsearch,nilabhsagar/elasticsearch,gingerwizard/elasticsearch,davidvgalbraith/elasticsearch,strapdata/elassandra5-rc,jpountz/elasticsearch,maddin2016/elasticsearch,maddin2016/elasticsearch,jbertouch/elasticsearch,brandonkearby/elasticsearch,palecur/elasticsearch,LeoYao/elasticsearch,pozhidaevak/elasticsearch,IanvsPoplicola/elasticsearch,LeoYao/elasticsearch,Shepard1212/elasticsearch,Shepard1212/elasticsearch,kalimatas/elasticsearch,JackyMai/elasticsearch,nezirus/elasticsearch,gingerwizard/elasticsearch,nknize/elasticsearch,jbertouch/elasticsearch,umeshdangat/elasticsearch,alexshadow007/elasticsearch,tebriel/elasticsearch,zkidkid/elasticsearch,camilojd/elasticsearch,jbertouch/elasticsearch,coding0011/elasticsearch,nknize/elasticsearch,episerver/elasticsearch,sreeramjayan/elasticsearch,nazarewk/elasticsearch,vroyer/elassandra,umeshdangat/elasticsearch,sreeramjayan/elasticsearch,JackyMai/elasticsearch,shreejay/elasticsearch,cwurm/elasticsearch,markwalkom/elasticsearch,bawse/elasticsearch,LewayneNaidoo/elasticsearch,strapdata/elassandra5-rc,liweinan0423/elasticsearch,sneivandt/elasticsearch,pozhidaevak/elasticsearch,elasticdog/elasticsearch,nomoa/elasticsearch,girirajsharma/elasticsearch,xuzha/elasticsearch,MaineC/elasticsearch,ricardocerq/elasticsearch,MisterAndersen/elasticsearch,diendt/elasticsearch,fernandozhu/elasticsearch,robin13/elasticsearch,gingerwizard/elasticsearch,JervyShi/elasticsearch,trangvh/elasticsearch,mapr/elasticsearch,kalimatas/elasticsearch,vroyer/elasticassandra,mikemccand/elasticsearch,markwalkom/elasticsearch,fernandozhu/elasticsearch,nazarewk/elasticsearch,robin13/elasticsearch,dongjoon-hyun/elasticsearch,nazarewk/elasticsearch,umeshdangat/elasticsearch,artnowo/elasticsearch,JervyShi/elasticsearch,artnowo/elasticsearch,palecur/elasticsearch,geidies/elasticsearch,StefanGor/elasticsearch,nknize/elasticsearch,nilabhsagar/elasticsearch,nknize/elasticsearch,glefloch/elasticsearch,i-am-Nathan/elasticsearch,girirajsharma/elasticsearch,episerver/elasticsearch,StefanGor/elasticsearch,strapdata/elassandra,henakamaMSFT/elasticsearch,fred84/elasticsearch,wangtuo/elasticsearch,pozhidaevak/elasticsearch,scorpionvicky/elasticsearch,JSCooke/elasticsearch,strapdata/elassandra,markharwood/elasticsearch,markharwood/elasticsearch,scottsom/elasticsearch,LewayneNaidoo/elasticsearch,markwalkom/elasticsearch,Helen-Zhao/elasticsearch,yynil/elasticsearch,ESamir/elasticsearch,i-am-Nathan/elasticsearch,markharwood/elasticsearch,nazarewk/elasticsearch,rajanm/elasticsearch,IanvsPoplicola/elasticsearch,ThiagoGarciaAlves/elasticsearch,shreejay/elasticsearch,JSCooke/elasticsearch,mohit/elasticsearch,palecur/elasticsearch,wenpos/elasticsearch,lks21c/elasticsearch,girirajsharma/elasticsearch,tebriel/elasticsearch,HonzaKral/elasticsearch,nezirus/elasticsearch,spiegela/elasticsearch,nazarewk/elasticsearch,s1monw/elasticsearch,umeshdangat/elasticsearch,JSCooke/elasticsearch,davidvgalbraith/elasticsearch,sneivandt/elasticsearch,yynil/elasticsearch,jchampion/elasticsearch,ZTE-PaaS/elasticsearch,MaineC/elasticsearch,qwerty4030/elasticsearch,JSCooke/elasticsearch,LeoYao/elasticsearch,fforbeck/elasticsearch,robin13/elasticsearch,mjason3/elasticsearch,nomoa/elasticsearch,mmaracic/elasticsearch,GlenRSmith/elasticsearch,awislowski/elasticsearch,trangvh/elasticsearch,mjason3/elasticsearch,a2lin/elasticsearch,fernandozhu/elasticsearch,artnowo/elasticsearch,uschindler/elasticsearch,uschindler/elasticsearch,mortonsykes/elasticsearch,mjason3/elasticsearch,njlawton/elasticsearch,liweinan0423/elasticsearch,mohit/elasticsearch,robin13/elasticsearch,wangtuo/elasticsearch,rlugojr/elasticsearch,robin13/elasticsearch,ricardocerq/elasticsearch,jprante/elasticsearch,mmaracic/elasticsearch,jpountz/elasticsearch,lks21c/elasticsearch,LeoYao/elasticsearch,wuranbo/elasticsearch,jimczi/elasticsearch | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you 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 org.elasticsearch.repositories.hdfs;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.AbstractFileSystem;
import org.apache.hadoop.fs.FileContext;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.security.UserGroupInformation;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ElasticsearchGenerationException;
import org.elasticsearch.SpecialPermission;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.SuppressForbidden;
import org.elasticsearch.common.blobstore.BlobPath;
import org.elasticsearch.common.blobstore.BlobStore;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.io.PathUtils;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.index.snapshots.IndexShardRepository;
import org.elasticsearch.repositories.RepositoryName;
import org.elasticsearch.repositories.RepositorySettings;
import org.elasticsearch.repositories.blobstore.BlobStoreRepository;
public final class HdfsRepository extends BlobStoreRepository implements FileContextFactory {
private final BlobPath basePath;
private final ByteSizeValue chunkSize;
private final boolean compress;
private final RepositorySettings repositorySettings;
private final String path;
private final String uri;
private FileContext fc;
private HdfsBlobStore blobStore;
@Inject
public HdfsRepository(RepositoryName name, RepositorySettings repositorySettings, IndexShardRepository indexShardRepository) throws IOException {
super(name.getName(), repositorySettings, indexShardRepository);
this.repositorySettings = repositorySettings;
uri = repositorySettings.settings().get("uri", settings.get("uri"));
path = repositorySettings.settings().get("path", settings.get("path"));
this.basePath = BlobPath.cleanPath();
this.chunkSize = repositorySettings.settings().getAsBytesSize("chunk_size", settings.getAsBytesSize("chunk_size", null));
this.compress = repositorySettings.settings().getAsBoolean("compress", settings.getAsBoolean("compress", false));
}
@Override
protected void doStart() {
if (!Strings.hasText(uri)) {
throw new IllegalArgumentException("No 'uri' defined for hdfs snapshot/restore");
}
URI actualUri = URI.create(uri);
String scheme = actualUri.getScheme();
if (!Strings.hasText(scheme) || !scheme.toLowerCase(Locale.ROOT).equals("hdfs")) {
throw new IllegalArgumentException(
String.format(Locale.ROOT, "Invalid scheme [%s] specified in uri [%s]; only 'hdfs' uri allowed for hdfs snapshot/restore", scheme, uri));
}
String p = actualUri.getPath();
if (Strings.hasText(p) && !p.equals("/")) {
throw new IllegalArgumentException(String.format(Locale.ROOT,
"Use 'path' option to specify a path [%s], not the uri [%s] for hdfs snapshot/restore", p, uri));
}
// get configuration
if (path == null) {
throw new IllegalArgumentException("No 'path' defined for hdfs snapshot/restore");
}
try {
fc = getFileContext();
Path hdfsPath = SecurityUtils.execute(fc, new FcCallback<Path>() {
@Override
public Path doInHdfs(FileContext fc) throws IOException {
return fc.makeQualified(new Path(path));
}
});
logger.debug("Using file-system [{}] for URI [{}], path [{}]", fc.getDefaultFileSystem(), fc.getDefaultFileSystem().getUri(), hdfsPath);
blobStore = new HdfsBlobStore(settings, this, hdfsPath);
} catch (IOException e) {
throw new RuntimeException(e);
}
super.doStart();
}
// as the FileSystem is long-lived and might go away, make sure to check it before it's being used.
@Override
public FileContext getFileContext() throws IOException {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
// unprivileged code such as scripts do not have SpecialPermission
sm.checkPermission(new SpecialPermission());
}
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<FileContext>() {
@Override
public FileContext run() throws IOException {
return doGetFileContext();
}
});
} catch (PrivilegedActionException pae) {
throw (IOException) pae.getException();
}
}
private FileContext doGetFileContext() throws IOException {
// check if the fs is still alive
// make a cheap call that triggers little to no security checks
if (fc != null) {
try {
fc.util().exists(fc.getWorkingDirectory());
} catch (IOException ex) {
if (ex.getMessage().contains("Filesystem closed")) {
fc = null;
}
else {
throw ex;
}
}
}
if (fc == null) {
Thread th = Thread.currentThread();
ClassLoader oldCL = th.getContextClassLoader();
try {
th.setContextClassLoader(getClass().getClassLoader());
return initFileContext(repositorySettings);
} catch (IOException ex) {
throw ex;
} finally {
th.setContextClassLoader(oldCL);
}
}
return fc;
}
private FileContext initFileContext(RepositorySettings repositorySettings) throws IOException {
Configuration cfg = new Configuration(repositorySettings.settings().getAsBoolean("load_defaults", settings.getAsBoolean("load_defaults", true)));
cfg.setClassLoader(this.getClass().getClassLoader());
cfg.reloadConfiguration();
Map<String, String> map = repositorySettings.settings().getByPrefix("conf.").getAsMap();
for (Entry<String, String> entry : map.entrySet()) {
cfg.set(entry.getKey(), entry.getValue());
}
try {
UserGroupInformation.setConfiguration(cfg);
} catch (Throwable th) {
throw new ElasticsearchGenerationException(String.format(Locale.ROOT, "Cannot initialize Hadoop"), th);
}
URI actualUri = URI.create(uri);
try {
// disable FS cache
cfg.setBoolean("fs.hdfs.impl.disable.cache", true);
// create the AFS manually since through FileContext is relies on Subject.doAs for no reason at all
AbstractFileSystem fs = AbstractFileSystem.get(actualUri, cfg);
return FileContext.getFileContext(fs, cfg);
} catch (Exception ex) {
throw new ElasticsearchGenerationException(String.format(Locale.ROOT, "Cannot create Hdfs file-system for uri [%s]", actualUri), ex);
}
}
@Override
protected BlobStore blobStore() {
return blobStore;
}
@Override
protected BlobPath basePath() {
return basePath;
}
@Override
protected boolean isCompress() {
return compress;
}
@Override
protected ByteSizeValue chunkSize() {
return chunkSize;
}
@Override
protected void doClose() throws ElasticsearchException {
super.doClose();
// TODO: FileContext does not support any close - is there really no way
// to handle it?
fc = null;
}
}
| plugins/repository-hdfs/src/main/java/org/elasticsearch/repositories/hdfs/HdfsRepository.java | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you 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 org.elasticsearch.repositories.hdfs;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.AbstractFileSystem;
import org.apache.hadoop.fs.FileContext;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.security.UserGroupInformation;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ElasticsearchGenerationException;
import org.elasticsearch.SpecialPermission;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.SuppressForbidden;
import org.elasticsearch.common.blobstore.BlobPath;
import org.elasticsearch.common.blobstore.BlobStore;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.io.PathUtils;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.index.snapshots.IndexShardRepository;
import org.elasticsearch.repositories.RepositoryName;
import org.elasticsearch.repositories.RepositorySettings;
import org.elasticsearch.repositories.blobstore.BlobStoreRepository;
public final class HdfsRepository extends BlobStoreRepository implements FileContextFactory {
private final BlobPath basePath;
private final ByteSizeValue chunkSize;
private final boolean compress;
private final RepositorySettings repositorySettings;
private final String path;
private final String uri;
private FileContext fc;
private HdfsBlobStore blobStore;
@Inject
public HdfsRepository(RepositoryName name, RepositorySettings repositorySettings, IndexShardRepository indexShardRepository) throws IOException {
super(name.getName(), repositorySettings, indexShardRepository);
this.repositorySettings = repositorySettings;
uri = repositorySettings.settings().get("uri", settings.get("uri"));
path = repositorySettings.settings().get("path", settings.get("path"));
this.basePath = BlobPath.cleanPath();
this.chunkSize = repositorySettings.settings().getAsBytesSize("chunk_size", settings.getAsBytesSize("chunk_size", null));
this.compress = repositorySettings.settings().getAsBoolean("compress", settings.getAsBoolean("compress", false));
}
@Override
protected void doStart() {
if (!Strings.hasText(uri)) {
throw new IllegalArgumentException("No 'uri' defined for hdfs snapshot/restore");
}
URI actualUri = URI.create(uri);
String scheme = actualUri.getScheme();
if (!Strings.hasText(scheme) || !scheme.toLowerCase(Locale.ROOT).equals("hdfs")) {
throw new IllegalArgumentException(
String.format(Locale.ROOT, "Invalid scheme [%s] specified in uri [%s]; only 'hdfs' uri allowed for hdfs snapshot/restore", scheme, uri));
}
String p = actualUri.getPath();
if (Strings.hasText(p) && !p.equals("/")) {
throw new IllegalArgumentException(String.format(Locale.ROOT,
"Use 'path' option to specify a path [%s], not the uri [%s] for hdfs snapshot/restore", p, uri));
}
// get configuration
if (path == null) {
throw new IllegalArgumentException("No 'path' defined for hdfs snapshot/restore");
}
try {
fc = getFileContext();
Path hdfsPath = SecurityUtils.execute(fc, new FcCallback<Path>() {
@Override
public Path doInHdfs(FileContext fc) throws IOException {
return fc.makeQualified(new Path(path));
}
});
logger.debug("Using file-system [{}] for URI [{}], path [{}]", fc.getDefaultFileSystem(), fc.getDefaultFileSystem().getUri(), hdfsPath);
blobStore = new HdfsBlobStore(settings, this, hdfsPath);
} catch (IOException e) {
throw new RuntimeException(e);
}
super.doStart();
}
// as the FileSystem is long-lived and might go away, make sure to check it before it's being used.
@Override
public FileContext getFileContext() throws IOException {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
// unprivileged code such as scripts do not have SpecialPermission
sm.checkPermission(new SpecialPermission());
}
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<FileContext>() {
@Override
public FileContext run() throws IOException {
return doGetFileContext();
}
});
} catch (PrivilegedActionException pae) {
Throwable th = pae.getCause();
if (th instanceof Error) {
throw (Error) th;
}
if (th instanceof RuntimeException) {
throw (RuntimeException) th;
}
if (th instanceof IOException) {
throw (IOException) th;
}
throw new ElasticsearchException(pae);
}
}
private FileContext doGetFileContext() throws IOException {
// check if the fs is still alive
// make a cheap call that triggers little to no security checks
if (fc != null) {
try {
fc.util().exists(fc.getWorkingDirectory());
} catch (IOException ex) {
if (ex.getMessage().contains("Filesystem closed")) {
fc = null;
}
else {
throw ex;
}
}
}
if (fc == null) {
Thread th = Thread.currentThread();
ClassLoader oldCL = th.getContextClassLoader();
try {
th.setContextClassLoader(getClass().getClassLoader());
return initFileContext(repositorySettings);
} catch (IOException ex) {
throw ex;
} finally {
th.setContextClassLoader(oldCL);
}
}
return fc;
}
private FileContext initFileContext(RepositorySettings repositorySettings) throws IOException {
Configuration cfg = new Configuration(repositorySettings.settings().getAsBoolean("load_defaults", settings.getAsBoolean("load_defaults", true)));
cfg.setClassLoader(this.getClass().getClassLoader());
cfg.reloadConfiguration();
Map<String, String> map = repositorySettings.settings().getByPrefix("conf.").getAsMap();
for (Entry<String, String> entry : map.entrySet()) {
cfg.set(entry.getKey(), entry.getValue());
}
try {
UserGroupInformation.setConfiguration(cfg);
} catch (Throwable th) {
throw new ElasticsearchGenerationException(String.format(Locale.ROOT, "Cannot initialize Hadoop"), th);
}
URI actualUri = URI.create(uri);
try {
// disable FS cache
cfg.setBoolean("fs.hdfs.impl.disable.cache", true);
// create the AFS manually since through FileContext is relies on Subject.doAs for no reason at all
AbstractFileSystem fs = AbstractFileSystem.get(actualUri, cfg);
return FileContext.getFileContext(fs, cfg);
} catch (Exception ex) {
throw new ElasticsearchGenerationException(String.format(Locale.ROOT, "Cannot create Hdfs file-system for uri [%s]", actualUri), ex);
}
}
@Override
protected BlobStore blobStore() {
return blobStore;
}
@Override
protected BlobPath basePath() {
return basePath;
}
@Override
protected boolean isCompress() {
return compress;
}
@Override
protected ByteSizeValue chunkSize() {
return chunkSize;
}
@Override
protected void doClose() throws ElasticsearchException {
super.doClose();
// TODO: FileContext does not support any close - is there really no way
// to handle it?
fc = null;
}
}
| fix exc handling
| plugins/repository-hdfs/src/main/java/org/elasticsearch/repositories/hdfs/HdfsRepository.java | fix exc handling | |
Java | apache-2.0 | 65609ff39d66e8215586388427e2b6a935db4073 | 0 | opennetworkinglab/onos,maheshraju-Huawei/actn,oplinkoms/onos,opennetworkinglab/onos,oplinkoms/onos,maheshraju-Huawei/actn,osinstom/onos,y-higuchi/onos,kuujo/onos,Shashikanth-Huawei/bmp,y-higuchi/onos,gkatsikas/onos,gkatsikas/onos,oplinkoms/onos,y-higuchi/onos,maheshraju-Huawei/actn,sdnwiselab/onos,donNewtonAlpha/onos,kuujo/onos,mengmoya/onos,LorenzReinhart/ONOSnew,sdnwiselab/onos,kuujo/onos,Shashikanth-Huawei/bmp,opennetworkinglab/onos,gkatsikas/onos,osinstom/onos,sonu283304/onos,kuujo/onos,oplinkoms/onos,sdnwiselab/onos,y-higuchi/onos,VinodKumarS-Huawei/ietf96yang,planoAccess/clonedONOS,lsinfo3/onos,oplinkoms/onos,mengmoya/onos,osinstom/onos,osinstom/onos,sdnwiselab/onos,opennetworkinglab/onos,gkatsikas/onos,donNewtonAlpha/onos,VinodKumarS-Huawei/ietf96yang,kuujo/onos,y-higuchi/onos,sdnwiselab/onos,opennetworkinglab/onos,Shashikanth-Huawei/bmp,oplinkoms/onos,lsinfo3/onos,kuujo/onos,planoAccess/clonedONOS,mengmoya/onos,LorenzReinhart/ONOSnew,sdnwiselab/onos,osinstom/onos,VinodKumarS-Huawei/ietf96yang,LorenzReinhart/ONOSnew,donNewtonAlpha/onos,sonu283304/onos,maheshraju-Huawei/actn,VinodKumarS-Huawei/ietf96yang,planoAccess/clonedONOS,mengmoya/onos,Shashikanth-Huawei/bmp,mengmoya/onos,planoAccess/clonedONOS,sonu283304/onos,donNewtonAlpha/onos,lsinfo3/onos,LorenzReinhart/ONOSnew,gkatsikas/onos,lsinfo3/onos,opennetworkinglab/onos,kuujo/onos,gkatsikas/onos,oplinkoms/onos,Shashikanth-Huawei/bmp,donNewtonAlpha/onos,LorenzReinhart/ONOSnew,VinodKumarS-Huawei/ietf96yang,maheshraju-Huawei/actn,sonu283304/onos | /*
* Copyright 2015 Open Networking Laboratory
*
* 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 org.onosproject.ovsdb.provider.host;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.onlab.util.Tools.toHex;
import static org.slf4j.LoggerFactory.getLogger;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.Service;
import org.onlab.packet.VlanId;
import org.onosproject.core.CoreService;
import org.onosproject.net.DefaultAnnotations;
import org.onosproject.net.DeviceId;
import org.onosproject.net.Host;
import org.onosproject.net.HostId;
import org.onosproject.net.HostLocation;
import org.onosproject.net.PortNumber;
import org.onosproject.net.SparseAnnotations;
import org.onosproject.net.host.DefaultHostDescription;
import org.onosproject.net.host.HostDescription;
import org.onosproject.net.host.HostProvider;
import org.onosproject.net.host.HostProviderRegistry;
import org.onosproject.net.host.HostProviderService;
import org.onosproject.net.host.HostService;
import org.onosproject.net.provider.AbstractProvider;
import org.onosproject.net.provider.ProviderId;
import org.onosproject.ovsdb.controller.EventSubject;
import org.onosproject.ovsdb.controller.OvsdbController;
import org.onosproject.ovsdb.controller.OvsdbEvent;
import org.onosproject.ovsdb.controller.OvsdbEventListener;
import org.onosproject.ovsdb.controller.OvsdbEventSubject;
import org.slf4j.Logger;
/**
* Provider which uses an ovsdb controller to detect host.
*/
@Component(immediate = true)
@Service
public class OvsdbHostProvider extends AbstractProvider implements HostProvider {
private final Logger log = getLogger(getClass());
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected HostProviderRegistry providerRegistry;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected HostService hostService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected CoreService coreService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected OvsdbController controller;
private HostProviderService providerService;
private OvsdbEventListener innerEventListener = new InnerOvsdbEventListener();
@Activate
public void activate() {
providerService = providerRegistry.register(this);
controller.addOvsdbEventListener(innerEventListener);
log.info("Started");
}
@Deactivate
public void deactivate() {
providerRegistry.unregister(this);
providerService = null;
log.info("Stopped");
}
public OvsdbHostProvider() {
super(new ProviderId("ovsdb", "org.onosproject.ovsdb.provider.host"));
}
@Override
public void triggerProbe(Host host) {
log.info("Triggering probe on host {}", host);
}
private class InnerOvsdbEventListener implements OvsdbEventListener {
@Override
public void handle(OvsdbEvent<EventSubject> event) {
OvsdbEventSubject subject = null;
if (event.subject() instanceof OvsdbEventSubject) {
subject = (OvsdbEventSubject) event.subject();
}
checkNotNull(subject, "EventSubject is not null");
// If ifaceid is null,it indicates this is not a vm port.
if (subject.ifaceid() == null) {
return;
}
switch (event.type()) {
case PORT_ADDED:
HostId hostId = HostId.hostId(subject.hwAddress(), VlanId.vlanId());
DeviceId deviceId = DeviceId.deviceId(uri(subject.dpid().value()));
PortNumber portNumber = PortNumber.portNumber(subject
.portNumber().value(), subject.portName().value());
HostLocation loaction = new HostLocation(deviceId, portNumber,
0L);
SparseAnnotations annotations = DefaultAnnotations.builder()
.set("ifaceid", subject.ifaceid().value()).build();
HostDescription hostDescription = new DefaultHostDescription(
subject.hwAddress(),
VlanId.vlanId(),
loaction,
annotations);
providerService.hostDetected(hostId, hostDescription);
break;
case PORT_REMOVED:
HostId host = HostId.hostId(subject.hwAddress(), VlanId.vlanId());
providerService.hostVanished(host);
break;
default:
break;
}
}
}
public URI uri(String value) {
try {
return new URI("of", toHex(Long.valueOf(value)), null);
} catch (URISyntaxException e) {
return null;
}
}
}
| providers/ovsdb/host/src/main/java/org/onosproject/ovsdb/provider/host/OvsdbHostProvider.java | /*
* Copyright 2015 Open Networking Laboratory
*
* 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 org.onosproject.ovsdb.provider.host;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.onlab.util.Tools.toHex;
import static org.slf4j.LoggerFactory.getLogger;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.Service;
import org.onlab.packet.VlanId;
import org.onosproject.core.CoreService;
import org.onosproject.net.DefaultAnnotations;
import org.onosproject.net.DeviceId;
import org.onosproject.net.Host;
import org.onosproject.net.HostId;
import org.onosproject.net.HostLocation;
import org.onosproject.net.PortNumber;
import org.onosproject.net.SparseAnnotations;
import org.onosproject.net.host.DefaultHostDescription;
import org.onosproject.net.host.HostDescription;
import org.onosproject.net.host.HostProvider;
import org.onosproject.net.host.HostProviderRegistry;
import org.onosproject.net.host.HostProviderService;
import org.onosproject.net.host.HostService;
import org.onosproject.net.provider.AbstractProvider;
import org.onosproject.net.provider.ProviderId;
import org.onosproject.ovsdb.controller.EventSubject;
import org.onosproject.ovsdb.controller.OvsdbController;
import org.onosproject.ovsdb.controller.OvsdbEvent;
import org.onosproject.ovsdb.controller.OvsdbEventListener;
import org.onosproject.ovsdb.controller.OvsdbEventSubject;
import org.slf4j.Logger;
/**
* Provider which uses an ovsdb controller to detect host.
*/
@Component(immediate = true)
@Service
public class OvsdbHostProvider extends AbstractProvider implements HostProvider {
private final Logger log = getLogger(getClass());
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected HostProviderRegistry providerRegistry;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected HostService hostService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected CoreService coreService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected OvsdbController controller;
private HostProviderService providerService;
private OvsdbEventListener innerEventListener = new InnerOvsdbEventListener();
@Activate
public void activate() {
providerService = providerRegistry.register(this);
controller.addOvsdbEventListener(innerEventListener);
log.info("Started");
}
@Deactivate
public void deactivate() {
providerRegistry.unregister(this);
providerService = null;
log.info("Stopped");
}
public OvsdbHostProvider() {
super(new ProviderId("ovsdb", "org.onosproject.ovsdb.provider.host"));
}
@Override
public void triggerProbe(Host host) {
log.info("Triggering probe on host {}", host);
}
private class InnerOvsdbEventListener implements OvsdbEventListener {
@Override
public void handle(OvsdbEvent<EventSubject> event) {
OvsdbEventSubject subject = null;
if (event.subject() instanceof OvsdbEventSubject) {
subject = (OvsdbEventSubject) event.subject();
}
checkNotNull(subject, "EventSubject is not null");
// If ifaceid is null,it indicates this is not a vm port.
if (subject.ifaceid() == null) {
return;
}
switch (event.type()) {
case PORT_ADDED:
HostId hostId = HostId.hostId(subject.hwAddress(), null);
DeviceId deviceId = DeviceId.deviceId(uri(subject.dpid().value()));
PortNumber portNumber = PortNumber.portNumber(subject
.portNumber().value(), subject.portName().value());
HostLocation loaction = new HostLocation(deviceId, portNumber,
0L);
SparseAnnotations annotations = DefaultAnnotations.builder()
.set("ifaceid", subject.ifaceid().value()).build();
HostDescription hostDescription = new DefaultHostDescription(
subject.hwAddress(),
VlanId.vlanId(),
loaction,
annotations);
providerService.hostDetected(hostId, hostDescription);
break;
case PORT_REMOVED:
HostId host = HostId.hostId(subject.hwAddress(), null);
providerService.hostVanished(host);
break;
default:
break;
}
}
}
public URI uri(String value) {
try {
return new URI("of", toHex(Long.valueOf(value)), null);
} catch (URISyntaxException e) {
return null;
}
}
}
| ONOS-3236 Ovsdb host's vlanid is null,it should be the default value -1.
Change-Id: Ibf1739df674d7a8ecea27496fac870dcc384b3e2
| providers/ovsdb/host/src/main/java/org/onosproject/ovsdb/provider/host/OvsdbHostProvider.java | ONOS-3236 Ovsdb host's vlanid is null,it should be the default value -1. | |
Java | apache-2.0 | 1994a8dee5e44e4dcb110a6db401db9689badccb | 0 | apigee/astyanax,Netflix/astyanax,gorcz/astyanax,DavidHerzogTU-Berlin/astyanax,fengshao0907/astyanax,bazaarvoice/astyanax,DavidHerzogTU-Berlin/astyanax,DavidHerzogTU-Berlin/astyanax,gorcz/astyanax,fengshao0907/astyanax,Netflix/astyanax,apigee/astyanax,maxtomassi/ds-astyanax,Netflix/astyanax,maxtomassi/ds-astyanax,bazaarvoice/astyanax | /*******************************************************************************
* Copyright 2011 Netflix
*
* 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.netflix.astyanax.thrift;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.apache.cassandra.thrift.KeyRange;
import org.apache.cassandra.thrift.KeySlice;
import org.apache.commons.lang.NotImplementedException;
import com.google.common.collect.Iterables;
import com.netflix.astyanax.model.ColumnFamily;
import com.netflix.astyanax.model.Row;
import com.netflix.astyanax.model.Rows;
import com.netflix.astyanax.partitioner.Partitioner;
import com.netflix.astyanax.thrift.model.ThriftColumnOrSuperColumnListImpl;
import com.netflix.astyanax.thrift.model.ThriftRowImpl;
public class ThriftAllRowsImpl<K, C> implements Rows<K, C> {
private ColumnFamily<K, C> columnFamily;
private ThriftAllRowsQueryImpl<K, C> query;
private final Partitioner partitioner;
public ThriftAllRowsImpl(Partitioner partitioner, ThriftAllRowsQueryImpl<K, C> query, ColumnFamily<K, C> columnFamily) {
this.columnFamily = columnFamily;
this.query = query;
this.partitioner = partitioner;
}
/**
* Each call to .iterator() returns a new context starting at the beginning
* of the column family.
*/
@Override
public Iterator<Row<K, C>> iterator() {
return new Iterator<Row<K, C>>() {
private KeyRange range;
private org.apache.cassandra.thrift.KeySlice lastRow;
private List<org.apache.cassandra.thrift.KeySlice> list = null;
private Iterator<org.apache.cassandra.thrift.KeySlice> iter = null;
private boolean bContinueSearch = true;
private boolean bIgnoreTombstones = true;
{
String startToken = query.getStartToken() == null ? partitioner.getMinToken() : query.getStartToken();
String endToken = query.getEndToken() == null ? partitioner.getMaxToken() : query.getEndToken();
range = new KeyRange()
.setCount(query.getBlockSize())
.setStart_token(startToken)
.setEnd_token(endToken);
if (query.getIncludeEmptyRows() == null) {
if (query.getPredicate().isSetSlice_range() && query.getPredicate().getSlice_range().getCount() == 0) {
bIgnoreTombstones = false;
}
}
else {
bIgnoreTombstones = !query.getIncludeEmptyRows();
}
}
@Override
public boolean hasNext() {
// Get the next block
while (iter == null || (!iter.hasNext() && bContinueSearch)) {
if (lastRow != null) {
// Determine the start token for the next page
String token = partitioner.getTokenForKey(ByteBuffer.wrap(lastRow.getKey()));
if (query.getRepeatLastToken()) {
// Start token is non-inclusive
range.setStart_token(partitioner.getTokenMinusOne(token));
}
else {
range.setStart_token(token);
}
}
// Get the next block of rows from cassandra, exit if none returned
list = query.getNextBlock(range);
if (list == null || list.isEmpty()) {
return false;
}
// Since we may trim tombstones set a flag indicating whether a complete
// block was returned so we can know to try to fetch the next one
bContinueSearch = (list.size() == query.getBlockSize());
// Trim the list from tombstoned rows, i.e. rows with no columns
iter = list.iterator();
if (iter == null || !iter.hasNext()) {
return false;
}
KeySlice previousLastRow = lastRow;
lastRow = Iterables.getLast(list);
if (query.getRepeatLastToken() && previousLastRow != null) {
iter.next();
iter.remove();
}
if (iter.hasNext() && bIgnoreTombstones) {
// Discard any tombstones
while (iter.hasNext()) {
KeySlice row = iter.next();
if (row.getColumns().isEmpty()) {
iter.remove();
}
}
// Get the iterator again
iter = list.iterator();
}
}
return iter.hasNext();
}
@Override
public Row<K, C> next() {
org.apache.cassandra.thrift.KeySlice row = iter.next();
return new ThriftRowImpl<K, C>(columnFamily.getKeySerializer().fromBytes(row.getKey()),
ByteBuffer.wrap(row.getKey()), new ThriftColumnOrSuperColumnListImpl<C>(row.getColumns(),
columnFamily.getColumnSerializer()));
}
@Override
public void remove() {
throw new IllegalStateException();
}
};
}
@Override
public Row<K, C> getRow(K key) {
throw new NotImplementedException("Only iterator based access is implemented");
}
@Override
public int size() {
throw new NotImplementedException("Only iterator based access is implemented");
}
@Override
public boolean isEmpty() {
throw new NotImplementedException("Only iterator based access is implemented");
}
@Override
public Row<K, C> getRowByIndex(int i) {
throw new NotImplementedException("Only iterator based access is implemented");
}
@Override
public Collection<K> getKeys() {
throw new NotImplementedException("Only iterator based access is implemented");
}
}
| astyanax-thrift/src/main/java/com/netflix/astyanax/thrift/ThriftAllRowsImpl.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* 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.netflix.astyanax.thrift;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.apache.cassandra.thrift.KeyRange;
import org.apache.cassandra.thrift.KeySlice;
import org.apache.commons.lang.NotImplementedException;
import com.google.common.collect.Iterables;
import com.netflix.astyanax.model.ColumnFamily;
import com.netflix.astyanax.model.Row;
import com.netflix.astyanax.model.Rows;
import com.netflix.astyanax.partitioner.Partitioner;
import com.netflix.astyanax.thrift.model.ThriftColumnOrSuperColumnListImpl;
import com.netflix.astyanax.thrift.model.ThriftRowImpl;
public class ThriftAllRowsImpl<K, C> implements Rows<K, C> {
private ColumnFamily<K, C> columnFamily;
private ThriftAllRowsQueryImpl<K, C> query;
private final Partitioner partitioner;
public ThriftAllRowsImpl(Partitioner partitioner, ThriftAllRowsQueryImpl<K, C> query, ColumnFamily<K, C> columnFamily) {
this.columnFamily = columnFamily;
this.query = query;
this.partitioner = partitioner;
}
/**
* Each call to .iterator() returns a new context starting at the beginning
* of the column family.
*/
@Override
public Iterator<Row<K, C>> iterator() {
return new Iterator<Row<K, C>>() {
private KeyRange range;
private org.apache.cassandra.thrift.KeySlice lastRow;
private List<org.apache.cassandra.thrift.KeySlice> list = null;
private Iterator<org.apache.cassandra.thrift.KeySlice> iter = null;
private boolean bContinueSearch = true;
private boolean bIgnoreTombstones = true;
{
String startToken = query.getStartToken() == null ? partitioner.getMinToken() : query.getStartToken();
String endToken = query.getEndToken() == null ? partitioner.getMaxToken() : query.getEndToken();
range = new KeyRange()
.setCount(query.getBlockSize())
.setStart_token(startToken)
.setEnd_token(endToken);
if (query.getIncludeEmptyRows() == null) {
if (query.getPredicate().isSetSlice_range() && query.getPredicate().getSlice_range().getCount() == 0) {
bIgnoreTombstones = false;
}
}
else {
bIgnoreTombstones = !query.getIncludeEmptyRows();
}
}
@Override
public boolean hasNext() {
// Get the next block
while (iter == null || (!iter.hasNext() && bContinueSearch)) {
if (lastRow != null) {
// Determine the start token for the next page
String token = partitioner.getTokenForKey(ByteBuffer.wrap(lastRow.getKey()));
if (query.getRepeatLastToken()) {
// Start token is non-inclusive
range.setStart_token(partitioner.getTokenMinusOne(token));
}
else {
range.setStart_token(token);
}
}
// Get the next block of rows from cassandra, exit if none returned
list = query.getNextBlock(range);
if (list == null || list.isEmpty()) {
return false;
}
// Since we may trim tombstones set a flag indicating whether a complete
// block was returned so we can know to try to fetch the next one
bContinueSearch = (list.size() == query.getBlockSize());
// Trim the list from tombstoned rows, i.e. rows with no columns
iter = list.iterator();
if (iter == null || !iter.hasNext()) {
return false;
}
KeySlice previousLastRow = lastRow;
lastRow = Iterables.getLast(list);
if (query.getRepeatLastToken() && previousLastRow != null) {
iter.next();
iter.remove();
}
if (iter.hasNext() && bIgnoreTombstones) {
// Discard any tombstones
while (iter.hasNext()) {
KeySlice row = iter.next();
if (row.getColumns().isEmpty()) {
iter.remove();
}
}
// Get the iterator again
iter = list.iterator();
}
}
return iter.hasNext();
}
@Override
public Row<K, C> next() {
org.apache.cassandra.thrift.KeySlice row = iter.next();
return new ThriftRowImpl<K, C>(columnFamily.getKeySerializer().fromBytes(row.getKey()),
ByteBuffer.wrap(row.getKey()), new ThriftColumnOrSuperColumnListImpl<C>(row.getColumns(),
columnFamily.getColumnSerializer()));
}
@Override
public void remove() {
throw new IllegalStateException();
}
};
}
@Override
public Row<K, C> getRow(K key) {
throw new NotImplementedException("Use the iterator interface instead");
}
@Override
public int size() {
throw new NotImplementedException("Use the iterator interface instead");
}
@Override
public boolean isEmpty() {
throw new NotImplementedException("Use the iterator interface instead");
}
@Override
public Row<K, C> getRowByIndex(int i) {
throw new NotImplementedException("Use the iterator interface instead");
}
@Override
public Collection<K> getKeys() {
throw new NotImplementedException("Use the iterator interface instead");
}
}
| Adding in better explanation for not implementing the non-iterator style interface in AllRowsQuery
| astyanax-thrift/src/main/java/com/netflix/astyanax/thrift/ThriftAllRowsImpl.java | Adding in better explanation for not implementing the non-iterator style interface in AllRowsQuery | |
Java | apache-2.0 | 163180787fdff39893b499717bba7558f845f41e | 0 | aosp-mirror/platform_frameworks_support,androidx/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,androidx/androidx,aosp-mirror/platform_frameworks_support,androidx/androidx,androidx/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx | /*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.v4.widget;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Transformation;
import android.widget.AbsListView;
/**
* The SwipeRefreshLayout should be used whenever the user can refresh the
* contents of a view via a vertical swipe gesture. The activity that
* instantiates this view should add an OnRefreshListener to be notified
* whenever the swipe to refresh gesture is completed. The SwipeRefreshLayout
* will notify the listener each and every time the gesture is completed again;
* the listener is responsible for correctly determining when to actually
* initiate a refresh of its content. If the listener determines there should
* not be a refresh, it must call setRefreshing(false) to cancel any visual
* indication of a refresh. If an activity wishes to show just the progress
* animation, it should call setRefreshing(true). To disable the gesture and
* progress animation, call setEnabled(false) on the view.
* <p>
* This layout should be made the parent of the view that will be refreshed as a
* result of the gesture and can only support one direct child. This view will
* also be made the target of the gesture and will be forced to match both the
* width and the height supplied in this layout. The SwipeRefreshLayout does not
* provide accessibility events; instead, a menu item must be provided to allow
* refresh of the content wherever this gesture is used.
* </p>
*/
public class SwipeRefreshLayout extends ViewGroup {
// Maps to ProgressBar.Large style
public static final int LARGE = MaterialProgressDrawable.LARGE;
// Maps to ProgressBar default style
public static final int DEFAULT = MaterialProgressDrawable.DEFAULT;
private static final String LOG_TAG = SwipeRefreshLayout.class.getSimpleName();
private static final int MAX_ALPHA = 255;
private static final int STARTING_PROGRESS_ALPHA = (int) (.3f * MAX_ALPHA);
private static final int CIRCLE_DIAMETER = 40;
private static final int CIRCLE_DIAMETER_LARGE = 56;
private static final float DECELERATE_INTERPOLATION_FACTOR = 2f;
private static final int INVALID_POINTER = -1;
private static final float DRAG_RATE = .5f;
// Max amount of circle that can be filled by progress during swipe gesture,
// where 1.0 is a full circle
private static final float MAX_PROGRESS_ANGLE = .8f;
private static final int SCALE_DOWN_DURATION = 150;
private static final int ALPHA_ANIMATION_DURATION = 300;
private static final int ANIMATE_TO_TRIGGER_DURATION = 200;
private static final int ANIMATE_TO_START_DURATION = 200;
// Default background for the progress spinner
private static final int CIRCLE_BG_LIGHT = 0xFFFAFAFA;
// Default offset in dips from the top of the view to where the progress spinner should stop
private static final int DEFAULT_CIRCLE_TARGET = 64;
private View mTarget; // the target of the gesture
private OnRefreshListener mListener;
private boolean mRefreshing = false;
private int mTouchSlop;
private float mTotalDragDistance = -1;
private int mMediumAnimationDuration;
private int mCurrentTargetOffsetTop;
// Whether or not the starting offset has been determined.
private boolean mOriginalOffsetCalculated = false;
private float mInitialMotionY;
private boolean mIsBeingDragged;
private int mActivePointerId = INVALID_POINTER;
// Whether this item is scaled up rather than clipped
private boolean mScale;
// Target is returning to its start offset because it was cancelled or a
// refresh was triggered.
private boolean mReturningToStart;
private final DecelerateInterpolator mDecelerateInterpolator;
private static final int[] LAYOUT_ATTRS = new int[] {
android.R.attr.enabled
};
private CircleImageView mCircleView;
private int mCircleViewIndex = -1;
protected int mFrom;
private float mStartingScale;
protected int mOriginalOffsetTop;
private MaterialProgressDrawable mProgress;
private Animation mScaleAnimation;
private Animation mScaleDownAnimation;
private Animation mAlphaStartAnimation;
private Animation mAlphaMaxAnimation;
private Animation mScaleDownToStartAnimation;
private float mSpinnerFinalOffset;
private boolean mNotify;
private int mCircleWidth;
private int mCircleHeight;
// Whether the client has set a custom starting position;
private boolean mUsingCustomStart;
private Animation.AnimationListener mRefreshListener = new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
if (mRefreshing) {
// Make sure the progress view is fully visible
mProgress.setAlpha(MAX_ALPHA);
mProgress.start();
if (mNotify) {
if (mListener != null) {
mListener.onRefresh();
}
}
} else {
mProgress.stop();
mCircleView.setVisibility(View.GONE);
setColorViewAlpha(MAX_ALPHA);
// Return the circle to its start position
if (mScale) {
setAnimationProgress(0 /* animation complete and view is hidden */);
} else {
setTargetOffsetTopAndBottom(mOriginalOffsetTop - mCurrentTargetOffsetTop,
true /* requires update */);
}
}
mCurrentTargetOffsetTop = mCircleView.getTop();
}
};
private void setColorViewAlpha(int targetAlpha) {
mCircleView.getBackground().setAlpha(targetAlpha);
mProgress.setAlpha(targetAlpha);
}
/**
* The refresh indicator starting and resting position is always positioned
* near the top of the refreshing content. This position is a consistent
* location, but can be adjusted in either direction based on whether or not
* there is a toolbar or actionbar present.
*
* @param scale Set to true if there is no view at a higher z-order than
* where the progress spinner is set to appear.
* @param start The offset in pixels from the top of this view at which the
* progress spinner should appear.
* @param end The offset in pixels from the top of this view at which the
* progress spinner should come to rest after a successful swipe
* gesture.
*/
public void setProgressViewOffset(boolean scale, int start, int end) {
mScale = scale;
mCircleView.setVisibility(View.GONE);
mOriginalOffsetTop = mCurrentTargetOffsetTop = start;
mSpinnerFinalOffset = end;
mUsingCustomStart = true;
mCircleView.invalidate();
}
/**
* The refresh indicator resting position is always positioned near the top
* of the refreshing content. This position is a consistent location, but
* can be adjusted in either direction based on whether or not there is a
* toolbar or actionbar present.
*
* @param scale Set to true if there is no view at a higher z-order than
* where the progress spinner is set to appear.
* @param end The offset in pixels from the top of this view at which the
* progress spinner should come to rest after a successful swipe
* gesture.
*/
public void setProgressViewEndTarget(boolean scale, int end) {
mSpinnerFinalOffset = end;
mScale = scale;
mCircleView.invalidate();
}
/**
* One of DEFAULT, or LARGE.
*/
public void setSize(int size) {
if (size != MaterialProgressDrawable.LARGE && size != MaterialProgressDrawable.DEFAULT) {
return;
}
final DisplayMetrics metrics = getResources().getDisplayMetrics();
if (size == MaterialProgressDrawable.LARGE) {
mCircleHeight = mCircleWidth = (int) (CIRCLE_DIAMETER_LARGE * metrics.density);
} else {
mCircleHeight = mCircleWidth = (int) (CIRCLE_DIAMETER * metrics.density);
}
// force the bounds of the progress circle inside the circle view to
// update by setting it to null before updating its size and then
// re-setting it
mCircleView.setImageDrawable(null);
mProgress.updateSizes(size);
mCircleView.setImageDrawable(mProgress);
}
/**
* Simple constructor to use when creating a SwipeRefreshLayout from code.
*
* @param context
*/
public SwipeRefreshLayout(Context context) {
this(context, null);
}
/**
* Constructor that is called when inflating SwipeRefreshLayout from XML.
*
* @param context
* @param attrs
*/
public SwipeRefreshLayout(Context context, AttributeSet attrs) {
super(context, attrs);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
mMediumAnimationDuration = getResources().getInteger(
android.R.integer.config_mediumAnimTime);
setWillNotDraw(false);
mDecelerateInterpolator = new DecelerateInterpolator(DECELERATE_INTERPOLATION_FACTOR);
final TypedArray a = context.obtainStyledAttributes(attrs, LAYOUT_ATTRS);
setEnabled(a.getBoolean(0, true));
a.recycle();
final DisplayMetrics metrics = getResources().getDisplayMetrics();
mCircleWidth = (int) (CIRCLE_DIAMETER * metrics.density);
mCircleHeight = (int) (CIRCLE_DIAMETER * metrics.density);
createProgressView();
ViewCompat.setChildrenDrawingOrderEnabled(this, true);
// the absolute offset has to take into account that the circle starts at an offset
mSpinnerFinalOffset = DEFAULT_CIRCLE_TARGET * metrics.density;
mTotalDragDistance = mSpinnerFinalOffset;
}
protected int getChildDrawingOrder(int childCount, int i) {
if (mCircleViewIndex < 0) {
return i;
} else if (i == childCount - 1) {
// Draw the selected child last
return mCircleViewIndex;
} else if (i >= mCircleViewIndex) {
// Move the children after the selected child earlier one
return i + 1;
} else {
// Keep the children before the selected child the same
return i;
}
}
private void createProgressView() {
mCircleView = new CircleImageView(getContext(), CIRCLE_BG_LIGHT, CIRCLE_DIAMETER/2);
mProgress = new MaterialProgressDrawable(getContext(), this);
mProgress.setBackgroundColor(CIRCLE_BG_LIGHT);
mCircleView.setImageDrawable(mProgress);
mCircleView.setVisibility(View.GONE);
addView(mCircleView);
}
/**
* Set the listener to be notified when a refresh is triggered via the swipe
* gesture.
*/
public void setOnRefreshListener(OnRefreshListener listener) {
mListener = listener;
}
/**
* Pre API 11, alpha is used to make the progress circle appear instead of scale.
*/
private boolean isAlphaUsedForScale() {
return android.os.Build.VERSION.SDK_INT < 11;
}
/**
* Notify the widget that refresh state has changed. Do not call this when
* refresh is triggered by a swipe gesture.
*
* @param refreshing Whether or not the view should show refresh progress.
*/
public void setRefreshing(boolean refreshing) {
if (refreshing && mRefreshing != refreshing) {
// scale and show
mRefreshing = refreshing;
int endTarget = 0;
if (!mUsingCustomStart) {
endTarget = (int) (mSpinnerFinalOffset + mOriginalOffsetTop);
} else {
endTarget = (int) mSpinnerFinalOffset;
}
setTargetOffsetTopAndBottom(endTarget - mCurrentTargetOffsetTop,
true /* requires update */);
mNotify = false;
startScaleUpAnimation(mRefreshListener);
} else {
setRefreshing(refreshing, false /* notify */);
}
}
private void startScaleUpAnimation(AnimationListener listener) {
mCircleView.setVisibility(View.VISIBLE);
if (android.os.Build.VERSION.SDK_INT >= 11) {
// Pre API 11, alpha is used in place of scale up to show the
// progress circle appearing.
// Don't adjust the alpha during appearance otherwise.
mProgress.setAlpha(MAX_ALPHA);
}
mScaleAnimation = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
setAnimationProgress(interpolatedTime);
}
};
mScaleAnimation.setDuration(mMediumAnimationDuration);
if (listener != null) {
mCircleView.setAnimationListener(listener);
}
mCircleView.clearAnimation();
mCircleView.startAnimation(mScaleAnimation);
}
/**
* Pre API 11, this does an alpha animation.
* @param progress
*/
private void setAnimationProgress(float progress) {
if (isAlphaUsedForScale()) {
setColorViewAlpha((int) (progress * MAX_ALPHA));
} else {
ViewCompat.setScaleX(mCircleView, progress);
ViewCompat.setScaleY(mCircleView, progress);
}
}
private void setRefreshing(boolean refreshing, final boolean notify) {
if (mRefreshing != refreshing) {
mNotify = notify;
ensureTarget();
mRefreshing = refreshing;
if (mRefreshing) {
animateOffsetToCorrectPosition(mCurrentTargetOffsetTop, mRefreshListener);
} else {
startScaleDownAnimation(mRefreshListener);
}
}
}
private void startScaleDownAnimation(Animation.AnimationListener listener) {
mScaleDownAnimation = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
setAnimationProgress(1 - interpolatedTime);
}
};
mScaleDownAnimation.setDuration(SCALE_DOWN_DURATION);
mCircleView.setAnimationListener(listener);
mCircleView.clearAnimation();
mCircleView.startAnimation(mScaleDownAnimation);
}
private void startProgressAlphaStartAnimation() {
mAlphaStartAnimation = startAlphaAnimation(mProgress.getAlpha(), STARTING_PROGRESS_ALPHA);
}
private void startProgressAlphaMaxAnimation() {
mAlphaMaxAnimation = startAlphaAnimation(mProgress.getAlpha(), MAX_ALPHA);
}
private Animation startAlphaAnimation(final int startingAlpha, final int endingAlpha) {
// Pre API 11, alpha is used in place of scale. Don't also use it to
// show the trigger point.
if (mScale && isAlphaUsedForScale()) {
return null;
}
Animation alpha = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
mProgress
.setAlpha((int) (startingAlpha+ ((endingAlpha - startingAlpha)
* interpolatedTime)));
}
};
alpha.setDuration(ALPHA_ANIMATION_DURATION);
// Clear out the previous animation listeners.
mCircleView.setAnimationListener(null);
mCircleView.clearAnimation();
mCircleView.startAnimation(alpha);
return alpha;
}
/**
* Set the background color of the progress spinner disc.
*
* @param colorRes Resource id of the color.
*/
public void setProgressBackgroundColor(int colorRes) {
mCircleView.setBackgroundColor(colorRes);
mProgress.setBackgroundColor(getResources().getColor(colorRes));
}
/**
* @deprecated Use {@link #setColorSchemeResources(int...)}
*/
@Deprecated
public void setColorScheme(int... colors) {
setColorSchemeResources(colors);
}
/**
* Set the color resources used in the progress animation from color resources.
* The first color will also be the color of the bar that grows in response
* to a user swipe gesture.
*
* @param colorResIds
*/
public void setColorSchemeResources(int... colorResIds) {
final Resources res = getResources();
int[] colorRes = new int[colorResIds.length];
for (int i = 0; i < colorResIds.length; i++) {
colorRes[i] = res.getColor(colorResIds[i]);
}
setColorSchemeColors(colorRes);
}
/**
* Set the colors used in the progress animation. The first
* color will also be the color of the bar that grows in response to a user
* swipe gesture.
*
* @param colors
*/
public void setColorSchemeColors(int... colors) {
ensureTarget();
mProgress.setColorSchemeColors(colors);
}
/**
* @return Whether the SwipeRefreshWidget is actively showing refresh
* progress.
*/
public boolean isRefreshing() {
return mRefreshing;
}
private void ensureTarget() {
// Don't bother getting the parent height if the parent hasn't been laid
// out yet.
if (mTarget == null) {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (!child.equals(mCircleView)) {
mTarget = child;
break;
}
}
}
}
/**
* Set the distance to trigger a sync in dips
*
* @param distance
*/
public void setDistanceToTriggerSync(int distance) {
mTotalDragDistance = distance;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
final int width = getMeasuredWidth();
final int height = getMeasuredHeight();
if (getChildCount() == 0) {
return;
}
if (mTarget == null) {
ensureTarget();
}
if (mTarget == null) {
return;
}
final View child = mTarget;
final int childLeft = getPaddingLeft();
final int childTop = getPaddingTop();
final int childWidth = width - getPaddingLeft() - getPaddingRight();
final int childHeight = height - getPaddingTop() - getPaddingBottom();
child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
int circleWidth = mCircleView.getMeasuredWidth();
int circleHeight = mCircleView.getMeasuredHeight();
mCircleView.layout((width / 2 - circleWidth / 2), mCurrentTargetOffsetTop,
(width / 2 + circleWidth / 2), mCurrentTargetOffsetTop + circleHeight);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mTarget == null) {
ensureTarget();
}
if (mTarget == null) {
return;
}
mTarget.measure(MeasureSpec.makeMeasureSpec(
getMeasuredWidth() - getPaddingLeft() - getPaddingRight(),
MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(
getMeasuredHeight() - getPaddingTop() - getPaddingBottom(), MeasureSpec.EXACTLY));
mCircleView.measure(MeasureSpec.makeMeasureSpec(mCircleWidth, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(mCircleHeight, MeasureSpec.EXACTLY));
if (!mUsingCustomStart && !mOriginalOffsetCalculated) {
mOriginalOffsetCalculated = true;
mCurrentTargetOffsetTop = mOriginalOffsetTop = -mCircleView.getMeasuredHeight();
}
mCircleViewIndex = -1;
// Get the index of the circleview.
for (int index = 0; index < getChildCount(); index++) {
if (getChildAt(index) == mCircleView) {
mCircleViewIndex = index;
break;
}
}
}
/**
* @return Whether it is possible for the child view of this layout to
* scroll up. Override this if the child view is a custom view.
*/
public boolean canChildScrollUp() {
if (android.os.Build.VERSION.SDK_INT < 14) {
if (mTarget instanceof AbsListView) {
final AbsListView absListView = (AbsListView) mTarget;
return absListView.getChildCount() > 0
&& (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0)
.getTop() < absListView.getPaddingTop());
} else {
return mTarget.getScrollY() > 0;
}
} else {
return ViewCompat.canScrollVertically(mTarget, -1);
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
ensureTarget();
final int action = MotionEventCompat.getActionMasked(ev);
if (mReturningToStart && action == MotionEvent.ACTION_DOWN) {
mReturningToStart = false;
}
if (!isEnabled() || mReturningToStart || canChildScrollUp() || mRefreshing) {
// Fail fast if we're not in a state where a swipe is possible
return false;
}
switch (action) {
case MotionEvent.ACTION_DOWN:
setTargetOffsetTopAndBottom(mOriginalOffsetTop - mCircleView.getTop(), true);
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
mIsBeingDragged = false;
final float initialMotionY = getMotionEventY(ev, mActivePointerId);
if (initialMotionY == -1) {
return false;
}
mInitialMotionY = initialMotionY;
case MotionEvent.ACTION_MOVE:
if (mActivePointerId == INVALID_POINTER) {
Log.e(LOG_TAG, "Got ACTION_MOVE event but don't have an active pointer id.");
return false;
}
final float y = getMotionEventY(ev, mActivePointerId);
if (y == -1) {
return false;
}
final float yDiff = y - mInitialMotionY;
if (yDiff > mTouchSlop && !mIsBeingDragged) {
mIsBeingDragged = true;
mProgress.setAlpha(STARTING_PROGRESS_ALPHA);
}
break;
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
mIsBeingDragged = false;
mActivePointerId = INVALID_POINTER;
break;
}
return mIsBeingDragged;
}
private float getMotionEventY(MotionEvent ev, int activePointerId) {
final int index = MotionEventCompat.findPointerIndex(ev, activePointerId);
if (index < 0) {
return -1;
}
return MotionEventCompat.getY(ev, index);
}
@Override
public void requestDisallowInterceptTouchEvent(boolean b) {
// Nope.
}
private boolean isAnimationRunning(Animation animation) {
return animation != null && animation.hasStarted() && !animation.hasEnded();
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
final int action = MotionEventCompat.getActionMasked(ev);
if (mReturningToStart && action == MotionEvent.ACTION_DOWN) {
mReturningToStart = false;
}
if (!isEnabled() || mReturningToStart || canChildScrollUp()) {
// Fail fast if we're not in a state where a swipe is possible
return false;
}
switch (action) {
case MotionEvent.ACTION_DOWN:
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
mIsBeingDragged = false;
break;
case MotionEvent.ACTION_MOVE: {
final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
if (pointerIndex < 0) {
Log.e(LOG_TAG, "Got ACTION_MOVE event but have an invalid active pointer id.");
return false;
}
final float y = MotionEventCompat.getY(ev, pointerIndex);
final float overscrollTop = (y - mInitialMotionY) * DRAG_RATE;
if (mIsBeingDragged) {
mProgress.showArrow(true);
float originalDragPercent = overscrollTop / mTotalDragDistance;
if (originalDragPercent < 0) {
return false;
}
float dragPercent = Math.min(1f, Math.abs(originalDragPercent));
float adjustedPercent = (float) Math.max(dragPercent - .4, 0) * 5 / 3;
float extraOS = Math.abs(overscrollTop) - mTotalDragDistance;
float slingshotDist = mUsingCustomStart ? mSpinnerFinalOffset
- mOriginalOffsetTop : mSpinnerFinalOffset;
float tensionSlingshotPercent = Math.max(0,
Math.min(extraOS, slingshotDist * 2) / slingshotDist);
float tensionPercent = (float) ((tensionSlingshotPercent / 4) - Math.pow(
(tensionSlingshotPercent / 4), 2)) * 2f;
float extraMove = (slingshotDist) * tensionPercent * 2;
int targetY = mOriginalOffsetTop
+ (int) ((slingshotDist * dragPercent) + extraMove);
// where 1.0f is a full circle
if (mCircleView.getVisibility() != View.VISIBLE) {
mCircleView.setVisibility(View.VISIBLE);
}
if (!mScale) {
ViewCompat.setScaleX(mCircleView, 1f);
ViewCompat.setScaleY(mCircleView, 1f);
}
if (overscrollTop < mTotalDragDistance) {
if (mScale) {
setAnimationProgress(overscrollTop / mTotalDragDistance);
}
if (mProgress.getAlpha() > STARTING_PROGRESS_ALPHA
&& !isAnimationRunning(mAlphaStartAnimation)) {
// Animate the alpha
startProgressAlphaStartAnimation();
}
float strokeStart = (float) (adjustedPercent * .8f);
mProgress.setStartEndTrim(0f, Math.min(MAX_PROGRESS_ANGLE, strokeStart));
mProgress.setArrowScale(Math.min(1f, adjustedPercent));
} else {
if (mProgress.getAlpha() < MAX_ALPHA
&& !isAnimationRunning(mAlphaMaxAnimation)) {
// Animate the alpha
startProgressAlphaMaxAnimation();
}
}
float rotation = (-0.25f + .4f * adjustedPercent + tensionPercent * 2) * .5f;
mProgress.setProgressRotation(rotation);
setTargetOffsetTopAndBottom(targetY - mCurrentTargetOffsetTop,
true /* requires update */);
}
break;
}
case MotionEventCompat.ACTION_POINTER_DOWN: {
final int index = MotionEventCompat.getActionIndex(ev);
mActivePointerId = MotionEventCompat.getPointerId(ev, index);
break;
}
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL: {
final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
final float y = MotionEventCompat.getY(ev, pointerIndex);
final float overscrollTop = (y - mInitialMotionY) * DRAG_RATE;
mIsBeingDragged = false;
if (overscrollTop > mTotalDragDistance) {
setRefreshing(true, true /* notify */);
} else {
// cancel refresh
mRefreshing = false;
mProgress.setStartEndTrim(0f, 0f);
Animation.AnimationListener listener = null;
if (!mScale) {
listener = new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
if (!mScale) {
startScaleDownAnimation(null);
}
}
@Override
public void onAnimationRepeat(Animation animation) {
}
};
}
animateOffsetToStartPosition(mCurrentTargetOffsetTop, listener);
mProgress.showArrow(false);
}
mActivePointerId = INVALID_POINTER;
return false;
}
}
return true;
}
private void animateOffsetToCorrectPosition(int from, AnimationListener listener) {
mFrom = from;
mAnimateToCorrectPosition.reset();
mAnimateToCorrectPosition.setDuration(ANIMATE_TO_TRIGGER_DURATION);
mAnimateToCorrectPosition.setInterpolator(mDecelerateInterpolator);
if (listener != null) {
mCircleView.setAnimationListener(listener);
}
mCircleView.clearAnimation();
mCircleView.startAnimation(mAnimateToCorrectPosition);
}
private void animateOffsetToStartPosition(int from, AnimationListener listener) {
if (mScale) {
// Scale the item back down
startScaleDownReturnToStartAnimation(from, listener);
} else {
mFrom = from;
mAnimateToStartPosition.reset();
mAnimateToStartPosition.setDuration(ANIMATE_TO_START_DURATION);
mAnimateToStartPosition.setInterpolator(mDecelerateInterpolator);
if (listener != null) {
mCircleView.setAnimationListener(listener);
}
mCircleView.clearAnimation();
mCircleView.startAnimation(mAnimateToStartPosition);
}
}
private final Animation mAnimateToCorrectPosition = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
int targetTop = 0;
int endTarget = 0;
if (!mUsingCustomStart) {
endTarget = (int) (mSpinnerFinalOffset - Math.abs(mOriginalOffsetTop));
} else {
endTarget = (int) mSpinnerFinalOffset;
}
targetTop = (mFrom + (int) ((endTarget - mFrom) * interpolatedTime));
int offset = targetTop - mCircleView.getTop();
setTargetOffsetTopAndBottom(offset, false /* requires update */);
}
};
private void moveToStart(float interpolatedTime) {
int targetTop = 0;
targetTop = (mFrom + (int) ((mOriginalOffsetTop - mFrom) * interpolatedTime));
int offset = targetTop - mCircleView.getTop();
setTargetOffsetTopAndBottom(offset, false /* requires update */);
}
private final Animation mAnimateToStartPosition = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
moveToStart(interpolatedTime);
}
};
private void startScaleDownReturnToStartAnimation(int from,
Animation.AnimationListener listener) {
mFrom = from;
if (isAlphaUsedForScale()) {
mStartingScale = mProgress.getAlpha();
} else {
mStartingScale = ViewCompat.getScaleX(mCircleView);
}
mScaleDownToStartAnimation = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
float targetScale = (mStartingScale + (-mStartingScale * interpolatedTime));
setAnimationProgress(targetScale);
moveToStart(interpolatedTime);
}
};
mScaleDownToStartAnimation.setDuration(SCALE_DOWN_DURATION);
if (listener != null) {
mCircleView.setAnimationListener(listener);
}
mCircleView.clearAnimation();
mCircleView.startAnimation(mScaleDownToStartAnimation);
}
private void setTargetOffsetTopAndBottom(int offset, boolean requiresUpdate) {
mCircleView.bringToFront();
mCircleView.offsetTopAndBottom(offset);
mCurrentTargetOffsetTop = mCircleView.getTop();
if (requiresUpdate && android.os.Build.VERSION.SDK_INT < 11) {
invalidate();
}
}
private void onSecondaryPointerUp(MotionEvent ev) {
final int pointerIndex = MotionEventCompat.getActionIndex(ev);
final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
}
}
/**
* Classes that wish to be notified when the swipe gesture correctly
* triggers a refresh should implement this interface.
*/
public interface OnRefreshListener {
public void onRefresh();
}
} | v4/java/android/support/v4/widget/SwipeRefreshLayout.java | /*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.v4.widget;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Transformation;
import android.widget.AbsListView;
/**
* The SwipeRefreshLayout should be used whenever the user can refresh the
* contents of a view via a vertical swipe gesture. The activity that
* instantiates this view should add an OnRefreshListener to be notified
* whenever the swipe to refresh gesture is completed. The SwipeRefreshLayout
* will notify the listener each and every time the gesture is completed again;
* the listener is responsible for correctly determining when to actually
* initiate a refresh of its content. If the listener determines there should
* not be a refresh, it must call setRefreshing(false) to cancel any visual
* indication of a refresh. If an activity wishes to show just the progress
* animation, it should call setRefreshing(true). To disable the gesture and
* progress animation, call setEnabled(false) on the view.
* <p>
* This layout should be made the parent of the view that will be refreshed as a
* result of the gesture and can only support one direct child. This view will
* also be made the target of the gesture and will be forced to match both the
* width and the height supplied in this layout. The SwipeRefreshLayout does not
* provide accessibility events; instead, a menu item must be provided to allow
* refresh of the content wherever this gesture is used.
* </p>
*/
public class SwipeRefreshLayout extends ViewGroup {
// Maps to ProgressBar.Large style
public static final int LARGE = MaterialProgressDrawable.LARGE;
// Maps to ProgressBar default style
public static final int DEFAULT = MaterialProgressDrawable.DEFAULT;
private static final String LOG_TAG = SwipeRefreshLayout.class.getSimpleName();
private static final int MAX_ALPHA = 255;
private static final int STARTING_PROGRESS_ALPHA = (int) (.3f * MAX_ALPHA);
private static final int CIRCLE_DIAMETER = 40;
private static final int CIRCLE_DIAMETER_LARGE = 56;
private static final float DECELERATE_INTERPOLATION_FACTOR = 2f;
private static final int INVALID_POINTER = -1;
private static final float DRAG_RATE = .5f;
// Max amount of circle that can be filled by progress during swipe gesture,
// where 1.0 is a full circle
private static final float MAX_PROGRESS_ANGLE = .8f;
private static final int SCALE_DOWN_DURATION = 150;
private static final int ALPHA_ANIMATION_DURATION = 300;
private static final int ANIMATE_TO_TRIGGER_DURATION = 200;
private static final int ANIMATE_TO_START_DURATION = 200;
// Default background for the progress spinner
private static final int CIRCLE_BG_LIGHT = 0xFFFAFAFA;
// Default offset in dips from the top of the view to where the progress spinner should stop
private static final int DEFAULT_CIRCLE_TARGET = 64;
private View mTarget; // the target of the gesture
private OnRefreshListener mListener;
private boolean mRefreshing = false;
private int mTouchSlop;
private float mTotalDragDistance = -1;
private int mMediumAnimationDuration;
private int mCurrentTargetOffsetTop;
// Whether or not the starting offset has been determined.
private boolean mOriginalOffsetCalculated = false;
private float mInitialMotionY;
private boolean mIsBeingDragged;
private int mActivePointerId = INVALID_POINTER;
// Whether this item is scaled up rather than clipped
private boolean mScale;
// Target is returning to its start offset because it was cancelled or a
// refresh was triggered.
private boolean mReturningToStart;
private final DecelerateInterpolator mDecelerateInterpolator;
private static final int[] LAYOUT_ATTRS = new int[] {
android.R.attr.enabled
};
private CircleImageView mCircleView;
private int mCircleViewIndex = -1;
protected int mFrom;
private float mStartingScale;
protected int mOriginalOffsetTop;
private MaterialProgressDrawable mProgress;
private Animation mScaleAnimation;
private Animation mScaleDownAnimation;
private Animation mAlphaStartAnimation;
private Animation mAlphaMaxAnimation;
private Animation mScaleDownToStartAnimation;
private float mSpinnerFinalOffset;
private boolean mNotify;
private int mCircleWidth;
private int mCircleHeight;
// Whether the client has set a custom starting position;
private boolean mUsingCustomStart;
private Animation.AnimationListener mRefreshListener = new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
if (mRefreshing) {
// Make sure the progress view is fully visible
mProgress.setAlpha(MAX_ALPHA);
mProgress.start();
if (mNotify) {
if (mListener != null) {
mListener.onRefresh();
}
}
} else {
mProgress.stop();
mCircleView.setVisibility(View.GONE);
// Return the circle to its start position
if (mScale) {
setAnimationProgress(0 /* animation complete and view is hidden */);
} else {
setTargetOffsetTopAndBottom(mOriginalOffsetTop - mCurrentTargetOffsetTop,
true /* requires update */);
}
}
mCurrentTargetOffsetTop = mCircleView.getTop();
}
};
private void setColorViewAlpha(int targetAlpha) {
mCircleView.getBackground().setAlpha(targetAlpha);
mProgress.setAlpha(targetAlpha);
}
/**
* The refresh indicator starting and resting position is always positioned
* near the top of the refreshing content. This position is a consistent
* location, but can be adjusted in either direction based on whether or not
* there is a toolbar or actionbar present.
*
* @param scale Set to true if there is no view at a higher z-order than
* where the progress spinner is set to appear.
* @param start The offset in pixels from the top of this view at which the
* progress spinner should appear.
* @param end The offset in pixels from the top of this view at which the
* progress spinner should come to rest after a successful swipe
* gesture.
*/
public void setProgressViewOffset(boolean scale, int start, int end) {
mScale = scale;
mCircleView.setVisibility(View.GONE);
mOriginalOffsetTop = mCurrentTargetOffsetTop = start;
mSpinnerFinalOffset = end;
mUsingCustomStart = true;
mCircleView.invalidate();
}
/**
* The refresh indicator resting position is always positioned near the top
* of the refreshing content. This position is a consistent location, but
* can be adjusted in either direction based on whether or not there is a
* toolbar or actionbar present.
*
* @param scale Set to true if there is no view at a higher z-order than
* where the progress spinner is set to appear.
* @param end The offset in pixels from the top of this view at which the
* progress spinner should come to rest after a successful swipe
* gesture.
*/
public void setProgressViewEndTarget(boolean scale, int end) {
mSpinnerFinalOffset = end;
mScale = scale;
mCircleView.invalidate();
}
/**
* One of DEFAULT, or LARGE.
*/
public void setSize(int size) {
if (size != MaterialProgressDrawable.LARGE && size != MaterialProgressDrawable.DEFAULT) {
return;
}
final DisplayMetrics metrics = getResources().getDisplayMetrics();
if (size == MaterialProgressDrawable.LARGE) {
mCircleHeight = mCircleWidth = (int) (CIRCLE_DIAMETER_LARGE * metrics.density);
} else {
mCircleHeight = mCircleWidth = (int) (CIRCLE_DIAMETER * metrics.density);
}
// force the bounds of the progress circle inside the circle view to
// update by setting it to null before updating its size and then
// re-setting it
mCircleView.setImageDrawable(null);
mProgress.updateSizes(size);
mCircleView.setImageDrawable(mProgress);
}
/**
* Simple constructor to use when creating a SwipeRefreshLayout from code.
*
* @param context
*/
public SwipeRefreshLayout(Context context) {
this(context, null);
}
/**
* Constructor that is called when inflating SwipeRefreshLayout from XML.
*
* @param context
* @param attrs
*/
public SwipeRefreshLayout(Context context, AttributeSet attrs) {
super(context, attrs);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
mMediumAnimationDuration = getResources().getInteger(
android.R.integer.config_mediumAnimTime);
setWillNotDraw(false);
mDecelerateInterpolator = new DecelerateInterpolator(DECELERATE_INTERPOLATION_FACTOR);
final TypedArray a = context.obtainStyledAttributes(attrs, LAYOUT_ATTRS);
setEnabled(a.getBoolean(0, true));
a.recycle();
final DisplayMetrics metrics = getResources().getDisplayMetrics();
mCircleWidth = (int) (CIRCLE_DIAMETER * metrics.density);
mCircleHeight = (int) (CIRCLE_DIAMETER * metrics.density);
createProgressView();
ViewCompat.setChildrenDrawingOrderEnabled(this, true);
// the absolute offset has to take into account that the circle starts at an offset
mSpinnerFinalOffset = DEFAULT_CIRCLE_TARGET * metrics.density;
mTotalDragDistance = mSpinnerFinalOffset;
}
protected int getChildDrawingOrder(int childCount, int i) {
if (mCircleViewIndex < 0) {
return i;
} else if (i == childCount - 1) {
// Draw the selected child last
return mCircleViewIndex;
} else if (i >= mCircleViewIndex) {
// Move the children after the selected child earlier one
return i + 1;
} else {
// Keep the children before the selected child the same
return i;
}
}
private void createProgressView() {
mCircleView = new CircleImageView(getContext(), CIRCLE_BG_LIGHT, CIRCLE_DIAMETER/2);
mProgress = new MaterialProgressDrawable(getContext(), this);
mProgress.setBackgroundColor(CIRCLE_BG_LIGHT);
mCircleView.setImageDrawable(mProgress);
mCircleView.setVisibility(View.GONE);
addView(mCircleView);
}
/**
* Set the listener to be notified when a refresh is triggered via the swipe
* gesture.
*/
public void setOnRefreshListener(OnRefreshListener listener) {
mListener = listener;
}
/**
* Pre API 11, alpha is used to make the progress circle appear instead of scale.
*/
private boolean isAlphaUsedForScale() {
return android.os.Build.VERSION.SDK_INT < 11;
}
/**
* Notify the widget that refresh state has changed. Do not call this when
* refresh is triggered by a swipe gesture.
*
* @param refreshing Whether or not the view should show refresh progress.
*/
public void setRefreshing(boolean refreshing) {
if (refreshing && mRefreshing != refreshing) {
// scale and show
mRefreshing = refreshing;
int endTarget = 0;
if (!mUsingCustomStart) {
endTarget = (int) (mSpinnerFinalOffset + mOriginalOffsetTop);
} else {
endTarget = (int) mSpinnerFinalOffset;
}
setTargetOffsetTopAndBottom(endTarget - mCurrentTargetOffsetTop,
true /* requires update */);
mNotify = false;
startScaleUpAnimation(mRefreshListener);
} else {
setRefreshing(refreshing, false /* notify */);
}
}
private void startScaleUpAnimation(AnimationListener listener) {
mCircleView.setVisibility(View.VISIBLE);
if (android.os.Build.VERSION.SDK_INT >= 11) {
// Pre API 11, alpha is used in place of scale up to show the
// progress circle appearing.
// Don't adjust the alpha during appearance otherwise.
mProgress.setAlpha(MAX_ALPHA);
}
mScaleAnimation = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
setAnimationProgress(interpolatedTime);
}
};
mScaleAnimation.setDuration(mMediumAnimationDuration);
if (listener != null) {
mCircleView.setAnimationListener(listener);
}
mCircleView.clearAnimation();
mCircleView.startAnimation(mScaleAnimation);
}
/**
* Pre API 11, this does an alpha animation.
* @param progress
*/
private void setAnimationProgress(float progress) {
if (isAlphaUsedForScale()) {
setColorViewAlpha((int) (progress * MAX_ALPHA));
} else {
ViewCompat.setScaleX(mCircleView, progress);
ViewCompat.setScaleY(mCircleView, progress);
}
}
private void setRefreshing(boolean refreshing, final boolean notify) {
if (mRefreshing != refreshing) {
mNotify = notify;
ensureTarget();
mRefreshing = refreshing;
if (mRefreshing) {
animateOffsetToCorrectPosition(mCurrentTargetOffsetTop, mRefreshListener);
} else {
startScaleDownAnimation(mRefreshListener);
}
}
}
private void startScaleDownAnimation(Animation.AnimationListener listener) {
mScaleDownAnimation = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
setAnimationProgress(1 - interpolatedTime);
}
};
mScaleDownAnimation.setDuration(SCALE_DOWN_DURATION);
mCircleView.setAnimationListener(listener);
mCircleView.clearAnimation();
mCircleView.startAnimation(mScaleDownAnimation);
}
private void startProgressAlphaStartAnimation() {
mAlphaStartAnimation = startAlphaAnimation(mProgress.getAlpha(), STARTING_PROGRESS_ALPHA);
}
private void startProgressAlphaMaxAnimation() {
mAlphaMaxAnimation = startAlphaAnimation(mProgress.getAlpha(), MAX_ALPHA);
}
private Animation startAlphaAnimation(final int startingAlpha, final int endingAlpha) {
// Pre API 11, alpha is used in place of scale. Don't also use it to
// show the trigger point.
if (mScale && isAlphaUsedForScale()) {
return null;
}
Animation alpha = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
mProgress
.setAlpha((int) (startingAlpha+ ((endingAlpha - startingAlpha)
* interpolatedTime)));
}
};
alpha.setDuration(ALPHA_ANIMATION_DURATION);
// Clear out the previous animation listeners.
mCircleView.setAnimationListener(null);
mCircleView.clearAnimation();
mCircleView.startAnimation(alpha);
return alpha;
}
/**
* Set the background color of the progress spinner disc.
*
* @param colorRes Resource id of the color.
*/
public void setProgressBackgroundColor(int colorRes) {
mCircleView.setBackgroundColor(colorRes);
mProgress.setBackgroundColor(getResources().getColor(colorRes));
}
/**
* @deprecated Use {@link #setColorSchemeResources(int...)}
*/
@Deprecated
public void setColorScheme(int... colors) {
setColorSchemeResources(colors);
}
/**
* Set the color resources used in the progress animation from color resources.
* The first color will also be the color of the bar that grows in response
* to a user swipe gesture.
*
* @param colorResIds
*/
public void setColorSchemeResources(int... colorResIds) {
final Resources res = getResources();
int[] colorRes = new int[colorResIds.length];
for (int i = 0; i < colorResIds.length; i++) {
colorRes[i] = res.getColor(colorResIds[i]);
}
setColorSchemeColors(colorRes);
}
/**
* Set the colors used in the progress animation. The first
* color will also be the color of the bar that grows in response to a user
* swipe gesture.
*
* @param colors
*/
public void setColorSchemeColors(int... colors) {
ensureTarget();
mProgress.setColorSchemeColors(colors);
}
/**
* @return Whether the SwipeRefreshWidget is actively showing refresh
* progress.
*/
public boolean isRefreshing() {
return mRefreshing;
}
private void ensureTarget() {
// Don't bother getting the parent height if the parent hasn't been laid
// out yet.
if (mTarget == null) {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (!child.equals(mCircleView)) {
mTarget = child;
break;
}
}
}
}
/**
* Set the distance to trigger a sync in dips
*
* @param distance
*/
public void setDistanceToTriggerSync(int distance) {
mTotalDragDistance = distance;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
final int width = getMeasuredWidth();
final int height = getMeasuredHeight();
if (getChildCount() == 0) {
return;
}
if (mTarget == null) {
ensureTarget();
}
if (mTarget == null) {
return;
}
final View child = mTarget;
final int childLeft = getPaddingLeft();
final int childTop = getPaddingTop();
final int childWidth = width - getPaddingLeft() - getPaddingRight();
final int childHeight = height - getPaddingTop() - getPaddingBottom();
child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
int circleWidth = mCircleView.getMeasuredWidth();
int circleHeight = mCircleView.getMeasuredHeight();
mCircleView.layout((width / 2 - circleWidth / 2), mCurrentTargetOffsetTop,
(width / 2 + circleWidth / 2), mCurrentTargetOffsetTop + circleHeight);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mTarget == null) {
ensureTarget();
}
if (mTarget == null) {
return;
}
mTarget.measure(MeasureSpec.makeMeasureSpec(
getMeasuredWidth() - getPaddingLeft() - getPaddingRight(),
MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(
getMeasuredHeight() - getPaddingTop() - getPaddingBottom(), MeasureSpec.EXACTLY));
mCircleView.measure(MeasureSpec.makeMeasureSpec(mCircleWidth, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(mCircleHeight, MeasureSpec.EXACTLY));
if (!mUsingCustomStart && !mOriginalOffsetCalculated) {
mOriginalOffsetCalculated = true;
mCurrentTargetOffsetTop = mOriginalOffsetTop = -mCircleView.getMeasuredHeight();
}
mCircleViewIndex = -1;
// Get the index of the circleview.
for (int index = 0; index < getChildCount(); index++) {
if (getChildAt(index) == mCircleView) {
mCircleViewIndex = index;
break;
}
}
}
/**
* @return Whether it is possible for the child view of this layout to
* scroll up. Override this if the child view is a custom view.
*/
public boolean canChildScrollUp() {
if (android.os.Build.VERSION.SDK_INT < 14) {
if (mTarget instanceof AbsListView) {
final AbsListView absListView = (AbsListView) mTarget;
return absListView.getChildCount() > 0
&& (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0)
.getTop() < absListView.getPaddingTop());
} else {
return mTarget.getScrollY() > 0;
}
} else {
return ViewCompat.canScrollVertically(mTarget, -1);
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
ensureTarget();
final int action = MotionEventCompat.getActionMasked(ev);
if (mReturningToStart && action == MotionEvent.ACTION_DOWN) {
mReturningToStart = false;
}
if (!isEnabled() || mReturningToStart || canChildScrollUp() || mRefreshing) {
// Fail fast if we're not in a state where a swipe is possible
return false;
}
switch (action) {
case MotionEvent.ACTION_DOWN:
setTargetOffsetTopAndBottom(mOriginalOffsetTop - mCircleView.getTop(), true);
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
mIsBeingDragged = false;
final float initialMotionY = getMotionEventY(ev, mActivePointerId);
if (initialMotionY == -1) {
return false;
}
mInitialMotionY = initialMotionY;
case MotionEvent.ACTION_MOVE:
if (mActivePointerId == INVALID_POINTER) {
Log.e(LOG_TAG, "Got ACTION_MOVE event but don't have an active pointer id.");
return false;
}
final float y = getMotionEventY(ev, mActivePointerId);
if (y == -1) {
return false;
}
final float yDiff = y - mInitialMotionY;
if (yDiff > mTouchSlop && !mIsBeingDragged) {
mIsBeingDragged = true;
mProgress.setAlpha(STARTING_PROGRESS_ALPHA);
}
break;
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
mIsBeingDragged = false;
mActivePointerId = INVALID_POINTER;
break;
}
return mIsBeingDragged;
}
private float getMotionEventY(MotionEvent ev, int activePointerId) {
final int index = MotionEventCompat.findPointerIndex(ev, activePointerId);
if (index < 0) {
return -1;
}
return MotionEventCompat.getY(ev, index);
}
@Override
public void requestDisallowInterceptTouchEvent(boolean b) {
// Nope.
}
private boolean isAnimationRunning(Animation animation) {
return animation != null && animation.hasStarted() && !animation.hasEnded();
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
final int action = MotionEventCompat.getActionMasked(ev);
if (mReturningToStart && action == MotionEvent.ACTION_DOWN) {
mReturningToStart = false;
}
if (!isEnabled() || mReturningToStart || canChildScrollUp()) {
// Fail fast if we're not in a state where a swipe is possible
return false;
}
switch (action) {
case MotionEvent.ACTION_DOWN:
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
mIsBeingDragged = false;
break;
case MotionEvent.ACTION_MOVE: {
final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
if (pointerIndex < 0) {
Log.e(LOG_TAG, "Got ACTION_MOVE event but have an invalid active pointer id.");
return false;
}
final float y = MotionEventCompat.getY(ev, pointerIndex);
final float overscrollTop = (y - mInitialMotionY) * DRAG_RATE;
if (mIsBeingDragged) {
mProgress.showArrow(true);
float originalDragPercent = overscrollTop / mTotalDragDistance;
if (originalDragPercent < 0) {
return false;
}
float dragPercent = Math.min(1f, Math.abs(originalDragPercent));
float adjustedPercent = (float) Math.max(dragPercent - .4, 0) * 5 / 3;
float extraOS = Math.abs(overscrollTop) - mTotalDragDistance;
float slingshotDist = mUsingCustomStart ? mSpinnerFinalOffset
- mOriginalOffsetTop : mSpinnerFinalOffset;
float tensionSlingshotPercent = Math.max(0,
Math.min(extraOS, slingshotDist * 2) / slingshotDist);
float tensionPercent = (float) ((tensionSlingshotPercent / 4) - Math.pow(
(tensionSlingshotPercent / 4), 2)) * 2f;
float extraMove = (slingshotDist) * tensionPercent * 2;
int targetY = mOriginalOffsetTop
+ (int) ((slingshotDist * dragPercent) + extraMove);
// where 1.0f is a full circle
if (mCircleView.getVisibility() != View.VISIBLE) {
mCircleView.setVisibility(View.VISIBLE);
}
if (!mScale) {
ViewCompat.setScaleX(mCircleView, 1f);
ViewCompat.setScaleY(mCircleView, 1f);
}
if (overscrollTop < mTotalDragDistance) {
if (mScale) {
setAnimationProgress(overscrollTop / mTotalDragDistance);
}
if (mProgress.getAlpha() > STARTING_PROGRESS_ALPHA
&& !isAnimationRunning(mAlphaStartAnimation)) {
// Animate the alpha
startProgressAlphaStartAnimation();
}
float strokeStart = (float) (adjustedPercent * .8f);
mProgress.setStartEndTrim(0f, Math.min(MAX_PROGRESS_ANGLE, strokeStart));
mProgress.setArrowScale(Math.min(1f, adjustedPercent));
} else {
if (mProgress.getAlpha() < MAX_ALPHA
&& !isAnimationRunning(mAlphaMaxAnimation)) {
// Animate the alpha
startProgressAlphaMaxAnimation();
}
}
float rotation = (-0.25f + .4f * adjustedPercent + tensionPercent * 2) * .5f;
mProgress.setProgressRotation(rotation);
setTargetOffsetTopAndBottom(targetY - mCurrentTargetOffsetTop,
true /* requires update */);
}
break;
}
case MotionEventCompat.ACTION_POINTER_DOWN: {
final int index = MotionEventCompat.getActionIndex(ev);
mActivePointerId = MotionEventCompat.getPointerId(ev, index);
break;
}
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL: {
final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
final float y = MotionEventCompat.getY(ev, pointerIndex);
final float overscrollTop = (y - mInitialMotionY) * DRAG_RATE;
mIsBeingDragged = false;
if (overscrollTop > mTotalDragDistance) {
setRefreshing(true, true /* notify */);
} else {
// cancel refresh
mRefreshing = false;
mProgress.setStartEndTrim(0f, 0f);
Animation.AnimationListener listener = null;
if (!mScale) {
listener = new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
if (!mScale) {
startScaleDownAnimation(null);
}
}
@Override
public void onAnimationRepeat(Animation animation) {
}
};
}
animateOffsetToStartPosition(mCurrentTargetOffsetTop, listener);
mProgress.showArrow(false);
}
mActivePointerId = INVALID_POINTER;
return false;
}
}
return true;
}
private void animateOffsetToCorrectPosition(int from, AnimationListener listener) {
mFrom = from;
mAnimateToCorrectPosition.reset();
mAnimateToCorrectPosition.setDuration(ANIMATE_TO_TRIGGER_DURATION);
mAnimateToCorrectPosition.setInterpolator(mDecelerateInterpolator);
if (listener != null) {
mCircleView.setAnimationListener(listener);
}
mCircleView.clearAnimation();
mCircleView.startAnimation(mAnimateToCorrectPosition);
}
private void animateOffsetToStartPosition(int from, AnimationListener listener) {
if (mScale) {
// Scale the item back down
startScaleDownReturnToStartAnimation(from, listener);
} else {
mFrom = from;
mAnimateToStartPosition.reset();
mAnimateToStartPosition.setDuration(ANIMATE_TO_START_DURATION);
mAnimateToStartPosition.setInterpolator(mDecelerateInterpolator);
if (listener != null) {
mCircleView.setAnimationListener(listener);
}
mCircleView.clearAnimation();
mCircleView.startAnimation(mAnimateToStartPosition);
}
}
private final Animation mAnimateToCorrectPosition = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
int targetTop = 0;
int endTarget = 0;
if (!mUsingCustomStart) {
endTarget = (int) (mSpinnerFinalOffset - Math.abs(mOriginalOffsetTop));
} else {
endTarget = (int) mSpinnerFinalOffset;
}
targetTop = (mFrom + (int) ((endTarget - mFrom) * interpolatedTime));
int offset = targetTop - mCircleView.getTop();
setTargetOffsetTopAndBottom(offset, false /* requires update */);
}
};
private void moveToStart(float interpolatedTime) {
int targetTop = 0;
targetTop = (mFrom + (int) ((mOriginalOffsetTop - mFrom) * interpolatedTime));
int offset = targetTop - mCircleView.getTop();
setTargetOffsetTopAndBottom(offset, false /* requires update */);
}
private final Animation mAnimateToStartPosition = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
moveToStart(interpolatedTime);
}
};
private void startScaleDownReturnToStartAnimation(int from,
Animation.AnimationListener listener) {
mFrom = from;
if (isAlphaUsedForScale()) {
mStartingScale = mProgress.getAlpha();
} else {
mStartingScale = ViewCompat.getScaleX(mCircleView);
}
mScaleDownToStartAnimation = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
float targetScale = (mStartingScale + (-mStartingScale * interpolatedTime));
setAnimationProgress(targetScale);
moveToStart(interpolatedTime);
}
};
mScaleDownToStartAnimation.setDuration(SCALE_DOWN_DURATION);
if (listener != null) {
mCircleView.setAnimationListener(listener);
}
mCircleView.clearAnimation();
mCircleView.startAnimation(mScaleDownToStartAnimation);
}
private void setTargetOffsetTopAndBottom(int offset, boolean requiresUpdate) {
mCircleView.bringToFront();
mCircleView.offsetTopAndBottom(offset);
mCurrentTargetOffsetTop = mCircleView.getTop();
if (requiresUpdate && android.os.Build.VERSION.SDK_INT < 11) {
invalidate();
}
}
private void onSecondaryPointerUp(MotionEvent ev) {
final int pointerIndex = MotionEventCompat.getActionIndex(ev);
final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
}
}
/**
* Classes that wish to be notified when the swipe gesture correctly
* triggers a refresh should implement this interface.
*/
public interface OnRefreshListener {
public void onRefresh();
}
} | am 6b828242: am 86552551: am 38bc495a: Reset the alpha of the circle view after animations complete
* commit '6b82824263812a356068ef83f507353f1dd00017':
Reset the alpha of the circle view after animations complete
| v4/java/android/support/v4/widget/SwipeRefreshLayout.java | am 6b828242: am 86552551: am 38bc495a: Reset the alpha of the circle view after animations complete | |
Java | apache-2.0 | ed0aabc366d1044f0487f1de0cf45d339d3a5cdc | 0 | manovotn/core,antoinesd/weld-core,manovotn/core,antoinesd/weld-core,weld/core,weld/core,antoinesd/weld-core,manovotn/core | package org.jboss.webbeans.tck.integration.jbossas;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import org.apache.log4j.Logger;
import org.jboss.jsr299.tck.api.Configurable;
import org.jboss.jsr299.tck.api.Configuration;
import org.jboss.jsr299.tck.spi.Containers;
/**
*
* @author jeffgenender
* @author Pete Muir
*
*/
public abstract class AbstractContainersImpl implements Configurable, Containers
{
public static String JAVA_OPTS = "-ea";
public static final String JBOSS_HOME_PROPERTY_NAME = "jboss.home";
public static final String JAVA_OPTS_PROPERTY_NAME = "java.opts";
public static final String JBOSS_AS_DIR_PROPERTY_NAME = "jboss-as.dir";
public static final String JBOSS_BOOT_TIMEOUT_PROPERTY_NAME = "jboss.boot.timeout";
public static final String FORCE_RESTART_PROPERTY_NAME = "jboss.force.restart";
private static Logger log = Logger.getLogger(AbstractContainersImpl.class);
private Configuration configuration;
protected String jbossHome;
private String jbossHttpUrl;
private boolean jbossWasStarted;
private long bootTimeout;
private String javaOpts;
protected static void copy(InputStream inputStream, File file) throws IOException
{
OutputStream os = new FileOutputStream(file);
try
{
byte[] buf = new byte[1024];
int i = 0;
while ((i = inputStream.read(buf)) != -1)
{
os.write(buf, 0, i);
}
}
finally
{
os.close();
}
}
public void setConfiguration(Configuration configuration)
{
this.configuration = configuration;
this.jbossHttpUrl = "http://" + configuration.getHost() + "/";
}
protected boolean isJBossUp()
{
// Check that JBoss is up!
try
{
URLConnection connection = new URL(jbossHttpUrl).openConnection();
if (!(connection instanceof HttpURLConnection))
{
throw new IllegalStateException("Not an http connection! " + connection);
}
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.connect();
if (httpConnection.getResponseCode() != HttpURLConnection.HTTP_OK)
{
return false;
}
}
catch (Exception e)
{
return false;
}
log.info("Successfully connected to JBoss AS at " + jbossHttpUrl);
return true;
}
public void setup() throws IOException
{
if (System.getProperty(JBOSS_AS_DIR_PROPERTY_NAME) != null)
{
File jbossAsDir = new File(System.getProperty(JBOSS_AS_DIR_PROPERTY_NAME));
if (jbossAsDir.isDirectory())
{
File buildProperties = new File(jbossAsDir, "build.properties");
if (buildProperties.exists())
{
System.getProperties().load(new FileReader(buildProperties));
}
File localBuildProperties = new File(jbossAsDir, "local.build.properties");
if (localBuildProperties.exists())
{
System.getProperties().load(new FileReader(localBuildProperties));
}
}
}
jbossHome = System.getProperty(JBOSS_HOME_PROPERTY_NAME);
javaOpts = System.getProperty(JAVA_OPTS_PROPERTY_NAME);
if (javaOpts == null)
{
javaOpts = "";
}
javaOpts = "\"" + javaOpts + JAVA_OPTS + "\"";
if (jbossHome == null)
{
throw new IllegalArgumentException("-D" + JBOSS_HOME_PROPERTY_NAME + " must be set");
}
else
{
log.info("Using JBoss instance in " + jbossHome + " at URL " + configuration.getHost());
}
this.bootTimeout = Long.getLong(JBOSS_BOOT_TIMEOUT_PROPERTY_NAME, 240000);
if (Boolean.getBoolean(FORCE_RESTART_PROPERTY_NAME))
{
if (isJBossUp())
{
log.info("Shutting down JBoss instance as in force-restart mode");
shutDownJBoss();
try
{
Thread.sleep(10000);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
}
}
if (!isJBossUp())
{
jbossWasStarted = true;
launch(jbossHome, "run", "");
log.info("Starting JBoss instance");
// Wait for JBoss to come up
long timeoutTime = System.currentTimeMillis() + bootTimeout;
boolean interrupted = false;
while (timeoutTime > System.currentTimeMillis())
{
if (isJBossUp())
{
log.info("Started JBoss instance");
return;
}
try
{
Thread.sleep(200);
}
catch (InterruptedException e)
{
interrupted = true;
}
}
if (interrupted)
{
Thread.currentThread().interrupt();
}
// If we got this far something went wrong
log.warn("Unable to connect to JBoss instance after " + bootTimeout + "ms, giving up!");
launch(jbossHome, "shutdown", "-S");
throw new IllegalStateException("Error connecting to JBoss instance");
}
else
{
return;
}
}
public void cleanup() throws IOException
{
if (jbossWasStarted)
{
log.info("Shutting down JBoss instance");
shutDownJBoss();
}
}
private void shutDownJBoss() throws IOException
{
launch(jbossHome, "shutdown", "-S");
log.info("Shut down JBoss AS");
}
private static void launch(String jbossHome, String scriptFileName, String params) throws IOException
{
String osName = System.getProperty("os.name");
Runtime runtime = Runtime.getRuntime();
Process p = null;
if (osName.startsWith("Windows"))
{
String command[] = {
"cmd.exe",
"/C",
"set JAVA_OPTS=" + JAVA_OPTS + " & cd " + jbossHome + "\\bin & " + scriptFileName + ".bat " + params
};
p = runtime.exec(command);
}
else
{
String command[] = {
"sh",
"-c",
"cd /D " + jbossHome + "/bin;set JAVA_OPTS=" + JAVA_OPTS + " ./" + scriptFileName + ".sh " + params
};
p = runtime.exec(command);
}
dump(p.getErrorStream());
dump(p.getInputStream());
}
protected static void dump(final InputStream is)
{
new Thread(new Runnable()
{
public void run()
{
try
{
DataOutputStream out = new DataOutputStream(new FileOutputStream(System.getProperty("java.io.tmpdir") + "jboss.log"));
int c;
while((c = is.read()) != -1)
{
out.writeByte(c);
}
is.close();
out.close();
}
catch(IOException e)
{
System.err.println("Error Writing/Reading Streams.");
}
}
}).start();
}
} | jboss-tck-runner/src/main/java/org/jboss/webbeans/tck/integration/jbossas/AbstractContainersImpl.java | package org.jboss.webbeans.tck.integration.jbossas;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import org.apache.log4j.Logger;
import org.jboss.jsr299.tck.api.Configurable;
import org.jboss.jsr299.tck.api.Configuration;
import org.jboss.jsr299.tck.spi.Containers;
/**
*
* @author jeffgenender
* @author Pete Muir
*
*/
public abstract class AbstractContainersImpl implements Configurable, Containers
{
public static String JAVA_OPTS = "-ea";
public static final String JBOSS_HOME_PROPERTY_NAME = "jboss.home";
public static final String JAVA_OPTS_PROPERTY_NAME = "java.opts";
public static final String JBOSS_AS_DIR_PROPERTY_NAME = "jboss-as.dir";
public static final String JBOSS_BOOT_TIMEOUT_PROPERTY_NAME = "jboss.boot.timeout";
public static final String FORCE_RESTART_PROPERTY_NAME = "jboss.force.restart";
private static Logger log = Logger.getLogger(AbstractContainersImpl.class);
private Configuration configuration;
protected String jbossHome;
private String jbossHttpUrl;
private boolean jbossWasStarted;
private long bootTimeout;
private String javaOpts;
protected static void copy(InputStream inputStream, File file) throws IOException
{
OutputStream os = new FileOutputStream(file);
try
{
byte[] buf = new byte[1024];
int i = 0;
while ((i = inputStream.read(buf)) != -1)
{
os.write(buf, 0, i);
}
}
finally
{
os.close();
}
}
public void setConfiguration(Configuration configuration)
{
this.configuration = configuration;
this.jbossHttpUrl = "http://" + configuration.getHost() + "/";
}
protected boolean isJBossUp()
{
// Check that JBoss is up!
try
{
URLConnection connection = new URL(jbossHttpUrl).openConnection();
if (!(connection instanceof HttpURLConnection))
{
throw new IllegalStateException("Not an http connection! " + connection);
}
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.connect();
if (httpConnection.getResponseCode() != HttpURLConnection.HTTP_OK)
{
return false;
}
}
catch (Exception e)
{
return false;
}
log.info("Successfully connected to JBoss AS at " + jbossHttpUrl);
return true;
}
public void setup() throws IOException
{
if (System.getProperty(JBOSS_AS_DIR_PROPERTY_NAME) != null)
{
File jbossAsDir = new File(System.getProperty(JBOSS_AS_DIR_PROPERTY_NAME));
if (jbossAsDir.isDirectory())
{
File buildProperties = new File(jbossAsDir, "build.properties");
if (buildProperties.exists())
{
System.getProperties().load(new FileReader(buildProperties));
}
File localBuildProperties = new File(jbossAsDir, "local.build.properties");
if (localBuildProperties.exists())
{
System.getProperties().load(new FileReader(localBuildProperties));
}
}
}
jbossHome = System.getProperty(JBOSS_HOME_PROPERTY_NAME);
javaOpts = System.getProperty(JAVA_OPTS_PROPERTY_NAME);
if (javaOpts == null)
{
javaOpts = "";
}
javaOpts = "\"" + javaOpts + JAVA_OPTS + "\"";
if (jbossHome == null)
{
throw new IllegalArgumentException("-D" + JBOSS_HOME_PROPERTY_NAME + " must be set");
}
else
{
log.info("Using JBoss instance in " + jbossHome + " at URL " + configuration.getHost());
}
this.bootTimeout = Long.getLong(JBOSS_BOOT_TIMEOUT_PROPERTY_NAME, 120000);
if (Boolean.getBoolean(FORCE_RESTART_PROPERTY_NAME))
{
if (isJBossUp())
{
log.info("Shutting down JBoss instance as in force-restart mode");
shutDownJBoss();
try
{
Thread.sleep(10000);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
}
}
if (!isJBossUp())
{
jbossWasStarted = true;
launch(jbossHome, "run", "");
log.info("Starting JBoss instance");
// Wait for JBoss to come up
long timeoutTime = System.currentTimeMillis() + bootTimeout;
boolean interrupted = false;
while (timeoutTime > System.currentTimeMillis())
{
if (isJBossUp())
{
log.info("Started JBoss instance");
return;
}
try
{
Thread.sleep(200);
}
catch (InterruptedException e)
{
interrupted = true;
}
}
if (interrupted)
{
Thread.currentThread().interrupt();
}
// If we got this far something went wrong
log.warn("Unable to connect to JBoss instance after " + bootTimeout + "ms, giving up!");
launch(jbossHome, "shutdown", "-S");
throw new IllegalStateException("Error connecting to JBoss instance");
}
else
{
return;
}
}
public void cleanup() throws IOException
{
if (jbossWasStarted)
{
log.info("Shutting down JBoss instance");
shutDownJBoss();
}
}
private void shutDownJBoss() throws IOException
{
launch(jbossHome, "shutdown", "-S");
log.info("Shut down JBoss AS");
}
private static void launch(String jbossHome, String scriptFileName, String params) throws IOException
{
String osName = System.getProperty("os.name");
Runtime runtime = Runtime.getRuntime();
Process p = null;
if (osName.startsWith("Windows"))
{
String command[] = {
"cmd.exe",
"/C",
"set JAVA_OPTS=" + JAVA_OPTS + " & cd " + jbossHome + "\\bin & " + scriptFileName + ".bat " + params
};
p = runtime.exec(command);
}
else
{
String command[] = {
"sh",
"-c",
"cd /D " + jbossHome + "/bin;set JAVA_OPTS=" + JAVA_OPTS + " ./" + scriptFileName + ".sh " + params
};
p = runtime.exec(command);
}
dump(p.getErrorStream());
dump(p.getInputStream());
}
protected static void dump(final InputStream is)
{
new Thread(new Runnable()
{
public void run()
{
try
{
DataOutputStream out = new DataOutputStream(new FileOutputStream(System.getProperty("java.io.tmpdir") + "jboss.log"));
int c;
while((c = is.read()) != -1)
{
out.writeByte(c);
}
is.close();
out.close();
}
catch(IOException e)
{
System.err.println("Error Writing/Reading Streams.");
}
}
}).start();
}
} | Increase the default JBoss boot timeout
git-svn-id: 811cd8a17a8c3c0c263af499002feedd54a892d0@1551 1c488680-804c-0410-94cd-c6b725194a0e
| jboss-tck-runner/src/main/java/org/jboss/webbeans/tck/integration/jbossas/AbstractContainersImpl.java | Increase the default JBoss boot timeout | |
Java | apache-2.0 | 42d9d7ade7bad831299e78712b89275ca2d7b4c7 | 0 | grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation | package com.navigation.reactnative;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import com.facebook.react.ReactApplication;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.modules.core.DeviceEventManagerModule;
public class LinkActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
finish();
}
@Override
protected void onDestroy() {
Activity currentActivity = getReactContext().getCurrentActivity();
Intent intent = getIntent();
Uri uri = intent.getData();
if (currentActivity == null) {
Intent mainIntent = getReactContext().getPackageManager().getLaunchIntentForPackage(getReactContext().getPackageName());
mainIntent.setData(uri);
startActivity(mainIntent);
} else {
DeviceEventManagerModule deviceEventManagerModule = getReactContext().getNativeModule(DeviceEventManagerModule.class);
deviceEventManagerModule.emitNewIntentReceived(uri);
}
super.onDestroy();
}
private ReactContext getReactContext() {
return ((ReactApplication) getApplication()).getReactNativeHost().getReactInstanceManager().getCurrentReactContext();
}
}
| NavigationReactNative/src/android/app/src/main/java/com/navigation/reactnative/LinkActivity.java | package com.navigation.reactnative;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import com.facebook.react.ReactApplication;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.modules.core.DeviceEventManagerModule;
public class LinkActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Activity currentActivity = getReactContext().getCurrentActivity();
Intent intent = getIntent();
Uri uri = intent.getData();
if (currentActivity == null) {
Intent mainIntent = getReactContext().getPackageManager().getLaunchIntentForPackage(getReactContext().getPackageName());
mainIntent.setData(uri);
startActivity(mainIntent);
} else {
DeviceEventManagerModule deviceEventManagerModule = getReactContext().getNativeModule(DeviceEventManagerModule.class);
deviceEventManagerModule.emitNewIntentReceived(uri);
}
finish();
}
private ReactContext getReactContext() {
return ((ReactApplication) getApplication()).getReactNativeHost().getReactInstanceManager().getCurrentReactContext();
}
}
| Launched activity from onDestroy
Need to give the LinkActivity time to finish before starting the shared element animation. Otherwise the transition gets stuck and the new activity doesn't launch
| NavigationReactNative/src/android/app/src/main/java/com/navigation/reactnative/LinkActivity.java | Launched activity from onDestroy | |
Java | apache-2.0 | acae7e11527f1dec074343accb1d9a382416e059 | 0 | konradcichy/java_pft,konradcichy/java_pft | package pl.stqa.pft.addressbook.tests;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import pl.stqa.pft.addressbook.model.ContactData;
import pl.stqa.pft.addressbook.model.Contacts;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.testng.Assert.assertEquals;
/**
* Created by Konrad on 03/06/2017.
*/
public class ContactModificationTests extends TestBase {
@BeforeMethod
public void ensurePreconditions() {
app.group().ensureGroupExisting();
app.goTo().contactHomePage();
if (app.contact().all().size() == 0) {
app.goTo().contactPage();
ContactData contact = new ContactData().withFirstName("Mike").withLastName("Janovsky")
.withAddress("Los Angeles 11th Avenue").withHomePhone("111").withMobilePhone("3333")
.withWorkPhone("4444").withEmail("emailmike@gmail.com").withGroup("Test1");
app.contact().create(contact);
}
}
@Test(enabled = true)
public void ContactModificationTest() {
app.goTo().contactHomePage();
Contacts before = app.contact().all();
ContactData modifiedContact = before.iterator().next();
ContactData contact = new ContactData().withId(modifiedContact.getId()).withFirstName("Mike2")
.withLastName("Janovsky2").withAddress("Los Angeles 11th Avenue2").withHomePhone("home2")
.withWorkPhone(null).withMobilePhone(null)
.withEmail("emailmike@gmail.com2").withGroup("Test1");
app.contact().modify(contact);
assertThat(app.contact().Count(),equalTo(before.size()));
Contacts after = app.contact().all();
assertThat(after, equalTo(before.without(modifiedContact).withAdded(contact)));
}
}
| addressbook-web-tests/src/test/java/pl/stqa/pft/addressbook/tests/ContactModificationTests.java | package pl.stqa.pft.addressbook.tests;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import pl.stqa.pft.addressbook.model.ContactData;
import pl.stqa.pft.addressbook.model.Contacts;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.testng.Assert.assertEquals;
/**
* Created by Konrad on 03/06/2017.
*/
public class ContactModificationTests extends TestBase {
@BeforeMethod
public void ensurePreconditions() {
app.group().ensureGroupExisting();
app.goTo().contactHomePage();
if (app.contact().all().size() == 0) {
app.goTo().contactPage();
ContactData contact = new ContactData().withFirstName("Mike").withLastName("Janovsky")
.withAddress("Los Angeles 11th Avenue").withHomePhone("111").withMobilePhone("3333")
.withWorkPhone("4444").withEmail("emailmike@gmail.com").withGroup("test1");
app.contact().create(contact);
}
}
@Test(enabled = true)
public void ContactModificationTest() {
app.goTo().contactHomePage();
Contacts before = app.contact().all();
ContactData modifiedContact = before.iterator().next();
ContactData contact = new ContactData().withId(modifiedContact.getId()).withFirstName("Mike2")
.withLastName("Janovsky2").withAddress("Los Angeles 11th Avenue2").withHomePhone("home2")
.withWorkPhone(null).withMobilePhone(null)
.withEmail("emailmike@gmail.com2").withGroup("test1");
app.contact().modify(contact);
assertThat(app.contact().Count(),equalTo(before.size()));
Contacts after = app.contact().all();
assertThat(after, equalTo(before.without(modifiedContact).withAdded(contact)));
}
}
| fix broken tests
| addressbook-web-tests/src/test/java/pl/stqa/pft/addressbook/tests/ContactModificationTests.java | fix broken tests | |
Java | apache-2.0 | cde6d31ce4e501269c4524b243d676072dc387d5 | 0 | allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vfs.impl.local;
import com.intellij.ide.GeneralSettings;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.*;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.*;
import com.intellij.openapi.vfs.ex.VirtualFileManagerEx;
import com.intellij.openapi.vfs.newvfs.ManagingFS;
import com.intellij.openapi.vfs.newvfs.RefreshQueue;
import com.intellij.openapi.vfs.newvfs.VfsImplUtil;
import com.intellij.openapi.vfs.newvfs.impl.FakeVirtualFile;
import com.intellij.util.ArrayUtil;
import com.intellij.util.PathUtilRt;
import com.intellij.util.ThrowableConsumer;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.SafeFileOutputStream;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.*;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
/**
* @author Dmitry Avdeev
*/
public abstract class LocalFileSystemBase extends LocalFileSystem {
protected static final Logger LOG = Logger.getInstance(LocalFileSystemBase.class);
private static final FileAttributes FAKE_ROOT_ATTRIBUTES =
new FileAttributes(true, false, false, false, DEFAULT_LENGTH, DEFAULT_TIMESTAMP, false);
private final List<LocalFileOperationsHandler> myHandlers = new ArrayList<>();
@Override
@Nullable
public VirtualFile findFileByPath(@NotNull String path) {
return VfsImplUtil.findFileByPath(this, path);
}
@Override
public VirtualFile findFileByPathIfCached(@NotNull String path) {
return VfsImplUtil.findFileByPathIfCached(this, path);
}
@Override
@Nullable
public VirtualFile refreshAndFindFileByPath(@NotNull String path) {
return VfsImplUtil.refreshAndFindFileByPath(this, path);
}
@Override
public VirtualFile findFileByIoFile(@NotNull File file) {
return findFileByPath(FileUtil.toSystemIndependentName(file.getAbsolutePath()));
}
@NotNull
private static File convertToIOFile(@NotNull VirtualFile file) {
String path = file.getPath();
if (StringUtil.endsWithChar(path, ':') && path.length() == 2 && SystemInfo.isWindows) {
path += "/"; // Make 'c:' resolve to a root directory for drive c:, not the current directory on that drive
}
return new File(path);
}
@NotNull
private static File convertToIOFileAndCheck(@NotNull VirtualFile file) throws FileNotFoundException {
File ioFile = convertToIOFile(file);
if (SystemInfo.isUnix) { // avoid opening fifo files
FileAttributes attributes = FileSystemUtil.getAttributes(ioFile);
if (attributes != null && !attributes.isFile()) {
throw new FileNotFoundException("Not a file: " + ioFile + " (type=" + attributes.type + ')');
}
}
return ioFile;
}
@Override
public boolean exists(@NotNull VirtualFile file) {
return getAttributes(file) != null;
}
@Override
public long getLength(@NotNull VirtualFile file) {
FileAttributes attributes = getAttributes(file);
return attributes != null ? attributes.length : DEFAULT_LENGTH;
}
@Override
public long getTimeStamp(@NotNull VirtualFile file) {
FileAttributes attributes = getAttributes(file);
return attributes != null ? attributes.lastModified : DEFAULT_TIMESTAMP;
}
@Override
public boolean isDirectory(@NotNull VirtualFile file) {
FileAttributes attributes = getAttributes(file);
return attributes != null && attributes.isDirectory();
}
@Override
public boolean isWritable(@NotNull VirtualFile file) {
FileAttributes attributes = getAttributes(file);
return attributes != null && attributes.isWritable();
}
@Override
public boolean isSymLink(@NotNull VirtualFile file) {
FileAttributes attributes = getAttributes(file);
return attributes != null && attributes.isSymLink();
}
@Override
public String resolveSymLink(@NotNull VirtualFile file) {
return FileSystemUtil.resolveSymLink(file.getPath());
}
@Override
@NotNull
public String[] list(@NotNull VirtualFile file) {
if (file.getParent() == null) {
File[] roots = File.listRoots();
if (roots.length == 1 && roots[0].getName().isEmpty()) {
String[] list = roots[0].list();
if (list != null) return list;
LOG.warn("Root '" + roots[0] + "' has no children - is it readable?");
return ArrayUtil.EMPTY_STRING_ARRAY;
}
if (file.getName().isEmpty()) {
// return drive letter names for the 'fake' root on windows
String[] names = new String[roots.length];
for (int i = 0; i < names.length; i++) {
String name = roots[i].getPath();
name = StringUtil.trimTrailing(name, File.separatorChar);
names[i] = name;
}
return names;
}
}
String[] names = convertToIOFile(file).list();
return names == null ? ArrayUtil.EMPTY_STRING_ARRAY : names;
}
@Override
@NotNull
public String getProtocol() {
return PROTOCOL;
}
@Override
public boolean isReadOnly() {
return false;
}
@Override
@Nullable
protected String normalize(@NotNull String path) {
if (path.isEmpty()) {
try {
path = new File("").getCanonicalPath();
}
catch (IOException e) {
return path;
}
}
else if (SystemInfo.isWindows) {
if (path.charAt(0) == '/' && !path.startsWith("//")) {
path = path.substring(1); // hack over new File(path).toURI().toURL().getFile()
}
try {
path = FileUtil.resolveShortWindowsName(path);
}
catch (IOException e) {
return null;
}
}
File file = new File(path);
if (!isAbsoluteFileOrDriveLetter(file)) {
path = file.getAbsolutePath();
}
return FileUtil.normalize(path);
}
private static boolean isAbsoluteFileOrDriveLetter(@NotNull File file) {
String path = file.getPath();
if (SystemInfo.isWindows && path.length() == 2 && path.charAt(1) == ':') {
// just drive letter.
// return true, despite the fact that technically it's not an absolute path
return true;
}
return file.isAbsolute();
}
@Override
public VirtualFile refreshAndFindFileByIoFile(@NotNull File file) {
String path = FileUtil.toSystemIndependentName(file.getAbsolutePath());
return refreshAndFindFileByPath(path);
}
@Override
public void refreshIoFiles(@NotNull Iterable<? extends File> files) {
refreshIoFiles(files, false, false, null);
}
@Override
public void refreshIoFiles(@NotNull Iterable<? extends File> files, boolean async, boolean recursive, @Nullable Runnable onFinish) {
VirtualFileManagerEx manager = (VirtualFileManagerEx)VirtualFileManager.getInstance();
Application app = ApplicationManager.getApplication();
boolean fireCommonRefreshSession = app.isDispatchThread() || app.isWriteAccessAllowed();
if (fireCommonRefreshSession) manager.fireBeforeRefreshStart(false);
try {
List<VirtualFile> filesToRefresh = new ArrayList<>();
for (File file : files) {
VirtualFile virtualFile = refreshAndFindFileByIoFile(file);
if (virtualFile != null) {
filesToRefresh.add(virtualFile);
}
}
RefreshQueue.getInstance().refresh(async, recursive, onFinish, filesToRefresh);
}
finally {
if (fireCommonRefreshSession) manager.fireAfterRefreshFinish(false);
}
}
@Override
public void refreshFiles(@NotNull Iterable<? extends VirtualFile> files) {
refreshFiles(files, false, false, null);
}
@Override
public void refreshFiles(@NotNull Iterable<? extends VirtualFile> files, boolean async, boolean recursive, @Nullable Runnable onFinish) {
RefreshQueue.getInstance().refresh(async, recursive, onFinish, ContainerUtil.toCollection(files));
}
@Override
public void registerAuxiliaryFileOperationsHandler(@NotNull LocalFileOperationsHandler handler) {
if (myHandlers.contains(handler)) {
LOG.error("Handler " + handler + " already registered.");
}
myHandlers.add(handler);
}
@Override
public void unregisterAuxiliaryFileOperationsHandler(@NotNull LocalFileOperationsHandler handler) {
if (!myHandlers.remove(handler)) {
LOG.error("Handler " + handler + " haven't been registered or already unregistered.");
}
}
private boolean auxDelete(@NotNull VirtualFile file) throws IOException {
for (LocalFileOperationsHandler handler : myHandlers) {
if (handler.delete(file)) return true;
}
return false;
}
private boolean auxMove(@NotNull VirtualFile file, @NotNull VirtualFile toDir) throws IOException {
for (LocalFileOperationsHandler handler : myHandlers) {
if (handler.move(file, toDir)) return true;
}
return false;
}
private boolean auxCopy(@NotNull VirtualFile file, @NotNull VirtualFile toDir, @NotNull String copyName) throws IOException {
for (LocalFileOperationsHandler handler : myHandlers) {
File copy = handler.copy(file, toDir, copyName);
if (copy != null) return true;
}
return false;
}
private boolean auxRename(@NotNull VirtualFile file, @NotNull String newName) throws IOException {
for (LocalFileOperationsHandler handler : myHandlers) {
if (handler.rename(file, newName)) return true;
}
return false;
}
private boolean auxCreateFile(@NotNull VirtualFile dir, @NotNull String name) throws IOException {
for (LocalFileOperationsHandler handler : myHandlers) {
if (handler.createFile(dir, name)) return true;
}
return false;
}
private boolean auxCreateDirectory(@NotNull VirtualFile dir, @NotNull String name) throws IOException {
for (LocalFileOperationsHandler handler : myHandlers) {
if (handler.createDirectory(dir, name)) return true;
}
return false;
}
private void auxNotifyCompleted(@NotNull ThrowableConsumer<LocalFileOperationsHandler, IOException> consumer) {
for (LocalFileOperationsHandler handler : myHandlers) {
handler.afterDone(consumer);
}
}
@Override
@NotNull
public VirtualFile createChildDirectory(Object requestor, @NotNull VirtualFile parent, @NotNull String dir) throws IOException {
if (!isValidName(dir)) {
throw new IOException(VfsBundle.message("directory.invalid.name.error", dir));
}
if (!parent.exists() || !parent.isDirectory()) {
throw new IOException(VfsBundle.message("vfs.target.not.directory.error", parent.getPath()));
}
if (parent.findChild(dir) != null) {
throw new IOException(VfsBundle.message("vfs.target.already.exists.error", parent.getPath() + "/" + dir));
}
File ioParent = convertToIOFile(parent);
if (!ioParent.isDirectory()) {
throw new IOException(VfsBundle.message("target.not.directory.error", ioParent.getPath()));
}
if (!auxCreateDirectory(parent, dir)) {
File ioDir = new File(ioParent, dir);
if (!(ioDir.mkdirs() || ioDir.isDirectory())) {
throw new IOException(VfsBundle.message("new.directory.failed.error", ioDir.getPath()));
}
}
auxNotifyCompleted(handler -> handler.createDirectory(parent, dir));
return new FakeVirtualFile(parent, dir);
}
@NotNull
@Override
public VirtualFile createChildFile(Object requestor, @NotNull VirtualFile parent, @NotNull String file) throws IOException {
if (!isValidName(file)) {
throw new IOException(VfsBundle.message("file.invalid.name.error", file));
}
if (!parent.exists() || !parent.isDirectory()) {
throw new IOException(VfsBundle.message("vfs.target.not.directory.error", parent.getPath()));
}
if (parent.findChild(file) != null) {
throw new IOException(VfsBundle.message("vfs.target.already.exists.error", parent.getPath() + "/" + file));
}
File ioParent = convertToIOFile(parent);
if (!ioParent.isDirectory()) {
throw new IOException(VfsBundle.message("target.not.directory.error", ioParent.getPath()));
}
if (!auxCreateFile(parent, file)) {
File ioFile = new File(ioParent, file);
if (!FileUtil.createIfDoesntExist(ioFile)) {
throw new IOException(VfsBundle.message("new.file.failed.error", ioFile.getPath()));
}
}
auxNotifyCompleted(handler -> handler.createFile(parent, file));
return new FakeVirtualFile(parent, file);
}
@Override
public void deleteFile(Object requestor, @NotNull VirtualFile file) throws IOException {
if (file.getParent() == null) {
throw new IOException(VfsBundle.message("cannot.delete.root.directory", file.getPath()));
}
if (!auxDelete(file)) {
File ioFile = convertToIOFile(file);
if (!FileUtil.delete(ioFile)) {
throw new IOException(VfsBundle.message("delete.failed.error", ioFile.getPath()));
}
}
auxNotifyCompleted(handler -> handler.delete(file));
}
@Override
public boolean isCaseSensitive() {
return SystemInfo.isFileSystemCaseSensitive;
}
@Override
public boolean isValidName(@NotNull String name) {
return PathUtilRt.isValidFileName(name, false);
}
@Override
@NotNull
public InputStream getInputStream(@NotNull VirtualFile file) throws IOException {
return new BufferedInputStream(new FileInputStream(convertToIOFileAndCheck(file)));
}
@Override
@NotNull
public byte[] contentsToByteArray(@NotNull VirtualFile file) throws IOException {
try (InputStream stream = new FileInputStream(convertToIOFileAndCheck(file))) {
long l = file.getLength();
if (l >= FileUtilRt.LARGE_FOR_CONTENT_LOADING) throw new FileTooBigException(file.getPath());
int length = (int)l;
if (length < 0) throw new IOException("Invalid file length: " + length + ", " + file);
// io_util.c#readBytes allocates custom native stack buffer for io operation with malloc if io request > 8K
// so let's do buffered requests with buffer size 8192 that will use stack allocated buffer
return loadBytes(length <= 8192 ? stream : new BufferedInputStream(stream), length);
}
}
@NotNull
private static byte[] loadBytes(@NotNull InputStream stream, int length) throws IOException {
byte[] bytes = new byte[length];
int count = 0;
while (count < length) {
int n = stream.read(bytes, count, length - count);
if (n <= 0) break;
count += n;
}
if (count < length) {
// this may happen with encrypted files, see IDEA-143773
return Arrays.copyOf(bytes, count);
}
return bytes;
}
@Override
@NotNull
public OutputStream getOutputStream(@NotNull VirtualFile file, Object requestor, long modStamp, long timeStamp) throws IOException {
File ioFile = convertToIOFileAndCheck(file);
OutputStream stream =
useSafeStream(requestor, file) ? new SafeFileOutputStream(ioFile, SystemInfo.isUnix) : new FileOutputStream(ioFile);
return new BufferedOutputStream(stream) {
@Override
public void close() throws IOException {
super.close();
if (timeStamp > 0 && ioFile.exists()) {
if (!ioFile.setLastModified(timeStamp)) {
LOG.warn("Failed: " + ioFile.getPath() + ", new:" + timeStamp + ", old:" + ioFile.lastModified());
}
}
}
};
}
// note: keep in sync with SafeWriteUtil#useSafeStream
private static boolean useSafeStream(Object requestor, VirtualFile file) {
return requestor instanceof SafeWriteRequestor && GeneralSettings.getInstance().isUseSafeWrite() && !file.is(VFileProperty.SYMLINK);
}
@Override
public void moveFile(Object requestor, @NotNull VirtualFile file, @NotNull VirtualFile newParent) throws IOException {
String name = file.getName();
if (!file.exists()) {
throw new IOException(VfsBundle.message("vfs.file.not.exist.error", file.getPath()));
}
if (file.getParent() == null) {
throw new IOException(VfsBundle.message("cannot.rename.root.directory", file.getPath()));
}
if (!newParent.exists() || !newParent.isDirectory()) {
throw new IOException(VfsBundle.message("vfs.target.not.directory.error", newParent.getPath()));
}
if (newParent.findChild(name) != null) {
throw new IOException(VfsBundle.message("vfs.target.already.exists.error", newParent.getPath() + "/" + name));
}
File ioFile = convertToIOFile(file);
if (FileSystemUtil.getAttributes(ioFile) == null) {
throw new FileNotFoundException(VfsBundle.message("file.not.exist.error", ioFile.getPath()));
}
File ioParent = convertToIOFile(newParent);
if (!ioParent.isDirectory()) {
throw new IOException(VfsBundle.message("target.not.directory.error", ioParent.getPath()));
}
File ioTarget = new File(ioParent, name);
if (ioTarget.exists()) {
throw new IOException(VfsBundle.message("target.already.exists.error", ioTarget.getPath()));
}
if (!auxMove(file, newParent)) {
if (!ioFile.renameTo(ioTarget)) {
throw new IOException(VfsBundle.message("move.failed.error", ioFile.getPath(), ioParent.getPath()));
}
}
auxNotifyCompleted(handler -> handler.move(file, newParent));
}
@Override
public void renameFile(Object requestor, @NotNull VirtualFile file, @NotNull String newName) throws IOException {
if (!isValidName(newName)) {
throw new IOException(VfsBundle.message("file.invalid.name.error", newName));
}
boolean sameName = !isCaseSensitive() && newName.equalsIgnoreCase(file.getName());
if (!file.exists()) {
throw new IOException(VfsBundle.message("vfs.file.not.exist.error", file.getPath()));
}
VirtualFile parent = file.getParent();
if (parent == null) {
throw new IOException(VfsBundle.message("cannot.rename.root.directory", file.getPath()));
}
if (!sameName && parent.findChild(newName) != null) {
throw new IOException(VfsBundle.message("vfs.target.already.exists.error", parent.getPath() + "/" + newName));
}
File ioFile = convertToIOFile(file);
if (!ioFile.exists()) {
throw new FileNotFoundException(VfsBundle.message("file.not.exist.error", ioFile.getPath()));
}
File ioTarget = new File(convertToIOFile(parent), newName);
if (!sameName && ioTarget.exists()) {
throw new IOException(VfsBundle.message("target.already.exists.error", ioTarget.getPath()));
}
if (!auxRename(file, newName)) {
if (!FileUtil.rename(ioFile, newName)) {
throw new IOException(VfsBundle.message("rename.failed.error", ioFile.getPath(), newName));
}
}
auxNotifyCompleted(handler -> handler.rename(file, newName));
}
@NotNull
@Override
public VirtualFile copyFile(Object requestor,
@NotNull VirtualFile file,
@NotNull VirtualFile newParent,
@NotNull String copyName) throws IOException {
if (!isValidName(copyName)) {
throw new IOException(VfsBundle.message("file.invalid.name.error", copyName));
}
if (!file.exists()) {
throw new IOException(VfsBundle.message("vfs.file.not.exist.error", file.getPath()));
}
if (!newParent.exists() || !newParent.isDirectory()) {
throw new IOException(VfsBundle.message("vfs.target.not.directory.error", newParent.getPath()));
}
if (newParent.findChild(copyName) != null) {
throw new IOException(VfsBundle.message("vfs.target.already.exists.error", newParent.getPath() + "/" + copyName));
}
FileAttributes attributes = getAttributes(file);
if (attributes == null) {
throw new FileNotFoundException(VfsBundle.message("file.not.exist.error", file.getPath()));
}
if (attributes.isSpecial()) {
throw new FileNotFoundException("Not a file: " + file);
}
File ioParent = convertToIOFile(newParent);
if (!ioParent.isDirectory()) {
throw new IOException(VfsBundle.message("target.not.directory.error", ioParent.getPath()));
}
File ioTarget = new File(ioParent, copyName);
if (ioTarget.exists()) {
throw new IOException(VfsBundle.message("target.already.exists.error", ioTarget.getPath()));
}
if (!auxCopy(file, newParent, copyName)) {
try {
File ioFile = convertToIOFile(file);
FileUtil.copyFileOrDir(ioFile, ioTarget, attributes.isDirectory());
}
catch (IOException e) {
FileUtil.delete(ioTarget);
throw e;
}
}
auxNotifyCompleted(handler -> handler.copy(file, newParent, copyName));
return new FakeVirtualFile(newParent, copyName);
}
@Override
public void setTimeStamp(@NotNull VirtualFile file, long timeStamp) {
File ioFile = convertToIOFile(file);
if (ioFile.exists() && !ioFile.setLastModified(timeStamp)) {
LOG.warn("Failed: " + file.getPath() + ", new:" + timeStamp + ", old:" + ioFile.lastModified());
}
}
@Override
public void setWritable(@NotNull VirtualFile file, boolean writableFlag) throws IOException {
String path = FileUtil.toSystemDependentName(file.getPath());
FileUtil.setReadOnlyAttribute(path, !writableFlag);
if (FileUtil.canWrite(path) != writableFlag) {
throw new IOException("Failed to change read-only flag for " + path);
}
}
private static final List<String> ourRootPaths;
static {
//noinspection SpellCheckingInspection
ourRootPaths = StringUtil.split(System.getProperty("idea.persistentfs.roots", ""), File.pathSeparator);
Collections.sort(ourRootPaths, (o1, o2) -> o2.length() - o1.length()); // longest first
}
@NotNull
@Override
protected String extractRootPath(@NotNull String path) {
if (path.isEmpty()) {
try {
path = new File("").getCanonicalPath();
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
for (String customRootPath : ourRootPaths) {
if (path.startsWith(customRootPath)) return customRootPath;
}
if (SystemInfo.isWindows) {
if (path.length() >= 2 && path.charAt(1) == ':') {
// Drive letter
return path.substring(0, 2).toUpperCase(Locale.US);
}
if (path.startsWith("//") || path.startsWith("\\\\")) {
// UNC. Must skip exactly two path elements like [\\ServerName\ShareName]\pathOnShare\file.txt
// Root path is in square brackets here.
int slashCount = 0;
int idx;
for (idx = 2; idx < path.length() && slashCount < 2; idx++) {
char c = path.charAt(idx);
if (c == '\\' || c == '/') {
slashCount++;
idx--;
}
}
return path.substring(0, idx);
}
return "";
}
return StringUtil.startsWithChar(path, '/') ? "/" : "";
}
@Override
public int getRank() {
return 1;
}
@Override
public boolean markNewFilesAsDirty() {
return true;
}
@NotNull
@Override
public String getCanonicallyCasedName(@NotNull VirtualFile file) {
if (isCaseSensitive()) {
return super.getCanonicallyCasedName(file);
}
String originalFileName = file.getName();
long t = LOG.isTraceEnabled() ? System.nanoTime() : 0;
try {
File ioFile = convertToIOFile(file);
File canonicalFile = ioFile.getCanonicalFile();
String canonicalFileName = canonicalFile.getName();
if (!SystemInfo.isUnix) {
return canonicalFileName;
}
// linux & mac support symbolic links
// unfortunately canonical file resolves sym links
// so its name may differ from name of origin file
//
// Here FS is case sensitive, so let's check that original and
// canonical file names are equal if we ignore name case
if (canonicalFileName.compareToIgnoreCase(originalFileName) == 0) {
// p.s. this should cover most cases related to not symbolic links
return canonicalFileName;
}
// Ok, names are not equal. Let's try to find corresponding file name
// among original file parent directory
File parentFile = ioFile.getParentFile();
if (parentFile != null) {
// I hope ls works fast on Unix
String[] canonicalFileNames = parentFile.list();
if (canonicalFileNames != null) {
for (String name : canonicalFileNames) {
// if names are equals
if (name.compareToIgnoreCase(originalFileName) == 0) {
return name;
}
}
}
}
// No luck. So ein mist!
// Ok, garbage in, garbage out. We may return original or canonical name
// no difference. Let's return canonical name just to preserve previous
// behaviour of this code.
return canonicalFileName;
}
catch (IOException e) {
return originalFileName;
}
finally {
if (t != 0) {
t = (System.nanoTime() - t) / 1000;
LOG.trace("getCanonicallyCasedName(" + file + "): " + t + " mks");
}
}
}
@Override
public FileAttributes getAttributes(@NotNull VirtualFile file) {
String path = normalize(file.getPath());
if (path == null) return null;
if (file.getParent() == null && path.startsWith("//")) {
return FAKE_ROOT_ATTRIBUTES; // fake Windows roots
}
return FileSystemUtil.getAttributes(FileUtil.toSystemDependentName(path));
}
@Override
public void refresh(boolean asynchronous) {
RefreshQueue.getInstance().refresh(asynchronous, true, null, ManagingFS.getInstance().getRoots(this));
}
@Override
public boolean hasChildren(@NotNull VirtualFile file) {
if (file.getParent() == null) {
// assume roots always have children
return true;
}
// make sure to not load all children
try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(file.getPath()))) {
return stream.iterator().hasNext();
}
catch (InvalidPathException | IOException | SecurityException e) {
return true;
}
}
} | platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/LocalFileSystemBase.java | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vfs.impl.local;
import com.intellij.ide.GeneralSettings;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.*;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.*;
import com.intellij.openapi.vfs.ex.VirtualFileManagerEx;
import com.intellij.openapi.vfs.newvfs.ManagingFS;
import com.intellij.openapi.vfs.newvfs.RefreshQueue;
import com.intellij.openapi.vfs.newvfs.VfsImplUtil;
import com.intellij.openapi.vfs.newvfs.impl.FakeVirtualFile;
import com.intellij.util.ArrayUtil;
import com.intellij.util.PathUtilRt;
import com.intellij.util.ThrowableConsumer;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.SafeFileOutputStream;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.*;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
/**
* @author Dmitry Avdeev
*/
public abstract class LocalFileSystemBase extends LocalFileSystem {
protected static final Logger LOG = Logger.getInstance(LocalFileSystemBase.class);
private static final FileAttributes FAKE_ROOT_ATTRIBUTES =
new FileAttributes(true, false, false, false, DEFAULT_LENGTH, DEFAULT_TIMESTAMP, false);
private final List<LocalFileOperationsHandler> myHandlers = new ArrayList<>();
@Override
@Nullable
public VirtualFile findFileByPath(@NotNull String path) {
return VfsImplUtil.findFileByPath(this, path);
}
@Override
public VirtualFile findFileByPathIfCached(@NotNull String path) {
return VfsImplUtil.findFileByPathIfCached(this, path);
}
@Override
@Nullable
public VirtualFile refreshAndFindFileByPath(@NotNull String path) {
return VfsImplUtil.refreshAndFindFileByPath(this, path);
}
@Override
public VirtualFile findFileByIoFile(@NotNull File file) {
return findFileByPath(FileUtil.toSystemIndependentName(file.getAbsolutePath()));
}
@NotNull
private static File convertToIOFile(@NotNull VirtualFile file) {
String path = file.getPath();
if (StringUtil.endsWithChar(path, ':') && path.length() == 2 && SystemInfo.isWindows) {
path += "/"; // Make 'c:' resolve to a root directory for drive c:, not the current directory on that drive
}
return new File(path);
}
@NotNull
private static File convertToIOFileAndCheck(@NotNull VirtualFile file) throws FileNotFoundException {
File ioFile = convertToIOFile(file);
if (SystemInfo.isUnix) { // avoid opening fifo files
FileAttributes attributes = FileSystemUtil.getAttributes(ioFile);
if (attributes != null && !attributes.isFile()) {
throw new FileNotFoundException("Not a file: " + ioFile + " (type=" + attributes.type + ')');
}
}
return ioFile;
}
@Override
public boolean exists(@NotNull VirtualFile file) {
return getAttributes(file) != null;
}
@Override
public long getLength(@NotNull VirtualFile file) {
FileAttributes attributes = getAttributes(file);
return attributes != null ? attributes.length : DEFAULT_LENGTH;
}
@Override
public long getTimeStamp(@NotNull VirtualFile file) {
FileAttributes attributes = getAttributes(file);
return attributes != null ? attributes.lastModified : DEFAULT_TIMESTAMP;
}
@Override
public boolean isDirectory(@NotNull VirtualFile file) {
FileAttributes attributes = getAttributes(file);
return attributes != null && attributes.isDirectory();
}
@Override
public boolean isWritable(@NotNull VirtualFile file) {
FileAttributes attributes = getAttributes(file);
return attributes != null && attributes.isWritable();
}
@Override
public boolean isSymLink(@NotNull VirtualFile file) {
FileAttributes attributes = getAttributes(file);
return attributes != null && attributes.isSymLink();
}
@Override
public String resolveSymLink(@NotNull VirtualFile file) {
return FileSystemUtil.resolveSymLink(file.getPath());
}
@Override
@NotNull
public String[] list(@NotNull VirtualFile file) {
if (file.getParent() == null) {
File[] roots = File.listRoots();
if (roots.length == 1 && roots[0].getName().isEmpty()) {
String[] list = roots[0].list();
if (list != null) return list;
LOG.warn("Root '" + roots[0] + "' has no children - is it readable?");
return ArrayUtil.EMPTY_STRING_ARRAY;
}
if (file.getName().isEmpty()) {
// return drive letter names for the 'fake' root on windows
String[] names = new String[roots.length];
for (int i = 0; i < names.length; i++) {
String name = roots[i].getPath();
name = StringUtil.trimTrailing(name, File.separatorChar);
names[i] = name;
}
return names;
}
}
String[] names = convertToIOFile(file).list();
return names == null ? ArrayUtil.EMPTY_STRING_ARRAY : names;
}
@Override
@NotNull
public String getProtocol() {
return PROTOCOL;
}
@Override
public boolean isReadOnly() {
return false;
}
@Override
@Nullable
protected String normalize(@NotNull String path) {
if (path.isEmpty()) {
try {
path = new File("").getCanonicalPath();
}
catch (IOException e) {
return path;
}
}
else if (SystemInfo.isWindows) {
if (path.charAt(0) == '/' && !path.startsWith("//")) {
path = path.substring(1); // hack over new File(path).toURI().toURL().getFile()
}
try {
path = FileUtil.resolveShortWindowsName(path);
}
catch (IOException e) {
return null;
}
}
File file = new File(path);
if (!isAbsoluteFileOrDriveLetter(file)) {
path = file.getAbsolutePath();
}
return FileUtil.normalize(path);
}
private static boolean isAbsoluteFileOrDriveLetter(@NotNull File file) {
String path = file.getPath();
if (SystemInfo.isWindows && path.length() == 2 && path.charAt(1) == ':') {
// just drive letter.
// return true, despite the fact that technically it's not an absolute path
return true;
}
return file.isAbsolute();
}
@Override
public VirtualFile refreshAndFindFileByIoFile(@NotNull File file) {
String path = FileUtil.toSystemIndependentName(file.getAbsolutePath());
return refreshAndFindFileByPath(path);
}
@Override
public void refreshIoFiles(@NotNull Iterable<? extends File> files) {
refreshIoFiles(files, false, false, null);
}
@Override
public void refreshIoFiles(@NotNull Iterable<? extends File> files, boolean async, boolean recursive, @Nullable Runnable onFinish) {
VirtualFileManagerEx manager = (VirtualFileManagerEx)VirtualFileManager.getInstance();
Application app = ApplicationManager.getApplication();
boolean fireCommonRefreshSession = app.isDispatchThread() || app.isWriteAccessAllowed();
if (fireCommonRefreshSession) manager.fireBeforeRefreshStart(false);
try {
List<VirtualFile> filesToRefresh = new ArrayList<>();
for (File file : files) {
VirtualFile virtualFile = refreshAndFindFileByIoFile(file);
if (virtualFile != null) {
filesToRefresh.add(virtualFile);
}
}
RefreshQueue.getInstance().refresh(async, recursive, onFinish, filesToRefresh);
}
finally {
if (fireCommonRefreshSession) manager.fireAfterRefreshFinish(false);
}
}
@Override
public void refreshFiles(@NotNull Iterable<? extends VirtualFile> files) {
refreshFiles(files, false, false, null);
}
@Override
public void refreshFiles(@NotNull Iterable<? extends VirtualFile> files, boolean async, boolean recursive, @Nullable Runnable onFinish) {
RefreshQueue.getInstance().refresh(async, recursive, onFinish, ContainerUtil.toCollection(files));
}
@Override
public void registerAuxiliaryFileOperationsHandler(@NotNull LocalFileOperationsHandler handler) {
if (myHandlers.contains(handler)) {
LOG.error("Handler " + handler + " already registered.");
}
myHandlers.add(handler);
}
@Override
public void unregisterAuxiliaryFileOperationsHandler(@NotNull LocalFileOperationsHandler handler) {
if (!myHandlers.remove(handler)) {
LOG.error("Handler " + handler + " haven't been registered or already unregistered.");
}
}
private boolean auxDelete(@NotNull VirtualFile file) throws IOException {
for (LocalFileOperationsHandler handler : myHandlers) {
if (handler.delete(file)) return true;
}
return false;
}
private boolean auxMove(@NotNull VirtualFile file, @NotNull VirtualFile toDir) throws IOException {
for (LocalFileOperationsHandler handler : myHandlers) {
if (handler.move(file, toDir)) return true;
}
return false;
}
private boolean auxCopy(@NotNull VirtualFile file, @NotNull VirtualFile toDir, @NotNull String copyName) throws IOException {
for (LocalFileOperationsHandler handler : myHandlers) {
File copy = handler.copy(file, toDir, copyName);
if (copy != null) return true;
}
return false;
}
private boolean auxRename(@NotNull VirtualFile file, @NotNull String newName) throws IOException {
for (LocalFileOperationsHandler handler : myHandlers) {
if (handler.rename(file, newName)) return true;
}
return false;
}
private boolean auxCreateFile(@NotNull VirtualFile dir, @NotNull String name) throws IOException {
for (LocalFileOperationsHandler handler : myHandlers) {
if (handler.createFile(dir, name)) return true;
}
return false;
}
private boolean auxCreateDirectory(@NotNull VirtualFile dir, @NotNull String name) throws IOException {
for (LocalFileOperationsHandler handler : myHandlers) {
if (handler.createDirectory(dir, name)) return true;
}
return false;
}
private void auxNotifyCompleted(@NotNull ThrowableConsumer<LocalFileOperationsHandler, IOException> consumer) {
for (LocalFileOperationsHandler handler : myHandlers) {
handler.afterDone(consumer);
}
}
@Override
@NotNull
public VirtualFile createChildDirectory(Object requestor, @NotNull VirtualFile parent, @NotNull String dir) throws IOException {
if (!isValidName(dir)) {
throw new IOException(VfsBundle.message("directory.invalid.name.error", dir));
}
if (!parent.exists() || !parent.isDirectory()) {
throw new IOException(VfsBundle.message("vfs.target.not.directory.error", parent.getPath()));
}
if (parent.findChild(dir) != null) {
throw new IOException(VfsBundle.message("vfs.target.already.exists.error", parent.getPath() + "/" + dir));
}
File ioParent = convertToIOFile(parent);
if (!ioParent.isDirectory()) {
throw new IOException(VfsBundle.message("target.not.directory.error", ioParent.getPath()));
}
if (!auxCreateDirectory(parent, dir)) {
File ioDir = new File(ioParent, dir);
if (!(ioDir.mkdirs() || ioDir.isDirectory())) {
throw new IOException(VfsBundle.message("new.directory.failed.error", ioDir.getPath()));
}
}
auxNotifyCompleted(handler -> handler.createDirectory(parent, dir));
return new FakeVirtualFile(parent, dir);
}
@NotNull
@Override
public VirtualFile createChildFile(Object requestor, @NotNull VirtualFile parent, @NotNull String file) throws IOException {
if (!isValidName(file)) {
throw new IOException(VfsBundle.message("file.invalid.name.error", file));
}
if (!parent.exists() || !parent.isDirectory()) {
throw new IOException(VfsBundle.message("vfs.target.not.directory.error", parent.getPath()));
}
if (parent.findChild(file) != null) {
throw new IOException(VfsBundle.message("vfs.target.already.exists.error", parent.getPath() + "/" + file));
}
File ioParent = convertToIOFile(parent);
if (!ioParent.isDirectory()) {
throw new IOException(VfsBundle.message("target.not.directory.error", ioParent.getPath()));
}
if (!auxCreateFile(parent, file)) {
File ioFile = new File(ioParent, file);
if (!FileUtil.createIfDoesntExist(ioFile)) {
throw new IOException(VfsBundle.message("new.file.failed.error", ioFile.getPath()));
}
}
auxNotifyCompleted(handler -> handler.createFile(parent, file));
return new FakeVirtualFile(parent, file);
}
@Override
public void deleteFile(Object requestor, @NotNull VirtualFile file) throws IOException {
if (file.getParent() == null) {
throw new IOException(VfsBundle.message("cannot.delete.root.directory", file.getPath()));
}
if (!auxDelete(file)) {
File ioFile = convertToIOFile(file);
if (!FileUtil.delete(ioFile)) {
throw new IOException(VfsBundle.message("delete.failed.error", ioFile.getPath()));
}
}
auxNotifyCompleted(handler -> handler.delete(file));
}
@Override
public boolean isCaseSensitive() {
return SystemInfo.isFileSystemCaseSensitive;
}
@Override
public boolean isValidName(@NotNull String name) {
return PathUtilRt.isValidFileName(name, false);
}
@Override
@NotNull
public InputStream getInputStream(@NotNull VirtualFile file) throws IOException {
return new BufferedInputStream(new FileInputStream(convertToIOFileAndCheck(file)));
}
@Override
@NotNull
public byte[] contentsToByteArray(@NotNull VirtualFile file) throws IOException {
try (InputStream stream = new FileInputStream(convertToIOFileAndCheck(file))) {
long l = file.getLength();
if (l >= FileUtilRt.LARGE_FOR_CONTENT_LOADING) throw new FileTooBigException(file.getPath());
int length = (int)l;
if (length < 0) throw new IOException("Invalid file length: " + length + ", " + file);
// io_util.c#readBytes allocates custom native stack buffer for io operation with malloc if io request > 8K
// so let's do buffered requests with buffer size 8192 that will use stack allocated buffer
return loadBytes(length <= 8192 ? stream : new BufferedInputStream(stream), length);
}
}
@NotNull
private static byte[] loadBytes(@NotNull InputStream stream, int length) throws IOException {
byte[] bytes = new byte[length];
int count = 0;
while (count < length) {
int n = stream.read(bytes, count, length - count);
if (n <= 0) break;
count += n;
}
if (count < length) {
// this may happen with encrypted files, see IDEA-143773
return Arrays.copyOf(bytes, count);
}
return bytes;
}
@Override
@NotNull
public OutputStream getOutputStream(@NotNull VirtualFile file, Object requestor, long modStamp, long timeStamp) throws IOException {
File ioFile = convertToIOFileAndCheck(file);
OutputStream stream =
useSafeStream(requestor, file) ? new SafeFileOutputStream(ioFile, SystemInfo.isUnix) : new FileOutputStream(ioFile);
return new BufferedOutputStream(stream) {
@Override
public void close() throws IOException {
super.close();
if (timeStamp > 0 && ioFile.exists()) {
if (!ioFile.setLastModified(timeStamp)) {
LOG.warn("Failed: " + ioFile.getPath() + ", new:" + timeStamp + ", old:" + ioFile.lastModified());
}
}
}
};
}
// note: keep in sync with SafeWriteUtil#useSafeStream
private static boolean useSafeStream(Object requestor, VirtualFile file) {
return requestor instanceof SafeWriteRequestor && GeneralSettings.getInstance().isUseSafeWrite() && !file.is(VFileProperty.SYMLINK);
}
@Override
public void moveFile(Object requestor, @NotNull VirtualFile file, @NotNull VirtualFile newParent) throws IOException {
String name = file.getName();
if (!file.exists()) {
throw new IOException(VfsBundle.message("vfs.file.not.exist.error", file.getPath()));
}
if (file.getParent() == null) {
throw new IOException(VfsBundle.message("cannot.rename.root.directory", file.getPath()));
}
if (!newParent.exists() || !newParent.isDirectory()) {
throw new IOException(VfsBundle.message("vfs.target.not.directory.error", newParent.getPath()));
}
if (newParent.findChild(name) != null) {
throw new IOException(VfsBundle.message("vfs.target.already.exists.error", newParent.getPath() + "/" + name));
}
File ioFile = convertToIOFile(file);
if (FileSystemUtil.getAttributes(ioFile) == null) {
throw new FileNotFoundException(VfsBundle.message("file.not.exist.error", ioFile.getPath()));
}
File ioParent = convertToIOFile(newParent);
if (!ioParent.isDirectory()) {
throw new IOException(VfsBundle.message("target.not.directory.error", ioParent.getPath()));
}
File ioTarget = new File(ioParent, name);
if (ioTarget.exists()) {
throw new IOException(VfsBundle.message("target.already.exists.error", ioTarget.getPath()));
}
if (!auxMove(file, newParent)) {
if (!ioFile.renameTo(ioTarget)) {
throw new IOException(VfsBundle.message("move.failed.error", ioFile.getPath(), ioParent.getPath()));
}
}
auxNotifyCompleted(handler -> handler.move(file, newParent));
}
@Override
public void renameFile(Object requestor, @NotNull VirtualFile file, @NotNull String newName) throws IOException {
if (!isValidName(newName)) {
throw new IOException(VfsBundle.message("file.invalid.name.error", newName));
}
boolean sameName = !isCaseSensitive() && newName.equalsIgnoreCase(file.getName());
if (!file.exists()) {
throw new IOException(VfsBundle.message("vfs.file.not.exist.error", file.getPath()));
}
VirtualFile parent = file.getParent();
if (parent == null) {
throw new IOException(VfsBundle.message("cannot.rename.root.directory", file.getPath()));
}
if (!sameName && parent.findChild(newName) != null) {
throw new IOException(VfsBundle.message("vfs.target.already.exists.error", parent.getPath() + "/" + newName));
}
File ioFile = convertToIOFile(file);
if (!ioFile.exists()) {
throw new FileNotFoundException(VfsBundle.message("file.not.exist.error", ioFile.getPath()));
}
File ioTarget = new File(convertToIOFile(parent), newName);
if (!sameName && ioTarget.exists()) {
throw new IOException(VfsBundle.message("target.already.exists.error", ioTarget.getPath()));
}
if (!auxRename(file, newName)) {
if (!FileUtil.rename(ioFile, newName)) {
throw new IOException(VfsBundle.message("rename.failed.error", ioFile.getPath(), newName));
}
}
auxNotifyCompleted(handler -> handler.rename(file, newName));
}
@NotNull
@Override
public VirtualFile copyFile(Object requestor,
@NotNull VirtualFile file,
@NotNull VirtualFile newParent,
@NotNull String copyName) throws IOException {
if (!isValidName(copyName)) {
throw new IOException(VfsBundle.message("file.invalid.name.error", copyName));
}
if (!file.exists()) {
throw new IOException(VfsBundle.message("vfs.file.not.exist.error", file.getPath()));
}
if (!newParent.exists() || !newParent.isDirectory()) {
throw new IOException(VfsBundle.message("vfs.target.not.directory.error", newParent.getPath()));
}
if (newParent.findChild(copyName) != null) {
throw new IOException(VfsBundle.message("vfs.target.already.exists.error", newParent.getPath() + "/" + copyName));
}
FileAttributes attributes = getAttributes(file);
if (attributes == null) {
throw new FileNotFoundException(VfsBundle.message("file.not.exist.error", file.getPath()));
}
if (attributes.isSpecial()) {
throw new FileNotFoundException("Not a file: " + file);
}
File ioParent = convertToIOFile(newParent);
if (!ioParent.isDirectory()) {
throw new IOException(VfsBundle.message("target.not.directory.error", ioParent.getPath()));
}
File ioTarget = new File(ioParent, copyName);
if (ioTarget.exists()) {
throw new IOException(VfsBundle.message("target.already.exists.error", ioTarget.getPath()));
}
if (!auxCopy(file, newParent, copyName)) {
try {
File ioFile = convertToIOFile(file);
FileUtil.copyFileOrDir(ioFile, ioTarget, attributes.isDirectory());
}
catch (IOException e) {
FileUtil.delete(ioTarget);
throw e;
}
}
auxNotifyCompleted(handler -> handler.copy(file, newParent, copyName));
return new FakeVirtualFile(newParent, copyName);
}
@Override
public void setTimeStamp(@NotNull VirtualFile file, long timeStamp) {
File ioFile = convertToIOFile(file);
if (ioFile.exists() && !ioFile.setLastModified(timeStamp)) {
LOG.warn("Failed: " + file.getPath() + ", new:" + timeStamp + ", old:" + ioFile.lastModified());
}
}
@Override
public void setWritable(@NotNull VirtualFile file, boolean writableFlag) throws IOException {
String path = FileUtil.toSystemDependentName(file.getPath());
FileUtil.setReadOnlyAttribute(path, !writableFlag);
if (FileUtil.canWrite(path) != writableFlag) {
throw new IOException("Failed to change read-only flag for " + path);
}
}
private static final List<String> ourRootPaths;
static {
//noinspection SpellCheckingInspection
ourRootPaths = StringUtil.split(System.getProperty("idea.persistentfs.roots", ""), File.pathSeparator);
Collections.sort(ourRootPaths, (o1, o2) -> o2.length() - o1.length()); // longest first
}
@NotNull
@Override
protected String extractRootPath(@NotNull String path) {
if (path.isEmpty()) {
try {
path = new File("").getCanonicalPath();
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
for (String customRootPath : ourRootPaths) {
if (path.startsWith(customRootPath)) return customRootPath;
}
if (SystemInfo.isWindows) {
if (path.length() >= 2 && path.charAt(1) == ':') {
// Drive letter
return path.substring(0, 2).toUpperCase(Locale.US);
}
if (path.startsWith("//") || path.startsWith("\\\\")) {
// UNC. Must skip exactly two path elements like [\\ServerName\ShareName]\pathOnShare\file.txt
// Root path is in square brackets here.
int slashCount = 0;
int idx;
for (idx = 2; idx < path.length() && slashCount < 2; idx++) {
char c = path.charAt(idx);
if (c == '\\' || c == '/') {
slashCount++;
idx--;
}
}
return path.substring(0, idx);
}
return "";
}
return StringUtil.startsWithChar(path, '/') ? "/" : "";
}
@Override
public int getRank() {
return 1;
}
@Override
public boolean markNewFilesAsDirty() {
return true;
}
@NotNull
@Override
public String getCanonicallyCasedName(@NotNull VirtualFile file) {
if (isCaseSensitive()) {
return super.getCanonicallyCasedName(file);
}
String originalFileName = file.getName();
long t = LOG.isTraceEnabled() ? System.nanoTime() : 0;
try {
File ioFile = convertToIOFile(file);
File canonicalFile = ioFile.getCanonicalFile();
String canonicalFileName = canonicalFile.getName();
if (!SystemInfo.isUnix) {
return canonicalFileName;
}
// linux & mac support symbolic links
// unfortunately canonical file resolves sym links
// so its name may differ from name of origin file
//
// Here FS is case sensitive, so let's check that original and
// canonical file names are equal if we ignore name case
if (canonicalFileName.compareToIgnoreCase(originalFileName) == 0) {
// p.s. this should cover most cases related to not symbolic links
return canonicalFileName;
}
// Ok, names are not equal. Let's try to find corresponding file name
// among original file parent directory
File parentFile = ioFile.getParentFile();
if (parentFile != null) {
// I hope ls works fast on Unix
String[] canonicalFileNames = parentFile.list();
if (canonicalFileNames != null) {
for (String name : canonicalFileNames) {
// if names are equals
if (name.compareToIgnoreCase(originalFileName) == 0) {
return name;
}
}
}
}
// No luck. So ein mist!
// Ok, garbage in, garbage out. We may return original or canonical name
// no difference. Let's return canonical name just to preserve previous
// behaviour of this code.
return canonicalFileName;
}
catch (IOException e) {
return originalFileName;
}
finally {
if (t != 0) {
t = (System.nanoTime() - t) / 1000;
LOG.trace("getCanonicallyCasedName(" + file + "): " + t + " mks");
}
}
}
@Override
public FileAttributes getAttributes(@NotNull VirtualFile file) {
String path = normalize(file.getPath());
if (path == null) return null;
if (file.getParent() == null && path.startsWith("//")) {
return FAKE_ROOT_ATTRIBUTES; // fake Windows roots
}
return FileSystemUtil.getAttributes(FileUtil.toSystemDependentName(path));
}
@Override
public void refresh(boolean asynchronous) {
RefreshQueue.getInstance().refresh(asynchronous, true, null, ManagingFS.getInstance().getRoots(this));
}
@Override
public boolean hasChildren(@NotNull VirtualFile file) {
try {
return file.getParent() == null || hasChildren(Paths.get(file.getPath()));
}
catch (InvalidPathException e) {
return true;
}
}
/**
* @return {@code true} if {@code path} represents a directory with at least one child.
*/
public static boolean hasChildren(@NotNull Path path) {
// make sure to not load all children
try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
return stream.iterator().hasNext();
}
catch (IOException | SecurityException e) {
return true;
}
}
} | cleanup: inline one usage method (IDEA-CR-44754)
| platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/LocalFileSystemBase.java | cleanup: inline one usage method (IDEA-CR-44754) | |
Java | apache-2.0 | b017a236b99b25e74227801aabf25e8f2c5956cf | 0 | christophd/camel,tadayosi/camel,christophd/camel,adessaigne/camel,adessaigne/camel,cunningt/camel,cunningt/camel,cunningt/camel,cunningt/camel,christophd/camel,apache/camel,apache/camel,adessaigne/camel,apache/camel,tadayosi/camel,tadayosi/camel,adessaigne/camel,apache/camel,christophd/camel,adessaigne/camel,apache/camel,tadayosi/camel,apache/camel,christophd/camel,adessaigne/camel,cunningt/camel,cunningt/camel,christophd/camel,tadayosi/camel,tadayosi/camel | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.camel.reifier;
import org.apache.camel.AsyncCallback;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.Route;
import org.apache.camel.model.InterceptFromDefinition;
import org.apache.camel.model.ProcessorDefinition;
import org.apache.camel.support.processor.DelegateAsyncProcessor;
public class InterceptFromReifier extends InterceptReifier<InterceptFromDefinition> {
public InterceptFromReifier(Route route, ProcessorDefinition<?> definition) {
super(route, definition);
}
@Override
public Processor createProcessor() throws Exception {
final Processor child = this.createChildProcessor(true);
return new DelegateAsyncProcessor(child) {
@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
if (exchange.getFromEndpoint() != null) {
exchange.getMessage().setHeader(Exchange.INTERCEPTED_ENDPOINT, exchange.getFromEndpoint().getEndpointUri());
}
return super.process(exchange, callback);
}
};
}
}
| core/camel-core-reifier/src/main/java/org/apache/camel/reifier/InterceptFromReifier.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.camel.reifier;
import org.apache.camel.AsyncCallback;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.Route;
import org.apache.camel.model.InterceptFromDefinition;
import org.apache.camel.model.ProcessorDefinition;
import org.apache.camel.support.processor.DelegateAsyncProcessor;
public class InterceptFromReifier extends InterceptReifier<InterceptFromDefinition> {
public InterceptFromReifier(Route route, ProcessorDefinition<?> definition) {
super(route, definition);
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Processor createProcessor() throws Exception {
final Processor child = this.createChildProcessor(true);
return new DelegateAsyncProcessor(child) {
@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
if (exchange.getFromEndpoint() != null) {
exchange.getMessage().setHeader(Exchange.INTERCEPTED_ENDPOINT, exchange.getFromEndpoint().getEndpointUri());
}
return super.process(exchange, callback);
}
};
}
}
| Polished
| core/camel-core-reifier/src/main/java/org/apache/camel/reifier/InterceptFromReifier.java | Polished | |
Java | apache-2.0 | c7a4c80da513d5ff29b354ca202ebd87fe9c8b7d | 0 | thomasbecker/jetty-spdy,xmpace/jetty-read,thomasbecker/jetty-spdy,xmpace/jetty-read,xmpace/jetty-read,xmpace/jetty-read,thomasbecker/jetty-spdy | // ========================================================================
// Copyright (c) 2008-2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.security.authentication;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.HttpHeaders;
import org.eclipse.jetty.security.SecurityHandler;
import org.eclipse.jetty.security.ServerAuthException;
import org.eclipse.jetty.security.UserAuthentication;
import org.eclipse.jetty.server.Authentication;
import org.eclipse.jetty.server.Authentication.User;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.util.B64Code;
import org.eclipse.jetty.util.QuotedStringTokenizer;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.security.Constraint;
import org.eclipse.jetty.util.security.Credential;
/**
* @version $Rev: 4793 $ $Date: 2009-03-19 00:00:01 +0100 (Thu, 19 Mar 2009) $
*
* The nonce max age in ms can be set with the {@link SecurityHandler#setInitParameter(String, String)}
* using the name "maxNonceAge"
*/
public class DigestAuthenticator extends LoginAuthenticator
{
private static final Logger LOG = Log.getLogger(DigestAuthenticator.class);
SecureRandom _random = new SecureRandom();
private long _maxNonceAgeMs = 60*1000;
private ConcurrentMap<String, Nonce> _nonceCount = new ConcurrentHashMap<String, Nonce>();
private Queue<Nonce> _nonceQueue = new ConcurrentLinkedQueue<Nonce>();
private static class Nonce
{
final String _nonce;
final long _ts;
AtomicInteger _nc=new AtomicInteger();
public Nonce(String nonce, long ts)
{
_nonce=nonce;
_ts=ts;
}
}
/* ------------------------------------------------------------ */
public DigestAuthenticator()
{
super();
}
/* ------------------------------------------------------------ */
/**
* @see org.eclipse.jetty.security.authentication.LoginAuthenticator#setConfiguration(org.eclipse.jetty.security.Authenticator.AuthConfiguration)
*/
@Override
public void setConfiguration(AuthConfiguration configuration)
{
super.setConfiguration(configuration);
String mna=configuration.getInitParameter("maxNonceAge");
if (mna!=null)
{
synchronized (this)
{
_maxNonceAgeMs=Long.valueOf(mna);
}
}
}
/* ------------------------------------------------------------ */
public synchronized void setMaxNonceAge(long maxNonceAgeInMillis)
{
_maxNonceAgeMs = maxNonceAgeInMillis;
}
/* ------------------------------------------------------------ */
public String getAuthMethod()
{
return Constraint.__DIGEST_AUTH;
}
/* ------------------------------------------------------------ */
public boolean secureResponse(ServletRequest req, ServletResponse res, boolean mandatory, User validatedUser) throws ServerAuthException
{
return true;
}
/* ------------------------------------------------------------ */
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException
{
if (!mandatory)
return _deferred;
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
String credentials = request.getHeader(HttpHeaders.AUTHORIZATION);
try
{
boolean stale = false;
if (credentials != null)
{
if (LOG.isDebugEnabled())
LOG.debug("Credentials: " + credentials);
QuotedStringTokenizer tokenizer = new QuotedStringTokenizer(credentials, "=, ", true, false);
final Digest digest = new Digest(request.getMethod());
String last = null;
String name = null;
while (tokenizer.hasMoreTokens())
{
String tok = tokenizer.nextToken();
char c = (tok.length() == 1) ? tok.charAt(0) : '\0';
switch (c)
{
case '=':
name = last;
last = tok;
break;
case ',':
name = null;
break;
case ' ':
break;
default:
last = tok;
if (name != null)
{
if ("username".equalsIgnoreCase(name))
digest.username = tok;
else if ("realm".equalsIgnoreCase(name))
digest.realm = tok;
else if ("nonce".equalsIgnoreCase(name))
digest.nonce = tok;
else if ("nc".equalsIgnoreCase(name))
digest.nc = tok;
else if ("cnonce".equalsIgnoreCase(name))
digest.cnonce = tok;
else if ("qop".equalsIgnoreCase(name))
digest.qop = tok;
else if ("uri".equalsIgnoreCase(name))
digest.uri = tok;
else if ("response".equalsIgnoreCase(name))
digest.response = tok;
name=null;
}
}
}
int n = checkNonce(digest,(Request)request);
if (n > 0)
{
UserIdentity user = _loginService.login(digest.username,digest);
if (user!=null)
{
renewSessionOnAuthentication(request,response);
return new UserAuthentication(getAuthMethod(),user);
}
}
else if (n == 0)
stale = true;
}
if (!_deferred.isDeferred(response))
{
String domain = request.getContextPath();
if (domain == null)
domain = "/";
response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Digest realm=\"" + _loginService.getName()
+ "\", domain=\""
+ domain
+ "\", nonce=\""
+ newNonce((Request)request)
+ "\", algorithm=MD5, qop=\"auth\","
+ " stale=" + stale);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return Authentication.SEND_CONTINUE;
}
return Authentication.UNAUTHENTICATED;
}
catch (IOException e)
{
throw new ServerAuthException(e);
}
}
/* ------------------------------------------------------------ */
public String newNonce(Request request)
{
Nonce nonce;
do
{
byte[] nounce = new byte[24];
_random.nextBytes(nounce);
nonce = new Nonce(new String(B64Code.encode(nounce)),request.getTimeStamp());
}
while (_nonceCount.putIfAbsent(nonce._nonce,nonce)!=null);
_nonceQueue.add(nonce);
return nonce._nonce;
}
/**
* @param nstring nonce to check
* @param request
* @return -1 for a bad nonce, 0 for a stale none, 1 for a good nonce
*/
/* ------------------------------------------------------------ */
private int checkNonce(Digest digest, Request request)
{
// firstly let's expire old nonces
long expired;
synchronized (this)
{
expired = request.getTimeStamp()-_maxNonceAgeMs;
}
Nonce nonce=_nonceQueue.peek();
while (nonce!=null && nonce._ts<expired)
{
_nonceQueue.remove(nonce);
_nonceCount.remove(nonce._nonce);
nonce=_nonceQueue.peek();
}
try
{
nonce = _nonceCount.get(digest.nonce);
if (nonce==null)
return 0;
long count = Long.parseLong(digest.nc,16);
if (count>Integer.MAX_VALUE)
return 0;
int old=nonce._nc.get();
while (!nonce._nc.compareAndSet(old,(int)count))
old=nonce._nc.get();
if (count<=old)
return -1;
return 1;
}
catch (Exception e)
{
LOG.ignore(e);
}
return -1;
}
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
private static class Digest extends Credential
{
private static final long serialVersionUID = -2484639019549527724L;
final String method;
String username = "";
String realm = "";
String nonce = "";
String nc = "";
String cnonce = "";
String qop = "";
String uri = "";
String response = "";
/* ------------------------------------------------------------ */
Digest(String m)
{
method = m;
}
/* ------------------------------------------------------------ */
@Override
public boolean check(Object credentials)
{
if (credentials instanceof char[])
credentials=new String((char[])credentials);
String password = (credentials instanceof String) ? (String) credentials : credentials.toString();
try
{
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] ha1;
if (credentials instanceof Credential.MD5)
{
// Credentials are already a MD5 digest - assume it's in
// form user:realm:password (we have no way to know since
// it's a digest, alright?)
ha1 = ((Credential.MD5) credentials).getDigest();
}
else
{
// calc A1 digest
md.update(username.getBytes(StringUtil.__ISO_8859_1));
md.update((byte) ':');
md.update(realm.getBytes(StringUtil.__ISO_8859_1));
md.update((byte) ':');
md.update(password.getBytes(StringUtil.__ISO_8859_1));
ha1 = md.digest();
}
// calc A2 digest
md.reset();
md.update(method.getBytes(StringUtil.__ISO_8859_1));
md.update((byte) ':');
md.update(uri.getBytes(StringUtil.__ISO_8859_1));
byte[] ha2 = md.digest();
// calc digest
// request-digest = <"> < KD ( H(A1), unq(nonce-value) ":"
// nc-value ":" unq(cnonce-value) ":" unq(qop-value) ":" H(A2) )
// <">
// request-digest = <"> < KD ( H(A1), unq(nonce-value) ":" H(A2)
// ) > <">
md.update(TypeUtil.toString(ha1, 16).getBytes(StringUtil.__ISO_8859_1));
md.update((byte) ':');
md.update(nonce.getBytes(StringUtil.__ISO_8859_1));
md.update((byte) ':');
md.update(nc.getBytes(StringUtil.__ISO_8859_1));
md.update((byte) ':');
md.update(cnonce.getBytes(StringUtil.__ISO_8859_1));
md.update((byte) ':');
md.update(qop.getBytes(StringUtil.__ISO_8859_1));
md.update((byte) ':');
md.update(TypeUtil.toString(ha2, 16).getBytes(StringUtil.__ISO_8859_1));
byte[] digest = md.digest();
// check digest
return (TypeUtil.toString(digest, 16).equalsIgnoreCase(response));
}
catch (Exception e)
{
LOG.warn(e);
}
return false;
}
public String toString()
{
return username + "," + response;
}
}
}
| jetty-security/src/main/java/org/eclipse/jetty/security/authentication/DigestAuthenticator.java | // ========================================================================
// Copyright (c) 2008-2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.security.authentication;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.HttpHeaders;
import org.eclipse.jetty.security.SecurityHandler;
import org.eclipse.jetty.security.ServerAuthException;
import org.eclipse.jetty.security.UserAuthentication;
import org.eclipse.jetty.server.Authentication;
import org.eclipse.jetty.server.Authentication.User;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.util.B64Code;
import org.eclipse.jetty.util.QuotedStringTokenizer;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.security.Constraint;
import org.eclipse.jetty.util.security.Credential;
/**
* @version $Rev: 4793 $ $Date: 2009-03-19 00:00:01 +0100 (Thu, 19 Mar 2009) $
*
* The nonce max age in ms can be set with the {@link SecurityHandler#setInitParameter(String, String)}
* using the name "maxNonceAge"
*/
public class DigestAuthenticator extends LoginAuthenticator
{
private static final Logger LOG = Log.getLogger(DigestAuthenticator.class);
SecureRandom _random = new SecureRandom();
private long _maxNonceAgeMs = 60*1000;
private ConcurrentMap<String, Nonce> _nonceCount = new ConcurrentHashMap<String, Nonce>();
private Queue<Nonce> _nonceQueue = new ConcurrentLinkedQueue<Nonce>();
private static class Nonce
{
final String _nonce;
final long _ts;
AtomicInteger _nc=new AtomicInteger();
public Nonce(String nonce, long ts)
{
_nonce=nonce;
_ts=ts;
}
}
/* ------------------------------------------------------------ */
public DigestAuthenticator()
{
super();
}
/* ------------------------------------------------------------ */
/**
* @see org.eclipse.jetty.security.authentication.LoginAuthenticator#setConfiguration(org.eclipse.jetty.security.Authenticator.AuthConfiguration)
*/
@Override
public void setConfiguration(AuthConfiguration configuration)
{
super.setConfiguration(configuration);
String mna=configuration.getInitParameter("maxNonceAge");
if (mna!=null)
{
synchronized (this)
{
_maxNonceAgeMs=Long.valueOf(mna);
}
}
}
/* ------------------------------------------------------------ */
public synchronized void setMaxNonceAge(long maxNonceAgeInMillis)
{
_maxNonceAgeMs = maxNonceAgeInMillis;
}
/* ------------------------------------------------------------ */
public String getAuthMethod()
{
return Constraint.__DIGEST_AUTH;
}
/* ------------------------------------------------------------ */
public boolean secureResponse(ServletRequest req, ServletResponse res, boolean mandatory, User validatedUser) throws ServerAuthException
{
return true;
}
/* ------------------------------------------------------------ */
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException
{
if (!mandatory)
return _deferred;
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
String credentials = request.getHeader(HttpHeaders.AUTHORIZATION);
try
{
boolean stale = false;
if (credentials != null)
{
if (LOG.isDebugEnabled())
LOG.debug("Credentials: " + credentials);
QuotedStringTokenizer tokenizer = new QuotedStringTokenizer(credentials, "=, ", true, false);
final Digest digest = new Digest(request.getMethod());
String last = null;
String name = null;
while (tokenizer.hasMoreTokens())
{
String tok = tokenizer.nextToken();
char c = (tok.length() == 1) ? tok.charAt(0) : '\0';
switch (c)
{
case '=':
name = last;
last = tok;
break;
case ',':
name = null;
break;
case ' ':
break;
default:
last = tok;
if (name != null)
{
if ("username".equalsIgnoreCase(name))
digest.username = tok;
else if ("realm".equalsIgnoreCase(name))
digest.realm = tok;
else if ("nonce".equalsIgnoreCase(name))
digest.nonce = tok;
else if ("nc".equalsIgnoreCase(name))
digest.nc = tok;
else if ("cnonce".equalsIgnoreCase(name))
digest.cnonce = tok;
else if ("qop".equalsIgnoreCase(name))
digest.qop = tok;
else if ("uri".equalsIgnoreCase(name))
digest.uri = tok;
else if ("response".equalsIgnoreCase(name))
digest.response = tok;
name=null;
}
}
}
int n = checkNonce(digest,(Request)request);
if (n > 0)
{
UserIdentity user = _loginService.login(digest.username,digest);
if (user!=null)
{
renewSessionOnAuthentication(request,response);
return new UserAuthentication(getAuthMethod(),user);
}
}
else if (n == 0)
stale = true;
}
if (!_deferred.isDeferred(response))
{
String domain = request.getContextPath();
if (domain == null)
domain = "/";
response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Digest realm=\"" + _loginService.getName()
+ "\", domain=\""
+ domain
+ "\", nonce=\""
+ newNonce((Request)request)
+ "\", algorithm=MD5, qop=\"auth\","
+ " stale=" + stale);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return Authentication.SEND_CONTINUE;
}
return Authentication.UNAUTHENTICATED;
}
catch (IOException e)
{
throw new ServerAuthException(e);
}
}
/* ------------------------------------------------------------ */
public String newNonce(Request request)
{
Nonce nonce;
do
{
byte[] nounce = new byte[24];
_random.nextBytes(nounce);
nonce = new Nonce(new String(B64Code.encode(nounce)),request.getTimeStamp());
}
while (_nonceCount.putIfAbsent(nonce._nonce,nonce)!=null);
_nonceQueue.add(nonce);
return nonce._nonce;
}
/**
* @param nstring nonce to check
* @param request
* @return -1 for a bad nonce, 0 for a stale none, 1 for a good nonce
*/
/* ------------------------------------------------------------ */
private int checkNonce(Digest digest, Request request)
{
// firstly let's expire old nonces
long expired;
synchronized (this)
{
expired = request.getTimeStamp()-_maxNonceAgeMs;
}
Nonce nonce=_nonceQueue.peek();
while (nonce!=null && nonce._ts<expired)
{
_nonceQueue.remove();
_nonceCount.remove(nonce._nonce);
nonce=_nonceQueue.peek();
}
try
{
nonce = _nonceCount.get(digest.nonce);
if (nonce==null)
return 0;
long count = Long.parseLong(digest.nc,16);
if (count>Integer.MAX_VALUE)
return 0;
int old=nonce._nc.get();
while (!nonce._nc.compareAndSet(old,(int)count))
old=nonce._nc.get();
if (count<=old)
return -1;
return 1;
}
catch (Exception e)
{
LOG.ignore(e);
}
return -1;
}
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
private static class Digest extends Credential
{
private static final long serialVersionUID = -2484639019549527724L;
final String method;
String username = "";
String realm = "";
String nonce = "";
String nc = "";
String cnonce = "";
String qop = "";
String uri = "";
String response = "";
/* ------------------------------------------------------------ */
Digest(String m)
{
method = m;
}
/* ------------------------------------------------------------ */
@Override
public boolean check(Object credentials)
{
if (credentials instanceof char[])
credentials=new String((char[])credentials);
String password = (credentials instanceof String) ? (String) credentials : credentials.toString();
try
{
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] ha1;
if (credentials instanceof Credential.MD5)
{
// Credentials are already a MD5 digest - assume it's in
// form user:realm:password (we have no way to know since
// it's a digest, alright?)
ha1 = ((Credential.MD5) credentials).getDigest();
}
else
{
// calc A1 digest
md.update(username.getBytes(StringUtil.__ISO_8859_1));
md.update((byte) ':');
md.update(realm.getBytes(StringUtil.__ISO_8859_1));
md.update((byte) ':');
md.update(password.getBytes(StringUtil.__ISO_8859_1));
ha1 = md.digest();
}
// calc A2 digest
md.reset();
md.update(method.getBytes(StringUtil.__ISO_8859_1));
md.update((byte) ':');
md.update(uri.getBytes(StringUtil.__ISO_8859_1));
byte[] ha2 = md.digest();
// calc digest
// request-digest = <"> < KD ( H(A1), unq(nonce-value) ":"
// nc-value ":" unq(cnonce-value) ":" unq(qop-value) ":" H(A2) )
// <">
// request-digest = <"> < KD ( H(A1), unq(nonce-value) ":" H(A2)
// ) > <">
md.update(TypeUtil.toString(ha1, 16).getBytes(StringUtil.__ISO_8859_1));
md.update((byte) ':');
md.update(nonce.getBytes(StringUtil.__ISO_8859_1));
md.update((byte) ':');
md.update(nc.getBytes(StringUtil.__ISO_8859_1));
md.update((byte) ':');
md.update(cnonce.getBytes(StringUtil.__ISO_8859_1));
md.update((byte) ':');
md.update(qop.getBytes(StringUtil.__ISO_8859_1));
md.update((byte) ':');
md.update(TypeUtil.toString(ha2, 16).getBytes(StringUtil.__ISO_8859_1));
byte[] digest = md.digest();
// check digest
return (TypeUtil.toString(digest, 16).equalsIgnoreCase(response));
}
catch (Exception e)
{
LOG.warn(e);
}
return false;
}
public String toString()
{
return username + "," + response;
}
}
}
| [Bug 373421] address potential race condition related to the nonce queue
removing the same nonce twice | jetty-security/src/main/java/org/eclipse/jetty/security/authentication/DigestAuthenticator.java | [Bug 373421] address potential race condition related to the nonce queue removing the same nonce twice | |
Java | apache-2.0 | 32128a6ac2390250d9e0b933618177846fb7bef0 | 0 | DeezCashews/spring-boot,michael-simons/spring-boot,johnktims/spring-boot,fireshort/spring-boot,master-slave/spring-boot,jxblum/spring-boot,tbadie/spring-boot,paweldolecinski/spring-boot,lexandro/spring-boot,RainPlanter/spring-boot,ractive/spring-boot,pnambiarsf/spring-boot,hello2009chen/spring-boot,liupugong/spring-boot,kayelau/spring-boot,bijukunjummen/spring-boot,spring-projects/spring-boot,lif123/spring-boot,jbovet/spring-boot,qerub/spring-boot,AstaTus/spring-boot,yuxiaole/spring-boot,sbcoba/spring-boot,roymanish/spring-boot,paddymahoney/spring-boot,ptahchiev/spring-boot,mackeprm/spring-boot,jjankar/spring-boot,bjornlindstrom/spring-boot,mike-kukla/spring-boot,mouadtk/spring-boot,fogone/spring-boot,gauravbrills/spring-boot,tsachev/spring-boot,lexandro/spring-boot,duandf35/spring-boot,drunklite/spring-boot,kdvolder/spring-boot,Charkui/spring-boot,nandakishorm/spring-boot,mackeprm/spring-boot,jeremiahmarks/spring-boot,akmaharshi/jenkins,lokbun/spring-boot,jvz/spring-boot,yunbian/spring-boot,xc145214/spring-boot,fulvio-m/spring-boot,dreis2211/spring-boot,joshiste/spring-boot,ihoneymon/spring-boot,frost2014/spring-boot,satheeshmb/spring-boot,nelswadycki/spring-boot,michael-simons/spring-boot,npcode/spring-boot,eddumelendez/spring-boot,master-slave/spring-boot,drumonii/spring-boot,izeye/spring-boot,ameraljovic/spring-boot,herau/spring-boot,xiaoleiPENG/my-project,fireshort/spring-boot,jayeshmuralidharan/spring-boot,PraveenkumarShethe/spring-boot,axibase/spring-boot,drumonii/spring-boot,ralenmandao/spring-boot,xiaoleiPENG/my-project,jforge/spring-boot,allyjunio/spring-boot,fireshort/spring-boot,marcellodesales/spring-boot,lexandro/spring-boot,nebhale/spring-boot,jeremiahmarks/spring-boot,satheeshmb/spring-boot,olivergierke/spring-boot,axelfontaine/spring-boot,crackien/spring-boot,fulvio-m/spring-boot,buobao/spring-boot,ameraljovic/spring-boot,auvik/spring-boot,zhanhb/spring-boot,lokbun/spring-boot,pvorb/spring-boot,dreis2211/spring-boot,eonezhang/spring-boot,DeezCashews/spring-boot,rams2588/spring-boot,mbenson/spring-boot,kiranbpatil/spring-boot,liupugong/spring-boot,drunklite/spring-boot,ralenmandao/spring-boot,nebhale/spring-boot,dnsw83/spring-boot,AngusZhu/spring-boot,jvz/spring-boot,paddymahoney/spring-boot,shakuzen/spring-boot,yangdd1205/spring-boot,buobao/spring-boot,bjornlindstrom/spring-boot,thomasdarimont/spring-boot,5zzang/spring-boot,fogone/spring-boot,mevasaroj/jenkins2-course-spring-boot,srikalyan/spring-boot,lingounet/spring-boot,thomasdarimont/spring-boot,fjlopez/spring-boot,existmaster/spring-boot,axibase/spring-boot,Charkui/spring-boot,5zzang/spring-boot,ApiSecRay/spring-boot,satheeshmb/spring-boot,zhanhb/spring-boot,joshthornhill/spring-boot,durai145/spring-boot,Pokbab/spring-boot,nevenc-pivotal/spring-boot,ptahchiev/spring-boot,qerub/spring-boot,sungha/spring-boot,SPNilsen/spring-boot,mike-kukla/spring-boot,npcode/spring-boot,philwebb/spring-boot,dnsw83/spring-boot,nghialunhaiha/spring-boot,ilayaperumalg/spring-boot,AngusZhu/spring-boot,rajendra-chola/jenkins2-course-spring-boot,paweldolecinski/spring-boot,RichardCSantana/spring-boot,meftaul/spring-boot,linead/spring-boot,nebhale/spring-boot,nelswadycki/spring-boot,mbenson/spring-boot,jjankar/spring-boot,dreis2211/spring-boot,deki/spring-boot,kdvolder/spring-boot,forestqqqq/spring-boot,minmay/spring-boot,nebhale/spring-boot,balajinsr/spring-boot,npcode/spring-boot,jbovet/spring-boot,nisuhw/spring-boot,eliudiaz/spring-boot,kayelau/spring-boot,JiweiWong/spring-boot,designreuse/spring-boot,nelswadycki/spring-boot,ptahchiev/spring-boot,philwebb/spring-boot,joansmith/spring-boot,master-slave/spring-boot,tiarebalbi/spring-boot,chrylis/spring-boot,ptahchiev/spring-boot,balajinsr/spring-boot,existmaster/spring-boot,felipeg48/spring-boot,roymanish/spring-boot,cleverjava/jenkins2-course-spring-boot,ihoneymon/spring-boot,Charkui/spring-boot,johnktims/spring-boot,rajendra-chola/jenkins2-course-spring-boot,raiamber1/spring-boot,RichardCSantana/spring-boot,deki/spring-boot,existmaster/spring-boot,forestqqqq/spring-boot,MasterRoots/spring-boot,rams2588/spring-boot,DONIKAN/spring-boot,philwebb/spring-boot-concourse,trecloux/spring-boot,habuma/spring-boot,vaseemahmed01/spring-boot,wilkinsona/spring-boot,smilence1986/spring-boot,jforge/spring-boot,bjornlindstrom/spring-boot,eric-stanley/spring-boot,playleud/spring-boot,nevenc-pivotal/spring-boot,Pokbab/spring-boot,mdeinum/spring-boot,brettwooldridge/spring-boot,spring-projects/spring-boot,imranansari/spring-boot,frost2014/spring-boot,jcastaldoFoodEssentials/spring-boot,afroje-reshma/spring-boot-sample,paddymahoney/spring-boot,javyzheng/spring-boot,balajinsr/spring-boot,sbcoba/spring-boot,mbogoevici/spring-boot,rizwan18/spring-boot,rickeysu/spring-boot,jmnarloch/spring-boot,master-slave/spring-boot,nurkiewicz/spring-boot,mbogoevici/spring-boot,huangyugui/spring-boot,SPNilsen/spring-boot,rajendra-chola/jenkins2-course-spring-boot,allyjunio/spring-boot,AstaTus/spring-boot,herau/spring-boot,frost2014/spring-boot,patrikbeno/spring-boot,mouadtk/spring-boot,yhj630520/spring-boot,kdvolder/spring-boot,na-na/spring-boot,meloncocoo/spring-boot,royclarkson/spring-boot,philwebb/spring-boot,peteyan/spring-boot,jayarampradhan/spring-boot,minmay/spring-boot,ameraljovic/spring-boot,tbbost/spring-boot,raiamber1/spring-boot,lcardito/spring-boot,lingounet/spring-boot,kiranbpatil/spring-boot,xingguang2013/spring-boot,na-na/spring-boot,sebastiankirsch/spring-boot,Charkui/spring-boot,xwjxwj30abc/spring-boot,frost2014/spring-boot,bbrouwer/spring-boot,joshthornhill/spring-boot,ractive/spring-boot,jrrickard/spring-boot,mike-kukla/spring-boot,5zzang/spring-boot,bijukunjummen/spring-boot,lexandro/spring-boot,hqrt/jenkins2-course-spring-boot,mevasaroj/jenkins2-course-spring-boot,yuxiaole/spring-boot,joshiste/spring-boot,clarklj001/spring-boot,minmay/spring-boot,paweldolecinski/spring-boot,AstaTus/spring-boot,lcardito/spring-boot,joansmith/spring-boot,sungha/spring-boot,jbovet/spring-boot,vakninr/spring-boot,vakninr/spring-boot,eonezhang/spring-boot,linead/spring-boot,mabernardo/spring-boot,liupugong/spring-boot,meftaul/spring-boot,designreuse/spring-boot,prasenjit-net/spring-boot,rickeysu/spring-boot,wilkinsona/spring-boot,tsachev/spring-boot,dreis2211/spring-boot,nisuhw/spring-boot,yhj630520/spring-boot,cmsandiga/spring-boot,crackien/spring-boot,brettwooldridge/spring-boot,akmaharshi/jenkins,chrylis/spring-boot,roberthafner/spring-boot,lokbun/spring-boot,nebhale/spring-boot,lokbun/spring-boot,bijukunjummen/spring-boot,meftaul/spring-boot,nisuhw/spring-boot,wwadge/spring-boot,nandakishorm/spring-boot,panbiping/spring-boot,dfa1/spring-boot,mbenson/spring-boot,rizwan18/spring-boot,rams2588/spring-boot,qq83387856/spring-boot,lokbun/spring-boot,sungha/spring-boot,kamilszymanski/spring-boot,eliudiaz/spring-boot,SaravananParthasarathy/SPSDemo,isopov/spring-boot,fulvio-m/spring-boot,cmsandiga/spring-boot,bijukunjummen/spring-boot,DONIKAN/spring-boot,joshiste/spring-boot,christian-posta/spring-boot,ApiSecRay/spring-boot,orangesdk/spring-boot,fjlopez/spring-boot,patrikbeno/spring-boot,lburgazzoli/spring-boot,rams2588/spring-boot,cleverjava/jenkins2-course-spring-boot,xingguang2013/spring-boot,trecloux/spring-boot,philwebb/spring-boot,lucassaldanha/spring-boot,lingounet/spring-boot,gauravbrills/spring-boot,clarklj001/spring-boot,meloncocoo/spring-boot,smayoorans/spring-boot,jrrickard/spring-boot,krmcbride/spring-boot,herau/spring-boot,fjlopez/spring-boot,akmaharshi/jenkins,sbuettner/spring-boot,rweisleder/spring-boot,navarrogabriela/spring-boot,rickeysu/spring-boot,philwebb/spring-boot-concourse,olivergierke/spring-boot,herau/spring-boot,kamilszymanski/spring-boot,rams2588/spring-boot,spring-projects/spring-boot,eonezhang/spring-boot,ollie314/spring-boot,master-slave/spring-boot,htynkn/spring-boot,wilkinsona/spring-boot,zhangshuangquan/spring-root,Pokbab/spring-boot,jayarampradhan/spring-boot,jxblum/spring-boot,lif123/spring-boot,drunklite/spring-boot,ApiSecRay/spring-boot,eddumelendez/spring-boot,bclozel/spring-boot,nghiavo/spring-boot,drumonii/spring-boot,jayarampradhan/spring-boot,yunbian/spring-boot,sbuettner/spring-boot,nelswadycki/spring-boot,SaravananParthasarathy/SPSDemo,isopov/spring-boot,imranansari/spring-boot,eliudiaz/spring-boot,jayarampradhan/spring-boot,cleverjava/jenkins2-course-spring-boot,playleud/spring-boot,habuma/spring-boot,xiaoleiPENG/my-project,eonezhang/spring-boot,prasenjit-net/spring-boot,jxblum/spring-boot,auvik/spring-boot,sbcoba/spring-boot,drumonii/spring-boot,jcastaldoFoodEssentials/spring-boot,na-na/spring-boot,rmoorman/spring-boot,jmnarloch/spring-boot,RishikeshDarandale/spring-boot,vpavic/spring-boot,javyzheng/spring-boot,michael-simons/spring-boot,vakninr/spring-boot,jayeshmuralidharan/spring-boot,hklv/spring-boot,axibase/spring-boot,forestqqqq/spring-boot,yuxiaole/spring-boot,raiamber1/spring-boot,jbovet/spring-boot,smayoorans/spring-boot,orangesdk/spring-boot,JiweiWong/spring-boot,philwebb/spring-boot-concourse,auvik/spring-boot,roymanish/spring-boot,joshthornhill/spring-boot,mbenson/spring-boot,existmaster/spring-boot,NetoDevel/spring-boot,akmaharshi/jenkins,rweisleder/spring-boot,lenicliu/spring-boot,sbuettner/spring-boot,allyjunio/spring-boot,olivergierke/spring-boot,xingguang2013/spring-boot,npcode/spring-boot,meloncocoo/spring-boot,qerub/spring-boot,afroje-reshma/spring-boot-sample,marcellodesales/spring-boot,Nowheresly/spring-boot,AstaTus/spring-boot,durai145/spring-boot,minmay/spring-boot,durai145/spring-boot,hello2009chen/spring-boot,lif123/spring-boot,rweisleder/spring-boot,buobao/spring-boot,ChunPIG/spring-boot,pvorb/spring-boot,patrikbeno/spring-boot,xdweleven/spring-boot,buobao/spring-boot,afroje-reshma/spring-boot-sample,nurkiewicz/spring-boot,dfa1/spring-boot,Chomeh/spring-boot,fjlopez/spring-boot,PraveenkumarShethe/spring-boot,kayelau/spring-boot,mbogoevici/spring-boot,neo4j-contrib/spring-boot,ameraljovic/spring-boot,imranansari/spring-boot,nisuhw/spring-boot,i007422/jenkins2-course-spring-boot,Nowheresly/spring-boot,zorosteven/spring-boot,bjornlindstrom/spring-boot,donhuvy/spring-boot,izeye/spring-boot,bclozel/spring-boot,Makhlab/spring-boot,mlc0202/spring-boot,fulvio-m/spring-boot,philwebb/spring-boot,mebinjacob/spring-boot,javyzheng/spring-boot,ChunPIG/spring-boot,kiranbpatil/spring-boot,eddumelendez/spring-boot,royclarkson/spring-boot,hello2009chen/spring-boot,roberthafner/spring-boot,aahlenst/spring-boot,mackeprm/spring-boot,allyjunio/spring-boot,mevasaroj/jenkins2-course-spring-boot,Chomeh/spring-boot,NetoDevel/spring-boot,cbtpro/spring-boot,MasterRoots/spring-boot,zorosteven/spring-boot,lburgazzoli/spring-boot,yuxiaole/spring-boot,mebinjacob/spring-boot,lcardito/spring-boot,michael-simons/spring-boot,ihoneymon/spring-boot,jcastaldoFoodEssentials/spring-boot,smayoorans/spring-boot,ollie314/spring-boot,ApiSecRay/spring-boot,nurkiewicz/spring-boot,designreuse/spring-boot,mlc0202/spring-boot,designreuse/spring-boot,huangyugui/spring-boot,murilobr/spring-boot,hklv/spring-boot,cbtpro/spring-boot,navarrogabriela/spring-boot,axibase/spring-boot,crackien/spring-boot,nghiavo/spring-boot,navarrogabriela/spring-boot,xdweleven/spring-boot,aahlenst/spring-boot,DONIKAN/spring-boot,krmcbride/spring-boot,marcellodesales/spring-boot,meloncocoo/spring-boot,eric-stanley/spring-boot,auvik/spring-boot,RainPlanter/spring-boot,herau/spring-boot,donhuvy/spring-boot,MrMitchellMoore/spring-boot,keithsjohnson/spring-boot,qq83387856/spring-boot,prakashme/spring-boot,cleverjava/jenkins2-course-spring-boot,mlc0202/spring-boot,philwebb/spring-boot,wilkinsona/spring-boot,ojacquemart/spring-boot,fogone/spring-boot,axelfontaine/spring-boot,jack-luj/spring-boot,mosoft521/spring-boot,qq83387856/spring-boot,sebastiankirsch/spring-boot,prakashme/spring-boot,clarklj001/spring-boot,scottfrederick/spring-boot,mdeinum/spring-boot,wwadge/spring-boot,brettwooldridge/spring-boot,sbuettner/spring-boot,wilkinsona/spring-boot,johnktims/spring-boot,lexandro/spring-boot,Chomeh/spring-boot,kdvolder/spring-boot,Makhlab/spring-boot,okba1/spring-boot,shangyi0102/spring-boot,tbadie/spring-boot,fulvio-m/spring-boot,aahlenst/spring-boot,balajinsr/spring-boot,nghiavo/spring-boot,SaravananParthasarathy/SPSDemo,jayeshmuralidharan/spring-boot,kamilszymanski/spring-boot,axelfontaine/spring-boot,jvz/spring-boot,lenicliu/spring-boot,isopov/spring-boot,habuma/spring-boot,vakninr/spring-boot,JiweiWong/spring-boot,christian-posta/spring-boot,shangyi0102/spring-boot,eddumelendez/spring-boot,brettwooldridge/spring-boot,mackeprm/spring-boot,donhuvy/spring-boot,lucassaldanha/spring-boot,mosoft521/spring-boot,jforge/spring-boot,dfa1/spring-boot,yunbian/spring-boot,spring-projects/spring-boot,vpavic/spring-boot,ApiSecRay/spring-boot,rizwan18/spring-boot,jjankar/spring-boot,MrMitchellMoore/spring-boot,roberthafner/spring-boot,rmoorman/spring-boot,RishikeshDarandale/spring-boot,jjankar/spring-boot,ractive/spring-boot,shangyi0102/spring-boot,deki/spring-boot,tbbost/spring-boot,candrews/spring-boot,trecloux/spring-boot,mabernardo/spring-boot,shakuzen/spring-boot,izeye/spring-boot,ollie314/spring-boot,Makhlab/spring-boot,nandakishorm/spring-boot,DONIKAN/spring-boot,mbenson/spring-boot,eddumelendez/spring-boot,mdeinum/spring-boot,forestqqqq/spring-boot,scottfrederick/spring-boot,mebinjacob/spring-boot,eliudiaz/spring-boot,lenicliu/spring-boot,htynkn/spring-boot,rickeysu/spring-boot,imranansari/spring-boot,kdvolder/spring-boot,kdvolder/spring-boot,neo4j-contrib/spring-boot,jrrickard/spring-boot,habuma/spring-boot,NetoDevel/spring-boot,xc145214/spring-boot,prakashme/spring-boot,nghialunhaiha/spring-boot,panbiping/spring-boot,ilayaperumalg/spring-boot,felipeg48/spring-boot,prasenjit-net/spring-boot,fireshort/spring-boot,mabernardo/spring-boot,DeezCashews/spring-boot,ojacquemart/spring-boot,Makhlab/spring-boot,crackien/spring-boot,ilayaperumalg/spring-boot,bclozel/spring-boot,isopov/spring-boot,axelfontaine/spring-boot,srikalyan/spring-boot,thomasdarimont/spring-boot,jrrickard/spring-boot,auvik/spring-boot,royclarkson/spring-boot,jcastaldoFoodEssentials/spring-boot,afroje-reshma/spring-boot-sample,ralenmandao/spring-boot,lenicliu/spring-boot,nurkiewicz/spring-boot,playleud/spring-boot,scottfrederick/spring-boot,M3lkior/spring-boot,rweisleder/spring-boot,keithsjohnson/spring-boot,johnktims/spring-boot,xingguang2013/spring-boot,roberthafner/spring-boot,kiranbpatil/spring-boot,paweldolecinski/spring-boot,eddumelendez/spring-boot,jcastaldoFoodEssentials/spring-boot,shakuzen/spring-boot,MasterRoots/spring-boot,allyjunio/spring-boot,lburgazzoli/spring-boot,Nowheresly/spring-boot,smilence1986/spring-boot,rickeysu/spring-boot,christian-posta/spring-boot,i007422/jenkins2-course-spring-boot,dnsw83/spring-boot,rajendra-chola/jenkins2-course-spring-boot,trecloux/spring-boot,mrumpf/spring-boot,MrMitchellMoore/spring-boot,existmaster/spring-boot,nghialunhaiha/spring-boot,jforge/spring-boot,npcode/spring-boot,MrMitchellMoore/spring-boot,zhangshuangquan/spring-root,joansmith/spring-boot,peteyan/spring-boot,fogone/spring-boot,eliudiaz/spring-boot,raiamber1/spring-boot,afroje-reshma/spring-boot-sample,Chomeh/spring-boot,dnsw83/spring-boot,lburgazzoli/spring-boot,zhanhb/spring-boot,okba1/spring-boot,rmoorman/spring-boot,Buzzardo/spring-boot,shakuzen/spring-boot,mouadtk/spring-boot,johnktims/spring-boot,PraveenkumarShethe/spring-boot,5zzang/spring-boot,nisuhw/spring-boot,AstaTus/spring-boot,kayelau/spring-boot,wilkinsona/spring-boot,christian-posta/spring-boot,i007422/jenkins2-course-spring-boot,chrylis/spring-boot,dfa1/spring-boot,mrumpf/spring-boot,smayoorans/spring-boot,hklv/spring-boot,smilence1986/spring-boot,srikalyan/spring-boot,kamilszymanski/spring-boot,keithsjohnson/spring-boot,zhangshuangquan/spring-root,hello2009chen/spring-boot,hqrt/jenkins2-course-spring-boot,drumonii/spring-boot,jayeshmuralidharan/spring-boot,zorosteven/spring-boot,felipeg48/spring-boot,cmsandiga/spring-boot,xingguang2013/spring-boot,dreis2211/spring-boot,paddymahoney/spring-boot,imranansari/spring-boot,neo4j-contrib/spring-boot,duandf35/spring-boot,qq83387856/spring-boot,cmsandiga/spring-boot,nelswadycki/spring-boot,ameraljovic/spring-boot,M3lkior/spring-boot,xc145214/spring-boot,ilayaperumalg/spring-boot,javyzheng/spring-boot,yunbian/spring-boot,neo4j-contrib/spring-boot,Nowheresly/spring-boot,mouadtk/spring-boot,tbadie/spring-boot,Pokbab/spring-boot,nghialunhaiha/spring-boot,bclozel/spring-boot,tiarebalbi/spring-boot,joshiste/spring-boot,peteyan/spring-boot,roymanish/spring-boot,mosoft521/spring-boot,RobertNickens/spring-boot,panbiping/spring-boot,aahlenst/spring-boot,joshthornhill/spring-boot,mlc0202/spring-boot,DeezCashews/spring-boot,mike-kukla/spring-boot,michael-simons/spring-boot,mebinjacob/spring-boot,lif123/spring-boot,Charkui/spring-boot,kayelau/spring-boot,SaravananParthasarathy/SPSDemo,nghiavo/spring-boot,jmnarloch/spring-boot,gauravbrills/spring-boot,vpavic/spring-boot,dfa1/spring-boot,RobertNickens/spring-boot,joansmith/spring-boot,zhanhb/spring-boot,liupugong/spring-boot,javyzheng/spring-boot,lingounet/spring-boot,cbtpro/spring-boot,jmnarloch/spring-boot,jbovet/spring-boot,royclarkson/spring-boot,bijukunjummen/spring-boot,paddymahoney/spring-boot,rizwan18/spring-boot,vaseemahmed01/spring-boot,RobertNickens/spring-boot,huangyugui/spring-boot,nghialunhaiha/spring-boot,SPNilsen/spring-boot,meftaul/spring-boot,eonezhang/spring-boot,royclarkson/spring-boot,tiarebalbi/spring-boot,marcellodesales/spring-boot,candrews/spring-boot,zorosteven/spring-boot,chrylis/spring-boot,pnambiarsf/spring-boot,DONIKAN/spring-boot,deki/spring-boot,lucassaldanha/spring-boot,thomasdarimont/spring-boot,na-na/spring-boot,RichardCSantana/spring-boot,tsachev/spring-boot,htynkn/spring-boot,mdeinum/spring-boot,hello2009chen/spring-boot,zhanhb/spring-boot,yangdd1205/spring-boot,xc145214/spring-boot,yhj630520/spring-boot,jmnarloch/spring-boot,xdweleven/spring-boot,jeremiahmarks/spring-boot,nandakishorm/spring-boot,RobertNickens/spring-boot,ojacquemart/spring-boot,felipeg48/spring-boot,jack-luj/spring-boot,xwjxwj30abc/spring-boot,mlc0202/spring-boot,thomasdarimont/spring-boot,navarrogabriela/spring-boot,gauravbrills/spring-boot,Buzzardo/spring-boot,okba1/spring-boot,yangdd1205/spring-boot,ilayaperumalg/spring-boot,meftaul/spring-boot,shangyi0102/spring-boot,frost2014/spring-boot,clarklj001/spring-boot,mosoft521/spring-boot,tbbost/spring-boot,bbrouwer/spring-boot,aahlenst/spring-boot,pvorb/spring-boot,ollie314/spring-boot,sungha/spring-boot,duandf35/spring-boot,tsachev/spring-boot,wwadge/spring-boot,jxblum/spring-boot,Buzzardo/spring-boot,jxblum/spring-boot,prakashme/spring-boot,ChunPIG/spring-boot,smilence1986/spring-boot,fireshort/spring-boot,xwjxwj30abc/spring-boot,vpavic/spring-boot,hqrt/jenkins2-course-spring-boot,RainPlanter/spring-boot,joshiste/spring-boot,linead/spring-boot,crackien/spring-boot,ChunPIG/spring-boot,jack-luj/spring-boot,fogone/spring-boot,ihoneymon/spring-boot,vpavic/spring-boot,roberthafner/spring-boot,jack-luj/spring-boot,cleverjava/jenkins2-course-spring-boot,keithsjohnson/spring-boot,nevenc-pivotal/spring-boot,zhangshuangquan/spring-root,mbenson/spring-boot,habuma/spring-boot,sbuettner/spring-boot,forestqqqq/spring-boot,krmcbride/spring-boot,vakninr/spring-boot,linead/spring-boot,murilobr/spring-boot,neo4j-contrib/spring-boot,drumonii/spring-boot,dnsw83/spring-boot,smayoorans/spring-boot,tiarebalbi/spring-boot,izeye/spring-boot,okba1/spring-boot,rweisleder/spring-boot,tsachev/spring-boot,tbbost/spring-boot,sungha/spring-boot,htynkn/spring-boot,SPNilsen/spring-boot,nevenc-pivotal/spring-boot,ralenmandao/spring-boot,nevenc-pivotal/spring-boot,huangyugui/spring-boot,scottfrederick/spring-boot,kiranbpatil/spring-boot,xdweleven/spring-boot,cbtpro/spring-boot,scottfrederick/spring-boot,RainPlanter/spring-boot,scottfrederick/spring-boot,zhangshuangquan/spring-root,liupugong/spring-boot,roymanish/spring-boot,jayeshmuralidharan/spring-boot,lingounet/spring-boot,mrumpf/spring-boot,eric-stanley/spring-boot,i007422/jenkins2-course-spring-boot,Makhlab/spring-boot,RishikeshDarandale/spring-boot,bclozel/spring-boot,tbbost/spring-boot,mbogoevici/spring-boot,yhj630520/spring-boot,RishikeshDarandale/spring-boot,JiweiWong/spring-boot,felipeg48/spring-boot,RishikeshDarandale/spring-boot,mabernardo/spring-boot,isopov/spring-boot,lif123/spring-boot,5zzang/spring-boot,shangyi0102/spring-boot,mosoft521/spring-boot,izeye/spring-boot,donhuvy/spring-boot,aahlenst/spring-boot,cmsandiga/spring-boot,tiarebalbi/spring-boot,spring-projects/spring-boot,wwadge/spring-boot,vaseemahmed01/spring-boot,shakuzen/spring-boot,ihoneymon/spring-boot,srikalyan/spring-boot,tbadie/spring-boot,okba1/spring-boot,htynkn/spring-boot,NetoDevel/spring-boot,ihoneymon/spring-boot,mike-kukla/spring-boot,candrews/spring-boot,na-na/spring-boot,lucassaldanha/spring-boot,pvorb/spring-boot,felipeg48/spring-boot,kamilszymanski/spring-boot,rmoorman/spring-boot,cbtpro/spring-boot,MasterRoots/spring-boot,xwjxwj30abc/spring-boot,olivergierke/spring-boot,yhj630520/spring-boot,pvorb/spring-boot,tiarebalbi/spring-boot,SaravananParthasarathy/SPSDemo,yunbian/spring-boot,axelfontaine/spring-boot,gauravbrills/spring-boot,playleud/spring-boot,huangyugui/spring-boot,orangesdk/spring-boot,nurkiewicz/spring-boot,nandakishorm/spring-boot,philwebb/spring-boot-concourse,mabernardo/spring-boot,mdeinum/spring-boot,JiweiWong/spring-boot,RainPlanter/spring-boot,spring-projects/spring-boot,patrikbeno/spring-boot,drunklite/spring-boot,murilobr/spring-boot,eric-stanley/spring-boot,M3lkior/spring-boot,linead/spring-boot,xwjxwj30abc/spring-boot,ptahchiev/spring-boot,murilobr/spring-boot,jvz/spring-boot,rweisleder/spring-boot,hklv/spring-boot,dreis2211/spring-boot,satheeshmb/spring-boot,RichardCSantana/spring-boot,qerub/spring-boot,mackeprm/spring-boot,jforge/spring-boot,prasenjit-net/spring-boot,minmay/spring-boot,trecloux/spring-boot,bjornlindstrom/spring-boot,michael-simons/spring-boot,Pokbab/spring-boot,jxblum/spring-boot,ChunPIG/spring-boot,ollie314/spring-boot,duandf35/spring-boot,buobao/spring-boot,vpavic/spring-boot,sbcoba/spring-boot,Nowheresly/spring-boot,bbrouwer/spring-boot,akmaharshi/jenkins,isopov/spring-boot,brettwooldridge/spring-boot,bbrouwer/spring-boot,prasenjit-net/spring-boot,raiamber1/spring-boot,hqrt/jenkins2-course-spring-boot,mrumpf/spring-boot,chrylis/spring-boot,ractive/spring-boot,designreuse/spring-boot,ptahchiev/spring-boot,mevasaroj/jenkins2-course-spring-boot,RichardCSantana/spring-boot,paweldolecinski/spring-boot,prakashme/spring-boot,Buzzardo/spring-boot,meloncocoo/spring-boot,NetoDevel/spring-boot,lcardito/spring-boot,sebastiankirsch/spring-boot,eric-stanley/spring-boot,lucassaldanha/spring-boot,tsachev/spring-boot,duandf35/spring-boot,navarrogabriela/spring-boot,jrrickard/spring-boot,SPNilsen/spring-boot,mrumpf/spring-boot,shakuzen/spring-boot,htynkn/spring-boot,MrMitchellMoore/spring-boot,mevasaroj/jenkins2-course-spring-boot,pnambiarsf/spring-boot,jeremiahmarks/spring-boot,Buzzardo/spring-boot,xiaoleiPENG/my-project,M3lkior/spring-boot,joansmith/spring-boot,orangesdk/spring-boot,bclozel/spring-boot,srikalyan/spring-boot,AngusZhu/spring-boot,satheeshmb/spring-boot,PraveenkumarShethe/spring-boot,joshthornhill/spring-boot,balajinsr/spring-boot,fjlopez/spring-boot,vaseemahmed01/spring-boot,orangesdk/spring-boot,xiaoleiPENG/my-project,panbiping/spring-boot,AngusZhu/spring-boot,drunklite/spring-boot,joshiste/spring-boot,tbadie/spring-boot,ilayaperumalg/spring-boot,DeezCashews/spring-boot,pnambiarsf/spring-boot,philwebb/spring-boot-concourse,mouadtk/spring-boot,panbiping/spring-boot,keithsjohnson/spring-boot,sebastiankirsch/spring-boot,habuma/spring-boot,RobertNickens/spring-boot,mbogoevici/spring-boot,ojacquemart/spring-boot,xdweleven/spring-boot,candrews/spring-boot,hqrt/jenkins2-course-spring-boot,playleud/spring-boot,deki/spring-boot,jayarampradhan/spring-boot,hklv/spring-boot,Chomeh/spring-boot,donhuvy/spring-boot,mebinjacob/spring-boot,murilobr/spring-boot,sbcoba/spring-boot,chrylis/spring-boot,nghiavo/spring-boot,peteyan/spring-boot,christian-posta/spring-boot,sebastiankirsch/spring-boot,rizwan18/spring-boot,krmcbride/spring-boot,xc145214/spring-boot,MasterRoots/spring-boot,qq83387856/spring-boot,AngusZhu/spring-boot,vaseemahmed01/spring-boot,ralenmandao/spring-boot,durai145/spring-boot,jeremiahmarks/spring-boot,peteyan/spring-boot,rmoorman/spring-boot,wwadge/spring-boot,lburgazzoli/spring-boot,jjankar/spring-boot,olivergierke/spring-boot,clarklj001/spring-boot,jvz/spring-boot,patrikbeno/spring-boot,Buzzardo/spring-boot,durai145/spring-boot,marcellodesales/spring-boot,smilence1986/spring-boot,zhanhb/spring-boot,yuxiaole/spring-boot,candrews/spring-boot,rajendra-chola/jenkins2-course-spring-boot,bbrouwer/spring-boot,i007422/jenkins2-course-spring-boot,lenicliu/spring-boot,M3lkior/spring-boot,lcardito/spring-boot,ojacquemart/spring-boot,mdeinum/spring-boot,donhuvy/spring-boot,qerub/spring-boot,PraveenkumarShethe/spring-boot,zorosteven/spring-boot,pnambiarsf/spring-boot,jack-luj/spring-boot,axibase/spring-boot,krmcbride/spring-boot,ractive/spring-boot | /*
* Copyright 2012-2015 the original author or authors.
*
* 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 org.springframework.boot.autoconfigure.jackson;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat;
import com.fasterxml.jackson.datatype.joda.ser.DateTimeSerializer;
/**
* Auto configuration for Jackson. The following auto-configuration will get applied:
* <ul>
* <li>an {@link ObjectMapper} in case none is already configured.</li>
* <li>a {@link Jackson2ObjectMapperBuilder} in case none is already configured.</li>
* <li>auto-registration for all {@link Module} beans with all {@link ObjectMapper} beans
* (including the defaulted ones).</li>
* </ul>
*
* @author Oliver Gierke
* @author Andy Wilkinson
* @author Marcel Overdijk
* @author Sebastien Deleuze
* @author Johannes Stelzer
* @since 1.1.0
*/
@Configuration
@ConditionalOnClass(ObjectMapper.class)
public class JacksonAutoConfiguration {
@Configuration
@ConditionalOnClass({ ObjectMapper.class, Jackson2ObjectMapperBuilder.class })
static class JacksonObjectMapperConfiguration {
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
return builder.createXmlMapper(false).build();
}
}
@Configuration
@ConditionalOnClass({ Jackson2ObjectMapperBuilder.class, DateTime.class,
DateTimeSerializer.class, JacksonJodaDateFormat.class })
static class JodaDateTimeJacksonConfiguration {
private final Log log = LogFactory.getLog(JodaDateTimeJacksonConfiguration.class);
@Autowired
private JacksonProperties jacksonProperties;
@Bean
public SimpleModule jodaDateTimeSerializationModule() {
SimpleModule module = new SimpleModule();
JacksonJodaDateFormat jacksonJodaFormat = getJacksonJodaDateFormat();
if (jacksonJodaFormat != null) {
module.addSerializer(DateTime.class, new DateTimeSerializer(
jacksonJodaFormat));
}
return module;
}
private JacksonJodaDateFormat getJacksonJodaDateFormat() {
if (this.jacksonProperties.getJodaDateTimeFormat() != null) {
return new JacksonJodaDateFormat(DateTimeFormat.forPattern(
this.jacksonProperties.getJodaDateTimeFormat()).withZoneUTC());
}
if (this.jacksonProperties.getDateFormat() != null) {
try {
return new JacksonJodaDateFormat(DateTimeFormat.forPattern(
this.jacksonProperties.getDateFormat()).withZoneUTC());
}
catch (IllegalArgumentException ex) {
if (this.log.isWarnEnabled()) {
this.log.warn("spring.jackson.date-format could not be used to "
+ "configure formatting of Joda's DateTime. You may want "
+ "to configure spring.jackson.joda-date-time-format as "
+ "well.");
}
}
}
return null;
}
}
@Configuration
@ConditionalOnClass({ ObjectMapper.class, Jackson2ObjectMapperBuilder.class })
@EnableConfigurationProperties(JacksonProperties.class)
static class JacksonObjectMapperBuilderConfiguration {
@Autowired
private ApplicationContext applicationContext;
@Autowired
private JacksonProperties jacksonProperties;
@Bean
@ConditionalOnMissingBean(Jackson2ObjectMapperBuilder.class)
public Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.applicationContext(this.applicationContext);
if (this.jacksonProperties.getSerializationInclusion() != null) {
builder.serializationInclusion(this.jacksonProperties
.getSerializationInclusion());
}
if (this.jacksonProperties.getTimeZone() != null) {
builder.timeZone(this.jacksonProperties.getTimeZone());
}
configureFeatures(builder, this.jacksonProperties.getDeserialization());
configureFeatures(builder, this.jacksonProperties.getSerialization());
configureFeatures(builder, this.jacksonProperties.getMapper());
configureFeatures(builder, this.jacksonProperties.getParser());
configureFeatures(builder, this.jacksonProperties.getGenerator());
configureDateFormat(builder);
configurePropertyNamingStrategy(builder);
configureModules(builder);
configureLocale(builder);
return builder;
}
private void configureFeatures(Jackson2ObjectMapperBuilder builder,
Map<?, Boolean> features) {
for (Entry<?, Boolean> entry : features.entrySet()) {
if (entry.getValue() != null && entry.getValue()) {
builder.featuresToEnable(entry.getKey());
}
else {
builder.featuresToDisable(entry.getKey());
}
}
}
private void configureDateFormat(Jackson2ObjectMapperBuilder builder) {
// We support a fully qualified class name extending DateFormat or a date
// pattern string value
String dateFormat = this.jacksonProperties.getDateFormat();
if (dateFormat != null) {
try {
Class<?> dateFormatClass = ClassUtils.forName(dateFormat, null);
builder.dateFormat((DateFormat) BeanUtils
.instantiateClass(dateFormatClass));
}
catch (ClassNotFoundException ex) {
builder.dateFormat(new SimpleDateFormat(dateFormat));
}
}
}
private void configurePropertyNamingStrategy(Jackson2ObjectMapperBuilder builder) {
// We support a fully qualified class name extending Jackson's
// PropertyNamingStrategy or a string value corresponding to the constant
// names in PropertyNamingStrategy which hold default provided implementations
String strategy = this.jacksonProperties.getPropertyNamingStrategy();
if (strategy != null) {
try {
configurePropertyNamingStrategyClass(builder,
ClassUtils.forName(strategy, null));
}
catch (ClassNotFoundException ex) {
configurePropertyNamingStrategyField(builder, strategy);
}
}
}
private void configurePropertyNamingStrategyClass(
Jackson2ObjectMapperBuilder builder, Class<?> propertyNamingStrategyClass) {
builder.propertyNamingStrategy((PropertyNamingStrategy) BeanUtils
.instantiateClass(propertyNamingStrategyClass));
}
private void configurePropertyNamingStrategyField(
Jackson2ObjectMapperBuilder builder, String fieldName) {
// Find the field (this way we automatically support new constants
// that may be added by Jackson in the future)
Field field = ReflectionUtils.findField(PropertyNamingStrategy.class,
fieldName, PropertyNamingStrategy.class);
Assert.notNull(field, "Constant named '" + fieldName + "' not found on "
+ PropertyNamingStrategy.class.getName());
try {
builder.propertyNamingStrategy((PropertyNamingStrategy) field.get(null));
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
}
private void configureModules(Jackson2ObjectMapperBuilder builder) {
Collection<Module> moduleBeans = getBeans(this.applicationContext,
Module.class);
builder.modulesToInstall(moduleBeans.toArray(new Module[moduleBeans.size()]));
}
private void configureLocale(Jackson2ObjectMapperBuilder builder) {
Locale locale = this.jacksonProperties.getLocale();
if (locale != null) {
builder.locale(locale);
}
}
private static <T> Collection<T> getBeans(ListableBeanFactory beanFactory,
Class<T> type) {
return BeanFactoryUtils.beansOfTypeIncludingAncestors(beanFactory, type)
.values();
}
}
}
| spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration.java | /*
* Copyright 2012-2015 the original author or authors.
*
* 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 org.springframework.boot.autoconfigure.jackson;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat;
import com.fasterxml.jackson.datatype.joda.ser.DateTimeSerializer;
/**
* Auto configuration for Jackson. The following auto-configuration will get applied:
* <ul>
* <li>an {@link ObjectMapper} in case none is already configured.</li>
* <li>a {@link Jackson2ObjectMapperBuilder} in case none is already configured.</li>
* <li>auto-registration for all {@link Module} beans with all {@link ObjectMapper} beans
* (including the defaulted ones).</li>
* </ul>
*
* @author Oliver Gierke
* @author Andy Wilkinson
* @author Marcel Overdijk
* @author Sebastien Deleuze
* @author Johannes Stelzer
* @since 1.1.0
*/
@Configuration
@ConditionalOnClass(ObjectMapper.class)
public class JacksonAutoConfiguration {
@Autowired
private ListableBeanFactory beanFactory;
@Configuration
@ConditionalOnClass({ ObjectMapper.class, Jackson2ObjectMapperBuilder.class })
static class JacksonObjectMapperConfiguration {
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
return builder.createXmlMapper(false).build();
}
}
@Configuration
@ConditionalOnClass({ Jackson2ObjectMapperBuilder.class, DateTime.class,
DateTimeSerializer.class, JacksonJodaDateFormat.class })
static class JodaDateTimeJacksonConfiguration {
private final Log log = LogFactory.getLog(JodaDateTimeJacksonConfiguration.class);
@Autowired
private JacksonProperties jacksonProperties;
@Bean
public SimpleModule jodaDateTimeSerializationModule() {
SimpleModule module = new SimpleModule();
JacksonJodaDateFormat jacksonJodaFormat = getJacksonJodaDateFormat();
if (jacksonJodaFormat != null) {
module.addSerializer(DateTime.class, new DateTimeSerializer(
jacksonJodaFormat));
}
return module;
}
private JacksonJodaDateFormat getJacksonJodaDateFormat() {
if (this.jacksonProperties.getJodaDateTimeFormat() != null) {
return new JacksonJodaDateFormat(DateTimeFormat.forPattern(
this.jacksonProperties.getJodaDateTimeFormat()).withZoneUTC());
}
if (this.jacksonProperties.getDateFormat() != null) {
try {
return new JacksonJodaDateFormat(DateTimeFormat.forPattern(
this.jacksonProperties.getDateFormat()).withZoneUTC());
}
catch (IllegalArgumentException ex) {
if (this.log.isWarnEnabled()) {
this.log.warn("spring.jackson.date-format could not be used to "
+ "configure formatting of Joda's DateTime. You may want "
+ "to configure spring.jackson.joda-date-time-format as "
+ "well.");
}
}
}
return null;
}
}
@Configuration
@ConditionalOnClass({ ObjectMapper.class, Jackson2ObjectMapperBuilder.class })
@EnableConfigurationProperties(JacksonProperties.class)
static class JacksonObjectMapperBuilderConfiguration implements
ApplicationContextAware {
private ApplicationContext applicationContext;
@Autowired
private JacksonProperties jacksonProperties;
@Bean
@ConditionalOnMissingBean(Jackson2ObjectMapperBuilder.class)
public Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.applicationContext(this.applicationContext);
if (this.jacksonProperties.getSerializationInclusion() != null) {
builder.serializationInclusion(this.jacksonProperties
.getSerializationInclusion());
}
if (this.jacksonProperties.getTimeZone() != null) {
builder.timeZone(this.jacksonProperties.getTimeZone());
}
configureFeatures(builder, this.jacksonProperties.getDeserialization());
configureFeatures(builder, this.jacksonProperties.getSerialization());
configureFeatures(builder, this.jacksonProperties.getMapper());
configureFeatures(builder, this.jacksonProperties.getParser());
configureFeatures(builder, this.jacksonProperties.getGenerator());
configureDateFormat(builder);
configurePropertyNamingStrategy(builder);
configureModules(builder);
configureLocale(builder);
return builder;
}
private void configureFeatures(Jackson2ObjectMapperBuilder builder,
Map<?, Boolean> features) {
for (Entry<?, Boolean> entry : features.entrySet()) {
if (entry.getValue() != null && entry.getValue()) {
builder.featuresToEnable(entry.getKey());
}
else {
builder.featuresToDisable(entry.getKey());
}
}
}
private void configureDateFormat(Jackson2ObjectMapperBuilder builder) {
// We support a fully qualified class name extending DateFormat or a date
// pattern string value
String dateFormat = this.jacksonProperties.getDateFormat();
if (dateFormat != null) {
try {
Class<?> dateFormatClass = ClassUtils.forName(dateFormat, null);
builder.dateFormat((DateFormat) BeanUtils
.instantiateClass(dateFormatClass));
}
catch (ClassNotFoundException ex) {
builder.dateFormat(new SimpleDateFormat(dateFormat));
}
}
}
private void configurePropertyNamingStrategy(Jackson2ObjectMapperBuilder builder) {
// We support a fully qualified class name extending Jackson's
// PropertyNamingStrategy or a string value corresponding to the constant
// names in PropertyNamingStrategy which hold default provided implementations
String strategy = this.jacksonProperties.getPropertyNamingStrategy();
if (strategy != null) {
try {
configurePropertyNamingStrategyClass(builder,
ClassUtils.forName(strategy, null));
}
catch (ClassNotFoundException ex) {
configurePropertyNamingStrategyField(builder, strategy);
}
}
}
private void configurePropertyNamingStrategyClass(
Jackson2ObjectMapperBuilder builder, Class<?> propertyNamingStrategyClass) {
builder.propertyNamingStrategy((PropertyNamingStrategy) BeanUtils
.instantiateClass(propertyNamingStrategyClass));
}
private void configurePropertyNamingStrategyField(
Jackson2ObjectMapperBuilder builder, String fieldName) {
// Find the field (this way we automatically support new constants
// that may be added by Jackson in the future)
Field field = ReflectionUtils.findField(PropertyNamingStrategy.class,
fieldName, PropertyNamingStrategy.class);
Assert.notNull(field, "Constant named '" + fieldName + "' not found on "
+ PropertyNamingStrategy.class.getName());
try {
builder.propertyNamingStrategy((PropertyNamingStrategy) field.get(null));
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
}
private void configureModules(Jackson2ObjectMapperBuilder builder) {
Collection<Module> moduleBeans = getBeans(this.applicationContext,
Module.class);
builder.modulesToInstall(moduleBeans.toArray(new Module[moduleBeans.size()]));
}
private void configureLocale(Jackson2ObjectMapperBuilder builder) {
Locale locale = this.jacksonProperties.getLocale();
if (locale != null) {
builder.locale(locale);
}
}
private static <T> Collection<T> getBeans(ListableBeanFactory beanFactory,
Class<T> type) {
return BeanFactoryUtils.beansOfTypeIncludingAncestors(beanFactory, type)
.values();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
}
}
| Polish
| spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration.java | Polish | |
Java | bsd-2-clause | b1010d78b357fb5b9f8707d1939051093da57ac9 | 0 | Noremac201/runelite,Sethtroll/runelite,devinfrench/runelite,KronosDesign/runelite,Sethtroll/runelite,abelbriggs1/runelite,abelbriggs1/runelite,KronosDesign/runelite,runelite/runelite,Noremac201/runelite,l2-/runelite,runelite/runelite,l2-/runelite,devinfrench/runelite,runelite/runelite,abelbriggs1/runelite | /*
* Copyright (c) 2017, Aria <aria@ar1as.space>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.grounditems;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import net.runelite.api.Client;
import net.runelite.api.GameState;
import net.runelite.api.Item;
import net.runelite.api.ItemLayer;
import net.runelite.api.Node;
import net.runelite.api.Player;
import net.runelite.api.Point;
import net.runelite.api.Region;
import net.runelite.api.Tile;
import net.runelite.api.widgets.WidgetInfo;
import net.runelite.client.ItemManager;
import net.runelite.client.RuneLite;
import net.runelite.client.ui.overlay.Overlay;
import net.runelite.client.ui.overlay.OverlayPosition;
import net.runelite.http.api.item.ItemPrice;
import net.runelite.rs.api.ItemComposition;
public class GroundItemsOverlay extends Overlay
{
private static final int REGION_SIZE = 104;
// The game won't send anything higher than this value to the plugin -
// so we replace any item quantity higher with "Lots" instead.
private static final int MAX_QUANTITY = 65535;
// The max distance between the player and the item.
private static final int MAX_RANGE = 2400;
// The 15 pixel gap between each drawn ground item.
private static final int STRING_GAP = 15;
// Threshold for highlighting items as blue.
private static final int LOW_VALUE = 20_000;
private static final Color BRIGHT_BLUE = new Color(102, 178, 255);
// Threshold for highlighting items as green.
private static final int MEDIUM_VALUE = 100_000;
private static final Color BRIGHT_GREEN = new Color(153, 255, 153);
// Threshold for highlighting items as amber.
private static final int HIGH_VALUE = 1_000_000;
private static final Color AMBER = new Color(255, 150, 0);
// Threshold for highlighting items as pink.
private static final int INSANE_VALUE = 10_000_000;
private static final Color FADED_PINK = new Color(255, 102, 178);
// Color to use if an item is highlighted in the config.
private static final Color PURPLE = new Color(170, 0, 255);
// Used when getting High Alchemy value - multiplied by general store price.
private static final float HIGH_ALCHEMY_CONSTANT = 0.6f;
// Regex for splitting the hidden items in the config.
private static final String DELIMITER_REGEX = "\\s*,\\s*";
private final Client client = RuneLite.getClient();
private final GroundItemsConfig config;
private final ItemManager itemManager = RuneLite.getRunelite().getItemManager();
private final StringBuilder itemStringBuilder = new StringBuilder();
private final LoadingCache<Integer, ItemComposition> itemCache = CacheBuilder.newBuilder()
.maximumSize(1024L)
.expireAfterAccess(1, TimeUnit.MINUTES)
.build(new CacheLoader<Integer, ItemComposition>()
{
@Override
public ItemComposition load(Integer key) throws Exception
{
return client.getItemDefinition(key);
}
});
public GroundItemsOverlay(GroundItems plugin)
{
super(OverlayPosition.DYNAMIC);
this.config = plugin.getConfig();
}
@Override
public Dimension render(Graphics2D graphics)
{
// won't draw if not logged in
if (client.getGameState() != GameState.LOGGED_IN || !config.enabled())
{
return null;
}
//if the player is logged in but viewing the click to play screen exit
if (client.getWidget(WidgetInfo.LOGIN_CLICK_TO_PLAY_SCREEN) != null)
{
return null;
}
//Widget bank = client.getWidget(WidgetInfo.BANK_ITEM_CONTAINER);
//if (bank != null && !bank.isHidden())
//{
// return null;
//}
// gets the hidden/highlighted items from the text box in the config
String configItems = config.getHiddenItems();
List<String> hiddenItems = Arrays.asList(configItems.split(DELIMITER_REGEX));
// note: both of these lists are immutable
configItems = config.getHighlightItems();
List<String> highlightedItems = Arrays.asList(configItems.split(DELIMITER_REGEX));
Region region = client.getRegion();
Tile[][][] tiles = region.getTiles();
FontMetrics fm = graphics.getFontMetrics();
Player player = client.getLocalPlayer();
if (player == null)
{
return null;
}
int z = client.getPlane();
for (int x = 0; x < REGION_SIZE; x++)
{
for (int y = 0; y < REGION_SIZE; y++)
{
Tile tile = tiles[z][x][y];
if (tile == null)
{
continue;
}
ItemLayer itemLayer = tile.getItemLayer();
if (itemLayer == null)
{
continue;
}
if (player.getLocalLocation().distanceTo(itemLayer.getLocalLocation()) >= MAX_RANGE)
{
continue;
}
Node current = itemLayer.getBottom();
Map<Integer, Integer> items = new LinkedHashMap<>();
// adds the items on the ground to the ArrayList to be drawn
while (current instanceof Item)
{
Item item = (Item) current;
int itemId = item.getId();
int itemQuantity = item.getQuantity();
ItemComposition itemDefinition = itemCache.getUnchecked(itemId);
Integer currentQuantity = items.get(itemId);
if (!hiddenItems.contains(itemDefinition.getName()))
{
if (currentQuantity == null)
{
items.put(itemId, itemQuantity);
}
else
{
items.put(itemId, currentQuantity + itemQuantity);
}
}
current = current.getNext();
}
// The bottom item is drawn first
List<Integer> itemIds = new ArrayList<>(items.keySet());
Collections.reverse(itemIds);
for (int i = 0; i < itemIds.size(); ++i)
{
int itemId = itemIds.get(i);
int quantity = items.get(itemId);
ItemComposition item = itemCache.getUnchecked(itemId);
if (item == null)
{
continue;
}
itemStringBuilder.append(item.getName());
if (quantity > 1)
{
if (quantity >= MAX_QUANTITY)
{
itemStringBuilder.append(" (Lots!)");
}
else
{
itemStringBuilder.append(" (").append(quantity).append(")");
}
}
// sets item ID to unnoted version, if noted
if (item.getNote() != -1)
{
itemId = item.getLinkedNoteId();
}
Color textColor = Color.WHITE; // Color to use when drawing the ground item
ItemPrice itemPrice = itemManager.get(itemId);
if (itemPrice != null && config.showGEPrice())
{
int cost = itemPrice.getPrice() * quantity;
// set the color according to rarity, if possible
if (cost >= INSANE_VALUE) // 10,000,000 gp
{
textColor = FADED_PINK;
}
else if (cost >= HIGH_VALUE) // 1,000,000 gp
{
textColor = AMBER;
}
else if (cost >= MEDIUM_VALUE) // 100,000 gp
{
textColor = BRIGHT_GREEN;
}
else if (cost >= LOW_VALUE) // 20,000 gp
{
textColor = BRIGHT_BLUE;
}
itemStringBuilder.append(" (EX: ")
.append(ItemManager.quantityToStackSize(cost))
.append(" gp)");
}
if (config.showHAValue())
{
itemStringBuilder.append(" (HA: ")
.append(Math.round(item.getPrice() * HIGH_ALCHEMY_CONSTANT))
.append(" gp)");
}
if (highlightedItems.contains(item.getName()))
{
textColor = PURPLE;
}
String itemString = itemStringBuilder.toString();
itemStringBuilder.setLength(0);
Point point = itemLayer.getCanvasLocation();
// if the item is offscreen, don't bother drawing it
if (point == null)
{
continue;
}
int screenX = point.getX() + 2 - (fm.stringWidth(itemString) / 2);
// Drawing the shadow for the text, 1px on both x and y
graphics.setColor(Color.BLACK);
graphics.drawString(itemString, screenX + 1, point.getY() - (STRING_GAP * i) + 1);
// Drawing the text itself
graphics.setColor(textColor);
graphics.drawString(itemString, screenX, point.getY() - (STRING_GAP * i));
}
}
}
return null;
}
}
| runelite-client/src/main/java/net/runelite/client/plugins/grounditems/GroundItemsOverlay.java | /*
* Copyright (c) 2017, Aria <aria@ar1as.space>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.grounditems;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Arrays;
import net.runelite.api.Client;
import net.runelite.api.GameState;
import net.runelite.api.Item;
import net.runelite.api.ItemLayer;
import net.runelite.api.Node;
import net.runelite.api.Player;
import net.runelite.api.Point;
import net.runelite.api.Region;
import net.runelite.api.Tile;
import net.runelite.api.widgets.Widget;
import net.runelite.api.widgets.WidgetInfo;
import net.runelite.client.ItemManager;
import net.runelite.client.RuneLite;
import net.runelite.client.ui.overlay.Overlay;
import net.runelite.client.ui.overlay.OverlayPosition;
import net.runelite.http.api.item.ItemPrice;
import net.runelite.rs.api.ItemComposition;
public class GroundItemsOverlay extends Overlay
{
private static final int REGION_SIZE = 104;
// The game won't send anything higher than this value to the plugin -
// so we replace any item quantity higher with "Lots" instead.
private static final int MAX_QUANTITY = 65535;
// The max distance between the player and the item.
private static final int MAX_RANGE = 2400;
// The 15 pixel gap between each drawn ground item.
private static final int STRING_GAP = 15;
// Threshold for highlighting items as blue.
private static final int LOW_VALUE = 20_000;
private static final Color BRIGHT_BLUE = new Color(102, 178, 255);
// Threshold for highlighting items as green.
private static final int MEDIUM_VALUE = 100_000;
private static final Color BRIGHT_GREEN = new Color(153, 255, 153);
// Threshold for highlighting items as amber.
private static final int HIGH_VALUE = 1_000_000;
private static final Color AMBER = new Color(255, 150, 0);
// Threshold for highlighting items as pink.
private static final int INSANE_VALUE = 10_000_000;
private static final Color FADED_PINK = new Color(255, 102, 178);
// Color to use if an item is highlighted in the config.
private static final Color PURPLE = new Color(170, 0, 255);
// Used when getting High Alchemy value - multiplied by general store price.
private static final float HIGH_ALCHEMY_CONSTANT = 0.6f;
// Regex for splitting the hidden items in the config.
private static final String DELIMITER_REGEX = "\\s*,\\s*";
private final Client client = RuneLite.getClient();
private final GroundItemsConfig config;
private final ItemManager itemManager = RuneLite.getRunelite().getItemManager();
private final StringBuilder itemStringBuilder = new StringBuilder();
public GroundItemsOverlay(GroundItems plugin)
{
super(OverlayPosition.DYNAMIC);
this.config = plugin.getConfig();
}
@Override
public Dimension render(Graphics2D graphics)
{
// won't draw if not logged in
if (client.getGameState() != GameState.LOGGED_IN || !config.enabled())
{
return null;
}
//if the player is logged in but viewing the click to play screen exit
if (client.getWidget(WidgetInfo.LOGIN_CLICK_TO_PLAY_SCREEN) != null)
{
return null;
}
//Widget bank = client.getWidget(WidgetInfo.BANK_ITEM_CONTAINER);
//if (bank != null && !bank.isHidden())
//{
// return null;
//}
// gets the hidden/highlighted items from the text box in the config
String configItems = config.getHiddenItems();
List<String> hiddenItems = Arrays.asList(configItems.split(DELIMITER_REGEX));
// note: both of these lists are immutable
configItems = config.getHighlightItems();
List<String> highlightedItems = Arrays.asList(configItems.split(DELIMITER_REGEX));
Region region = client.getRegion();
Tile[][][] tiles = region.getTiles();
FontMetrics fm = graphics.getFontMetrics();
Player player = client.getLocalPlayer();
if (player == null)
{
return null;
}
int z = client.getPlane();
for (int x = 0; x < REGION_SIZE; x++)
{
for (int y = 0; y < REGION_SIZE; y++)
{
Tile tile = tiles[z][x][y];
if (tile == null)
{
continue;
}
ItemLayer itemLayer = tile.getItemLayer();
if (itemLayer == null)
{
continue;
}
if (player.getLocalLocation().distanceTo(itemLayer.getLocalLocation()) >= MAX_RANGE)
{
continue;
}
Node current = itemLayer.getBottom();
Map<Integer, Integer> items = new LinkedHashMap<>();
// adds the items on the ground to the ArrayList to be drawn
while (current instanceof Item)
{
Item item = (Item) current;
int itemId = item.getId();
int itemQuantity = item.getQuantity();
// Item does not support getting the name, so we need to get the ItemComposition instead
ItemComposition itemDefinition = client.getItemDefinition(itemId);
Integer currentQuantity = items.get(itemId);
if (!hiddenItems.contains(itemDefinition.getName()))
{
if (currentQuantity == null)
{
items.put(itemId, itemQuantity);
}
else
{
items.put(itemId, currentQuantity + itemQuantity);
}
}
current = current.getNext();
}
// The bottom item is drawn first
List<Integer> itemIds = new ArrayList<>(items.keySet());
Collections.reverse(itemIds);
for (int i = 0; i < itemIds.size(); ++i)
{
int itemId = itemIds.get(i);
int quantity = items.get(itemId);
ItemComposition item = client.getItemDefinition(itemId);
if (item == null)
{
continue;
}
itemStringBuilder.append(item.getName());
if (quantity > 1)
{
if (quantity >= MAX_QUANTITY)
{
itemStringBuilder.append(" (Lots!)");
}
else
{
itemStringBuilder.append(" (").append(quantity).append(")");
}
}
// sets item ID to unnoted version, if noted
if (item.getNote() != -1)
{
itemId = item.getLinkedNoteId();
}
Color textColor = Color.WHITE; // Color to use when drawing the ground item
ItemPrice itemPrice = itemManager.get(itemId);
if (itemPrice != null && config.showGEPrice())
{
int cost = itemPrice.getPrice() * quantity;
// set the color according to rarity, if possible
if (cost >= INSANE_VALUE) // 10,000,000 gp
{
textColor = FADED_PINK;
}
else if (cost >= HIGH_VALUE) // 1,000,000 gp
{
textColor = AMBER;
}
else if (cost >= MEDIUM_VALUE) // 100,000 gp
{
textColor = BRIGHT_GREEN;
}
else if (cost >= LOW_VALUE) // 20,000 gp
{
textColor = BRIGHT_BLUE;
}
itemStringBuilder.append(" (EX: ")
.append(ItemManager.quantityToStackSize(cost))
.append(" gp)");
}
if (config.showHAValue())
{
itemStringBuilder.append(" (HA: ")
.append(Math.round(item.getPrice() * HIGH_ALCHEMY_CONSTANT))
.append(" gp)");
}
if (highlightedItems.contains(item.getName()))
{
textColor = PURPLE;
}
String itemString = itemStringBuilder.toString();
itemStringBuilder.setLength(0);
Point point = itemLayer.getCanvasLocation();
// if the item is offscreen, don't bother drawing it
if (point == null)
{
continue;
}
int screenX = point.getX() + 2 - (fm.stringWidth(itemString) / 2);
// Drawing the shadow for the text, 1px on both x and y
graphics.setColor(Color.BLACK);
graphics.drawString(itemString, screenX + 1, point.getY() - (STRING_GAP * i) + 1);
// Drawing the text itself
graphics.setColor(textColor);
graphics.drawString(itemString, screenX, point.getY() - (STRING_GAP * i));
}
}
}
return null;
}
}
| runelite-client: add cache for item compositions in grounditems plugin
| runelite-client/src/main/java/net/runelite/client/plugins/grounditems/GroundItemsOverlay.java | runelite-client: add cache for item compositions in grounditems plugin | |
Java | bsd-3-clause | 4138a350ed5314c159d2e485f7e34b86681e7c02 | 0 | CBIIT/caaers,NCIP/caaers,CBIIT/caaers,CBIIT/caaers,NCIP/caaers,NCIP/caaers,NCIP/caaers,CBIIT/caaers,CBIIT/caaers | package gov.nih.nci.cabig.caaers.dao;
import static edu.nwu.bioinformatics.commons.testing.CoreTestCase.assertDayOfDate;
import static edu.nwu.bioinformatics.commons.testing.CoreTestCase.prependMessage;
import static gov.nih.nci.cabig.caaers.CaaersUseCase.CREATE_EXPEDITED_REPORT;
import edu.nwu.bioinformatics.commons.DateUtils;
import edu.nwu.bioinformatics.commons.testing.CoreTestCase;
import gov.nih.nci.cabig.caaers.CaaersUseCases;
import gov.nih.nci.cabig.caaers.DaoNoSecurityTestCase;
import gov.nih.nci.cabig.caaers.api.AdverseEventReportSerializer;
import gov.nih.nci.cabig.caaers.dao.report.ReportDefinitionDao;
import gov.nih.nci.cabig.caaers.domain.AdverseEvent;
import gov.nih.nci.cabig.caaers.domain.AdverseEventResponseDescription;
import gov.nih.nci.cabig.caaers.domain.Attribution;
import gov.nih.nci.cabig.caaers.domain.ConcomitantMedication;
import gov.nih.nci.cabig.caaers.domain.CourseAgent;
import gov.nih.nci.cabig.caaers.domain.CtcTerm;
import gov.nih.nci.cabig.caaers.domain.DelayUnits;
import gov.nih.nci.cabig.caaers.domain.DiseaseHistory;
import gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport;
import gov.nih.nci.cabig.caaers.domain.Fixtures;
import gov.nih.nci.cabig.caaers.domain.Grade;
import gov.nih.nci.cabig.caaers.domain.Hospitalization;
import gov.nih.nci.cabig.caaers.domain.Lab;
import gov.nih.nci.cabig.caaers.domain.LabValue;
import gov.nih.nci.cabig.caaers.domain.MedicalDevice;
import gov.nih.nci.cabig.caaers.domain.OtherCause;
import gov.nih.nci.cabig.caaers.domain.ParticipantHistory;
import gov.nih.nci.cabig.caaers.domain.Physician;
import gov.nih.nci.cabig.caaers.domain.PostAdverseEventStatus;
import gov.nih.nci.cabig.caaers.domain.RadiationIntervention;
import gov.nih.nci.cabig.caaers.domain.ReportPerson;
import gov.nih.nci.cabig.caaers.domain.Reporter;
import gov.nih.nci.cabig.caaers.domain.SurgeryIntervention;
import gov.nih.nci.cabig.caaers.domain.TreatmentInformation;
import gov.nih.nci.cabig.caaers.domain.attribution.ConcomitantMedicationAttribution;
import gov.nih.nci.cabig.caaers.domain.attribution.CourseAgentAttribution;
import gov.nih.nci.cabig.caaers.domain.attribution.DeviceAttribution;
import gov.nih.nci.cabig.caaers.domain.attribution.DiseaseAttribution;
import gov.nih.nci.cabig.caaers.domain.attribution.OtherCauseAttribution;
import gov.nih.nci.cabig.caaers.domain.attribution.RadiationAttribution;
import gov.nih.nci.cabig.caaers.domain.attribution.SurgeryAttribution;
import gov.nih.nci.cabig.caaers.domain.report.Report;
import gov.nih.nci.cabig.caaers.domain.workflow.ReportReviewComment;
import gov.nih.nci.cabig.ctms.lang.DateTools;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.core.io.ClassPathResource;
/**
* @author Rhett Sutphin
*/
@CaaersUseCases( { CREATE_EXPEDITED_REPORT })
public class ExpeditedAdverseEventReportDaoTest extends DaoNoSecurityTestCase<ExpeditedAdverseEventReportDao> {
private CtcTermDao ctcTermDao = (CtcTermDao) getApplicationContext().getBean("ctcTermDao");
private AnatomicSiteDao anatomicSiteDao = (AnatomicSiteDao) getApplicationContext().getBean(
"anatomicSiteDao");
private InterventionSiteDao interventionSiteDao = (InterventionSiteDao) getApplicationContext()
.getBean("interventionSiteDao");
private ReportDefinitionDao reportDefinitionDao = (ReportDefinitionDao) getApplicationContext()
.getBean("reportDefinitionDao");
private AdverseEventReportingPeriodDao reportingPeriodDao = (AdverseEventReportingPeriodDao) getApplicationContext().getBean("adverseEventReportingPeriodDao");
public void testGet() throws Exception {
ExpeditedAdverseEventReport loaded = getDao().getById(-1);
assertEquals("Wrong AE 0", -70, (int) loaded.getAdverseEvents().get(0).getId());
assertEquals("Wrong AE 1", -11, (int) loaded.getAdverseEvents().get(1).getId());
assertEquals("Wrong assignment", -14, (int) loaded.getReportingPeriod().getAssignment().getId());
CoreTestCase.assertDayOfDate("Wrong created at (date)", 2004, Calendar.SEPTEMBER, 4, loaded
.getCreatedAt());
CoreTestCase.assertTimeOfDate("Wrong created at (time)", 13, 15, 30, 0, loaded
.getCreatedAt());
}
public void testGetLabs() throws Exception {
ExpeditedAdverseEventReport loaded = getDao().getById(-1);
assertEquals("Wrong number of labs", 3, loaded.getLabs().size());
assertEquals("Wrong lab 0", -21, (int) loaded.getLabs().get(0).getId());
assertEquals("Wrong lab 1", -20, (int) loaded.getLabs().get(1).getId());
assertEquals("Wrong lab 2", -22, (int) loaded.getLabs().get(2).getId());
Lab l1 = loaded.getLabs().get(1);
assertSame("Wrong report", loaded, l1.getReport());
assertEquals("Wrong units", "hectares/liter", l1.getUnits());
assertLabValue("Wrong baseline", "3.66", 2003, Calendar.APRIL, 17, l1.getBaseline());
assertLabValue("Wrong nadir", "0.4", 2007, Calendar.MARCH, 14, l1.getNadir());
assertLabValue("Wrong nadir", "3.54", 2007, Calendar.MARCH, 19, l1.getRecovery());
}
private static void assertLabValue(String message, String expectedValue, int expectedYear,
int expectedMonth, int expectedDay, LabValue actual) {
assertDayOfDate(prependMessage(message) + "wrong date", expectedYear, expectedMonth,
expectedDay, actual.getDate());
assertEquals(prependMessage(message) + "wrong value", expectedValue, actual.getValue());
}
public void testGetConcomitantMedications() throws Exception {
ExpeditedAdverseEventReport loaded = getDao().getById(-1);
assertEquals("Wrong number of concomitant meds", 2, loaded.getConcomitantMedications()
.size());
assertEquals("Wrong con med 0", -31, (int) loaded.getConcomitantMedications().get(0)
.getId());
assertEquals("Wrong con med 1", -30, (int) loaded.getConcomitantMedications().get(1)
.getId());
ConcomitantMedication cm1 = loaded.getConcomitantMedications().get(1);
assertSame("Wrong report", loaded, cm1.getReport());
assertNull("Wrong agent name", cm1.getAgentName());
}
public void testGetTreatmentInformation() throws Exception {
ExpeditedAdverseEventReport loaded = getDao().getById(-1);
assertNotNull("No treatment info", loaded.getTreatmentInformation());
TreatmentInformation actual = loaded.getTreatmentInformation();
assertEquals("Wrong treatment information", -10, (int) actual.getId());
assertDayOfDate("Wrong first course date", 2005, Calendar.JUNE, 4, actual
.getFirstCourseDate());
assertDayOfDate("Wrong adverse event course date", 2006, Calendar.JULY, 9, actual
.getAdverseEventCourse().getDate());
assertEquals("Wrong adverse event course number", 8, (int) actual.getAdverseEventCourse()
.getNumber());
assertEquals("Wrong number of course agents", 2, actual.getCourseAgents().size());
assertEquals("Wrong course agent 0", -19, (int) actual.getCourseAgents().get(0).getId());
assertNotNull("Worng association to TreatmentAssignment", actual.getTreatmentAssignment());
assertEquals("Wrong treatmentAssignment code", "TAC010", actual.getTreatmentAssignment()
.getCode());
CourseAgent agent1 = actual.getCourseAgents().get(1);
assertEquals("Wrong course agent 1", -20, (int) agent1.getId());
assertEquals("Wrong delay in minutes", new BigDecimal(240), agent1.getAdministrationDelay());
assertEquals("Wrong delay amount", new BigDecimal(4), agent1.getAdministrationDelayAmount());
assertEquals("Wrong delay units", DelayUnits.HOURS, agent1.getAdministrationDelayUnits());
assertEquals("Wrong dose amount", "17.4", agent1.getDose().getAmount());
assertEquals("Wrong dose units", "mg", agent1.getDose().getUnits());
assertEquals("Wrong dose route", "aural", agent1.getDose().getRoute());
assertEquals("Wrong duration", "8 times every third hour", agent1.getDurationAndSchedule());
assertEquals("Wrong total dose", new BigDecimal("7"), agent1
.getTotalDoseAdministeredThisCourse());
assertDayOfDate("Wrong last administered date", 2006, Calendar.JULY, 10, agent1
.getLastAdministeredDate());
}
public void testGetOtherCauses() throws Exception {
ExpeditedAdverseEventReport loaded = getDao().getById(-1);
assertEquals("Wrong number of causes", 3, loaded.getOtherCauses().size());
assertEquals("Wrong cause 0", -81, (int) loaded.getOtherCauses().get(0).getId());
assertEquals("Wrong cause 1", -80, (int) loaded.getOtherCauses().get(1).getId());
assertEquals("Wrong cause 2", -82, (int) loaded.getOtherCauses().get(2).getId());
assertEquals("Wrong text for cause 1", "Crossed against light", loaded.getOtherCauses()
.get(1).getText());
}
public void testGetResponseDescription() throws Exception {
AdverseEventResponseDescription actual = getDao().getById(-1).getResponseDescription();
assertEquals("Wrong present status", PostAdverseEventStatus.RECOVERED_WITH_SEQUELAE, actual
.getPresentStatus());
assertEquals("Wrong event description", "It was real bad", actual.getEventDescription());
assertEquals("Wrong retreated flag", Boolean.FALSE, actual.getRetreated());
assertDayOfDate("Wrong date removed", 2012, Calendar.MARCH, 4, actual.getRecoveryDate());
}
public void testGetReports() throws Exception {
List<Report> actual = getDao().getById(-1).getReports();
assertNotNull(actual);
assertEquals("Wrong number of reports", 2, actual.size());
assertEquals("Wrong report 0", -40, (int) actual.get(1).getId());
Report actualReport1 = actual.get(0);
assertNotNull(actualReport1);
assertEquals("Wrong report 1", -41, (int) actualReport1.getId());
assertEquals("Wrong def for report 1", -30, (int) actualReport1.getReportDefinition()
.getId());
}
public void testGetReporter() throws Exception {
Reporter actual = getDao().getById(-1).getReporter();
assertNotNull("No reporter", actual);
assertEquals("Wrong reporter", -100, (int) actual.getId());
assertEquals("DiMaggio", actual.getLastName());
assertEquals("Wrong number of contact mechanisms", 2, actual.getContactMechanisms().size());
assertEquals("joltin@joe.com", actual.getContactMechanisms().get(ReportPerson.EMAIL));
assertEquals("212 555-1212", actual.getContactMechanisms().get(ReportPerson.PHONE));
}
public void testGetPhysician() throws Exception {
Physician actual = getDao().getById(-1).getPhysician();
assertNotNull("No physician", actual);
assertEquals("Wrong reporter", -101, (int) actual.getId());
assertEquals("Sandpiper", actual.getLastName());
assertEquals("Wrong number of contact mechanisms", 0, actual.getContactMechanisms().size());
}
public void testGetDiseaseHistory() throws Exception {
DiseaseHistory actual = getDao().getById(-1).getDiseaseHistory();
assertNotNull("No disease history", actual);
assertEquals("Wrong history", -53, (int) actual.getId());
assertEquals("Wrong primary disease site", -1, (int) actual.getCodedPrimaryDiseaseSite()
.getId());
assertEquals("Wrong diagnosis date.DAY", new Integer(4), actual.getDiagnosisDate().getDay());
assertEquals("Wrong diagnosis date.Month", new Integer(1), actual.getDiagnosisDate().getMonth());
assertEquals("Wrong diagnosis date.Year", new Integer(2007), actual.getDiagnosisDate().getYear());
assertEquals("Wrong number of metastatic disease sites", 1, actual
.getMetastaticDiseaseSites().size());
assertEquals("Wrong metastatic disease site", -5, (int) actual.getMetastaticDiseaseSites()
.get(0).getId());
assertTrue(true);
}
public void testGetParticipantHistory() throws Exception {
ParticipantHistory actual = getDao().getById(-1).getParticipantHistory();
assertNotNull("No participant history", actual);
assertEquals("Wrong history", -57, (int) actual.getId());
assertEquals("Wrong height", new BigDecimal("134.3"), actual.getHeight().getQuantity());
assertEquals("Wrong height unit", "cm", actual.getHeight().getUnit());
assertEquals("Wrong weight", new BigDecimal("54.2"), actual.getWeight().getQuantity());
assertEquals("Wrong weight unit", "kg", actual.getWeight().getUnit());
assertEquals("Wrong baseline", "About here", actual.getBaselinePerformanceStatus());
}
public void testSaveBasics() throws Exception {
doSaveTest(new SaveTester() {
public void setupReport(ExpeditedAdverseEventReport report) {
CtcTerm term = ctcTermDao.getById(3012);
AdverseEvent event0 = new AdverseEvent();
event0.setGrade(Grade.MILD);
event0.setAdverseEventCtcTerm(Fixtures.createAdverseEventCtcTerm(event0, term));
event0.setExpected(Boolean.FALSE);
event0.setHospitalization(Hospitalization.NO);
event0.setStartDate(new Timestamp(DateUtils.createDate(2004, Calendar.APRIL, 25)
.getTime() + 600000));
report.getReportingPeriod().addAdverseEvent(event0);
AdverseEvent event1 = new AdverseEvent();
event1.setGrade(Grade.SEVERE);
event1.setAdverseEventCtcTerm(Fixtures.createAdverseEventCtcTerm(event0, term));
event1.setExpected(Boolean.FALSE);
event1.setHospitalization(Hospitalization.YES);
report.getReportingPeriod().addAdverseEvent(event1);
report.getAdverseEvents().clear();
report.addAdverseEvent(event0);
report.addAdverseEvent(event1);
}
public void assertCorrect(ExpeditedAdverseEventReport loaded) {
assertEquals("Wrong assignment", -14, (int) loaded.getAssignment().getId());
assertEquals("Wrong number of AEs", 2, loaded.getAdverseEvents().size());
AdverseEvent loadedEvent0 = loaded.getAdverseEvents().get(0);
assertNotNull("Cascaded AE not found", loadedEvent0);
assertEquals("Wrong grade", Grade.MILD, loadedEvent0.getGrade());
assertEquals("Wrong CTC term", 3012, (int) loadedEvent0.getAdverseEventCtcTerm()
.getCtcTerm().getId());
assertNotNull("No report", loadedEvent0.getReport());
assertEquals("Wrong hospitalization", Hospitalization.NO,
loadedEvent0.getHospitalization());
assertEquals("Wrong expectedness", Boolean.FALSE, loadedEvent0.getExpected());
assertNotNull("Second cascaded AE not found", loaded.getAdverseEvents().get(1));
}
});
}
public void testSaveBasicsWithReordering() throws Exception {
Integer reportId = null;
{
ExpeditedAdverseEventReport report = createMinimalAeReport();
CtcTerm term = ctcTermDao.getById(3012);
AdverseEvent event0 = new AdverseEvent();
event0.setGrade(Grade.MILD);
event0.setAdverseEventCtcTerm(Fixtures.createAdverseEventCtcTerm(event0, term));
event0.setExpected(Boolean.FALSE);
event0.setHospitalization(Hospitalization.NO);
event0.setStartDate(new Timestamp(DateUtils.createDate(2004, Calendar.APRIL, 25)
.getTime() + 600000));
report.getReportingPeriod().addAdverseEvent(event0);
AdverseEvent event1 = new AdverseEvent();
event1.setGrade(Grade.SEVERE);
event1.setAdverseEventCtcTerm(Fixtures.createAdverseEventCtcTerm(event1, term));
event1.setExpected(Boolean.FALSE);
event1.setHospitalization(Hospitalization.YES);
report.getReportingPeriod().addAdverseEvent(event1);
AdverseEvent event2 = new AdverseEvent();
event2.setGrade(Grade.DEATH);
event2.setAdverseEventCtcTerm(Fixtures.createAdverseEventCtcTerm(event2, term));
event2.setExpected(Boolean.FALSE);
event2.setHospitalization(Hospitalization.YES);
report.getReportingPeriod().addAdverseEvent(event2);
report.getAdverseEvents().clear();
report.addAdverseEvent(event0);
report.addAdverseEvent(event1);
report.addAdverseEvent(event2);
getDao().save(report);
reportId = report.getId();
assertNotNull(reportId);
}
interruptSession();
{
ExpeditedAdverseEventReport loaded = getDao().getById(reportId);
assertNotNull(loaded);
assertEquals("Wrong number of AEs", 3, loaded.getAdverseEvents().size());
AdverseEvent loadedEvent0 = loaded.getAdverseEvents().get(0);
assertNotNull("Cascaded AE not found", loadedEvent0);
assertEquals("Wrong grade", Grade.MILD, loadedEvent0.getGrade());
assertNotNull("Second cascaded AE not found", loaded.getAdverseEvents().get(1));
assertEquals("Wrong grade", Grade.SEVERE, loaded.getAdverseEvents().get(1).getGrade());
assertNotNull("Third cascaded AE not found", loaded.getAdverseEvents().get(2));
assertEquals("Wrong grade", Grade.DEATH, loaded.getAdverseEvents().get(2).getGrade());
//reorder
loaded.getAdverseEvents().remove(loadedEvent0);
loaded.getAdverseEvents().add(1, loadedEvent0);
getDao().save(loaded);
}
interruptSession();
{
ExpeditedAdverseEventReport loaded = getDao().getById(reportId);
assertNotNull(loaded);
assertEquals("Wrong number of AEs", 3, loaded.getAdverseEvents().size());
AdverseEvent loadedEvent0 = loaded.getAdverseEvents().get(0);
assertNotNull("Cascaded AE not found", loadedEvent0);
assertEquals("Wrong grade", Grade.SEVERE, loadedEvent0.getGrade());
assertNotNull("Second cascaded AE not found", loaded.getAdverseEvents().get(1));
assertEquals("Wrong grade", Grade.MILD, loaded.getAdverseEvents().get(1).getGrade());
assertNotNull("Third cascaded AE not found", loaded.getAdverseEvents().get(2));
assertEquals("Wrong grade", Grade.DEATH, loaded.getAdverseEvents().get(2).getGrade());
}
}
public void testSaveNewReportWithConMedWithAttribution() throws Exception {
doSaveTest(new SaveTester() {
public void setupReport(ExpeditedAdverseEventReport report) {
ConcomitantMedication conMed = report.getConcomitantMedications().get(0);
conMed.setId(-30);
conMed.setVersion(0);
conMed.setAgentName("agentName");
AdverseEvent ae0 = report.getAdverseEvents().get(0);
report.getAdverseEvents().get(0).getConcomitantMedicationAttributions().add(
new ConcomitantMedicationAttribution());
ConcomitantMedicationAttribution conMedAttrib = ae0
.getConcomitantMedicationAttributions().get(0);
conMedAttrib.setCause(conMed);
conMedAttrib.setAttribution(Attribution.PROBABLE);
}
public void assertCorrect(ExpeditedAdverseEventReport loaded) {
assertNotNull("Report not found", loaded);
assertEquals(1, loaded.getConcomitantMedications().size());
List<ConcomitantMedicationAttribution> attribs = loaded.getAdverseEvents().get(0)
.getConcomitantMedicationAttributions();
assertEquals(1, attribs.size());
assertEquals("Wrong number of con med attribs", "agentName", attribs.get(0)
.getCause().getAgentName());
}
});
}
public void testSaveNewReportWithTreatment() throws Exception {
doSaveTest(new SaveTester() {
public void setupReport(ExpeditedAdverseEventReport report) {
TreatmentInformation ti = new TreatmentInformation();
ti.getAdverseEventCourse().setDate(DateUtils.createDate(2006, Calendar.MAY, 4));
ti.getAdverseEventCourse().setNumber(4);
ti.setFirstCourseDate(DateTools.createDate(2005, Calendar.JULY, 30));
ti.getCourseAgents().get(0).setAdministrationDelay(new BigDecimal(480));
ti.getCourseAgents().get(0).getDose().setAmount("45.2");
// TODO: load the treatmentAssignment and add it, before saving.
report.setTreatmentInformation(ti);
}
public void assertCorrect(ExpeditedAdverseEventReport loaded) {
TreatmentInformation ti = loaded.getTreatmentInformation();
assertNotNull("Should have treatment info", ti);
assertDayOfDate("Wrong first course date", 2005, Calendar.JULY, 30, ti
.getFirstCourseDate());
assertEquals("Wrong AE course number", 4, (int) ti.getAdverseEventCourse()
.getNumber());
assertDayOfDate("Wrong AE course date", 2006, Calendar.MAY, 4, ti
.getAdverseEventCourse().getDate());
assertEquals("Wrong number of course agents", 1, ti.getCourseAgents().size());
CourseAgent ca = ti.getCourseAgents().get(0);
assertEquals(new BigDecimal(480), ca.getAdministrationDelay());
assertEquals("45.2", ca.getDose().getAmount());
}
});
}
public void testSaveOtherCauses() throws Exception {
doSaveTest(new SaveTester() {
public void setupReport(ExpeditedAdverseEventReport report) {
report.getOtherCauses().get(0).setText("Insomnia");
report.getOtherCauses().get(1).setText("Bus");
}
public void assertCorrect(ExpeditedAdverseEventReport loaded) {
assertEquals("Wrong number of other causes", 2, loaded.getOtherCauses().size());
assertEquals("Wrong cause 0", "Insomnia", loaded.getOtherCauses().get(0).getText());
assertEquals("Wrong cause 1", "Bus", loaded.getOtherCauses().get(1).getText());
}
});
}
public void testSaveNewContactMechanisms() throws Exception {
doSaveTest(new SaveTester() {
public void setupReport(ExpeditedAdverseEventReport report) {
report.getPhysician().getContactMechanisms().put("phone", "312-333-2100");
}
public void assertCorrect(ExpeditedAdverseEventReport loaded) {
assertEquals(2, loaded.getPhysician().getContactMechanisms().size());
assertEquals("312-333-2100", loaded.getPhysician().getContactMechanisms().get(
"phone"));
}
});
}
public void testDeleteContactMechanism() throws Exception {
{
ExpeditedAdverseEventReport report = getDao().getById(-1);
assertEquals(2, report.getReporter().getContactMechanisms().size());
report.getReporter().getContactMechanisms().remove("e-mail");
assertEquals("Not removed from memory copy", 1, report.getReporter()
.getContactMechanisms().size());
getDao().save(report);
}
interruptSession();
ExpeditedAdverseEventReport reloaded = getDao().getById(-1);
assertEquals("Removal not persisted", 1, reloaded.getReporter().getContactMechanisms()
.size());
}
public void testUpdateContactMechanism() throws Exception {
{
ExpeditedAdverseEventReport report = getDao().getById(-1);
assertEquals(2, report.getReporter().getContactMechanisms().size());
report.getReporter().getContactMechanisms().put("e-mail", "clipper@yankee.com");
getDao().save(report);
}
interruptSession();
ExpeditedAdverseEventReport reloaded = getDao().getById(-1);
assertEquals("Wrong number of mechanisms after reload", 2, reloaded.getReporter()
.getContactMechanisms().size());
assertEquals("Change not persisted", "clipper@yankee.com", reloaded.getReporter()
.getContactMechanisms().get("e-mail"));
}
public void testSaveNewAdditionalInformation() throws Exception {
doSaveTest(new SaveTester() {
public void setupReport(ExpeditedAdverseEventReport report) {
report.getAdditionalInformation().setConsults(Boolean.TRUE);
}
public void assertCorrect(ExpeditedAdverseEventReport loaded) {
assertEquals(Boolean.TRUE, loaded.getAdditionalInformation().getConsults());
}
});
}
public void testSaveNewMedicalDevice() throws Exception {
doSaveTest(new SaveTester() {
public void setupReport(ExpeditedAdverseEventReport report) {
report.getMedicalDevices().get(0).setBrandName("IBM");
}
public void assertCorrect(ExpeditedAdverseEventReport loaded) {
assertEquals("IBM", loaded.getMedicalDevices().get(0).getBrandName());
}
});
}
public void testSaveNewRadiationIntervention() throws Exception {
doSaveTest(new SaveTester() {
public void setupReport(ExpeditedAdverseEventReport report) {
report.getRadiationInterventions().get(0).setDaysElapsed("120");
}
public void assertCorrect(ExpeditedAdverseEventReport loaded) {
assertEquals("120", loaded.getRadiationInterventions().get(0).getDaysElapsed());
}
});
}
public void testSaveNewSurgeryIntervention() throws Exception {
doSaveTest(new SaveTester() {
public void setupReport(ExpeditedAdverseEventReport report) {
report.getSurgeryInterventions().get(0).setInterventionSite(
interventionSiteDao.getById(-33));
}
public void assertCorrect(ExpeditedAdverseEventReport loaded) {
assertEquals(-33, (int) loaded.getSurgeryInterventions().get(0)
.getInterventionSite().getId());
}
});
}
public void testSaveSkipsPhysicianWhenNotSavable() throws Exception {
doSaveTest(new SaveTester() {
public void setupReport(ExpeditedAdverseEventReport report) {
report.getPhysician().setLastName(null);
}
public void assertCorrect(ExpeditedAdverseEventReport loaded) {
assertNull(loaded.getPhysician());
}
});
}
public void testSaveSkipsReporterWhenNotSavable() throws Exception {
doSaveTest(new SaveTester() {
public void setupReport(ExpeditedAdverseEventReport report) {
report.getReporter().setFirstName(null);
}
public void assertCorrect(ExpeditedAdverseEventReport loaded) {
assertNull(loaded.getReporter());
}
});
}
public void testSaveWhenDetached(){
ExpeditedAdverseEventReport report = getDao().getById(-1);
interruptSession();
getDao().save(report);
}
public void testSaveSavesReporterWhenSavable() throws Exception {
doSaveTest(new SaveTester() {
private static final String FIRST_NAME = "Joe";
private static final String LAST_NAME = "Arimathea";
private static final String ADDRESS = "joe@arimatheaonline.net";
private static final String PHONE = "312-HY-GRAIL";
public void setupReport(ExpeditedAdverseEventReport report) {
report.getReporter().setFirstName(FIRST_NAME);
report.getReporter().setLastName(LAST_NAME);
report.getReporter().getContactMechanisms().put(ReportPerson.EMAIL, ADDRESS);
report.getReporter().getContactMechanisms().put(ReportPerson.PHONE, PHONE);
}
public void assertCorrect(ExpeditedAdverseEventReport loaded) {
assertEquals(FIRST_NAME, loaded.getReporter().getFirstName());
assertEquals(LAST_NAME, loaded.getReporter().getLastName());
assertEquals(ADDRESS, loaded.getReporter().getContactMechanisms().get(
ReportPerson.EMAIL));
assertEquals(PHONE, loaded.getReporter().getContactMechanisms().get(
ReportPerson.PHONE));
}
});
}
public void testSaveSavesPhysicianWhenSavable() throws Exception {
doSaveTest(new SaveTester() {
private static final String FIRST_NAME = "Henry";
private static final String LAST_NAME = "Jones";
private static final String ADDRESS = "jonessr@indianaonline.net";
private static final String PHONE = "773-LOST-BOK";
public void setupReport(ExpeditedAdverseEventReport report) {
report.getPhysician().setFirstName(FIRST_NAME);
report.getPhysician().setLastName(LAST_NAME);
report.getPhysician().getContactMechanisms().put(ReportPerson.EMAIL, ADDRESS);
report.getPhysician().getContactMechanisms().put(ReportPerson.PHONE, PHONE);
}
public void assertCorrect(ExpeditedAdverseEventReport loaded) {
assertEquals(FIRST_NAME, loaded.getPhysician().getFirstName());
assertEquals(LAST_NAME, loaded.getPhysician().getLastName());
assertEquals(ADDRESS, loaded.getPhysician().getContactMechanisms().get(
ReportPerson.EMAIL));
assertEquals(PHONE, loaded.getPhysician().getContactMechanisms().get(
ReportPerson.PHONE));
}
});
}
// public void testSaveSavesSubmittableReports() throws Exception {
// doSaveTest(new SaveTester() {
// public void setupReport(ExpeditedAdverseEventReport report) {
// Report submittable = new Report();
// submittable.setDueOn(new Date());
// submittable.setCreatedOn(new Date());
// // submittable.setName("What is this field for?");
// submittable.setReportDefinition(reportDefinitionDao.getById(-30));
// report.addReport(submittable);
// }
//
// public void assertCorrect(ExpeditedAdverseEventReport loaded) {
// assertEquals("Report not saved", 1, loaded.getReports().size());
// assertEquals("Report has wrong definition",
// -30, (int) loaded.getReports().get(0).getReportDefinition().getId());
// }
// });
// }
public void testDeleteOrphanAdverseEvent() throws Exception {
{
ExpeditedAdverseEventReport loaded = getDao().getById(-1);
assertEquals("Wrong number of AEs initially", 2, loaded.getAdverseEvents().size());
assertEquals("Wrong initial AE 0", -70, (int) loaded.getAdverseEvents().get(0).getId());
assertEquals("Wrong initial AE 1", -11, (int) loaded.getAdverseEvents().get(1).getId());
loaded.getAdverseEvents().remove(0);
getDao().save(loaded);
}
interruptSession();
ExpeditedAdverseEventReport reloaded = getDao().getById(-1);
assertEquals("Wrong number of AEs when reloaded", 1, reloaded.getAdverseEvents().size());
assertEquals("Wrong AE when reloaded", -11, (int) reloaded.getAdverseEvents().get(0)
.getId());
}
public void testDeleteMetastaticDiseaseSiteDoesNotDeleteAnatomicSite() throws Exception {
{
ExpeditedAdverseEventReport loaded = getDao().getById(-1);
assertEquals("Data not as initially expected", 1, loaded.getDiseaseHistory()
.getMetastaticDiseaseSites().size());
assertEquals("Data not as initially expected", -33, (int) loaded.getDiseaseHistory()
.getMetastaticDiseaseSites().get(0).getCodedSite().getId());
loaded.getDiseaseHistory().getMetastaticDiseaseSites().remove(0);
getDao().save(loaded);
}
interruptSession();
ExpeditedAdverseEventReport reloaded = getDao().getById(-1);
assertEquals("Metastatic site not removed", 0, reloaded.getDiseaseHistory()
.getMetastaticDiseaseSites().size());
assertNotNull("Anatomic site deleted", anatomicSiteDao.getById(-33));
}
public void testSearchExpeditedReportByCtcTermPartial() throws Exception {
List<ExpeditedAdverseEventReport> results;
Map<String, String> m = new HashMap<String, String>();
m.put("ctcTerm", "Auditory/Ear");
results = getDao().searchExpeditedReports(m);
assertEquals("Wrong number of results", 1, results.size());
}
public void testSearchExpeditedReportByParticipant() throws Exception {
List<ExpeditedAdverseEventReport> results;
Map<String, String> m = new HashMap<String, String>();
m.put("participantFirstName", "Michael");
m.put("participantLastName", "Jordan");
m.put("participantEthnicity", "ethnicity");
m.put("participantGender", "Male");
m.put("participantDateOfBirth","01/02/2006");
m.put("participantIdentifier", "13js77");
results = getDao().searchExpeditedReports(m);
assertEquals("Wrong number of results", 1, results.size());
}
public void testSearchExpeditedReportByStudy() throws Exception {
List<ExpeditedAdverseEventReport> results;
Map<String, String> m = new HashMap<String, String>();
m.put("studyShortTitle", "That");
m.put("studyIdentifier", "nci_test");
results = getDao().searchExpeditedReports(m);
assertEquals("Wrong number of results", 1, results.size());
}
//10043882
public void testSearchExpeditedReportByCtepCodeAndCategory() throws Exception {
List<ExpeditedAdverseEventReport> results;
Map<String, String> m = new HashMap<String, String>();
m.put("ctcCtepCode", "10043882");
m.put("ctcCategory", "auditory/ear");
results = getDao().searchExpeditedReports(m);
assertEquals("Wrong number of results", 1, results.size());
}
public void testSerializeExpeditedAdverseEventReport() throws Exception {
ExpeditedAdverseEventReport aer = getDao().getById(-1);
AdverseEventReportSerializer aeser = (AdverseEventReportSerializer) getApplicationContext()
.getBean("adverseEventReportSerializer");
String xml = aeser.serialize(aer, null);
assertNotNull(xml);
//assertEquals(xml,getStringFromFile());
}
public void testHasSubmittedReport(){
ExpeditedAdverseEventReport loaded = getDao().getById(-1);
assertFalse(loaded.getHasSubmittedAmendableReport());
}
private void doSaveTest(SaveTester tester) {
Integer savedId;
{
ExpeditedAdverseEventReport report = createMinimalAeReport();
tester.setupReport(report);
getDao().save(report);
assertNotNull("No ID for new report", report.getId());
savedId = report.getId();
}
interruptSession();
{
ExpeditedAdverseEventReport loaded = getDao().getById(savedId);
assertNotNull("Saved report not found", loaded);
tester.assertCorrect(loaded);
}
}
private ExpeditedAdverseEventReport createMinimalAeReport() {
ExpeditedAdverseEventReport report = Fixtures.createSavableExpeditedReport();
report.setReportingPeriod(reportingPeriodDao.getById(-14));
report.getAdverseEvents().get(0).setAdverseEventCtcTerm(
Fixtures.createAdverseEventCtcTerm(report.getAdverseEvents().get(0),
ctcTermDao.getById(3012)));
return report;
}
private static interface SaveTester {
void setupReport(ExpeditedAdverseEventReport report);
void assertCorrect(ExpeditedAdverseEventReport loaded);
}
public void testGetByCriteria(){
List<ExpeditedAdverseEventReport> reports = getDao().getByCriteria(null, null);
assertTrue(reports.isEmpty());
}
public void testReassociate(){
ExpeditedAdverseEventReport report = getDao().getById(-1);
interruptSession();
try{
report.getTreatmentInformation().getCourseAgentsInternal().size();
fail("should throw lazy exception");
}catch(Exception e){
}
getDao().reassociate(report);
assertEquals(2,report.getTreatmentInformation().getCourseAgentsInternal().size());
}
public void testDeleteAttribution(){
RadiationAttribution rAttribution1 = new RadiationAttribution();
RadiationIntervention cause = new RadiationIntervention();
cause.setId(5);
rAttribution1.setCause(cause);
RadiationAttribution rAttribution2 = new RadiationAttribution();
RadiationIntervention cause2 = new RadiationIntervention();
cause2.setId(6);
rAttribution2.setCause(cause2);
List<RadiationAttribution> list = new ArrayList<RadiationAttribution>();
list.add(rAttribution1);
list.add(rAttribution2);
getDao().deleteAttribution(rAttribution1.getCause(), list, null);
assertEquals(1,list.size());
}
public void testCascaeDeleteToAttributions(){
RadiationAttribution rAttribution1 = new RadiationAttribution();
RadiationIntervention cause = new RadiationIntervention();
cause.setId(5);
rAttribution1.setCause(cause);
RadiationAttribution rAttribution2 = new RadiationAttribution();
RadiationIntervention cause2 = new RadiationIntervention();
cause2.setId(6);
rAttribution2.setCause(cause2);
List<RadiationAttribution> list = new ArrayList<RadiationAttribution>();
list.add(rAttribution1);
list.add(rAttribution2);
ExpeditedAdverseEventReport aeReport = Fixtures.createSavableExpeditedReport();
aeReport.getAdverseEvents().get(0).setRadiationAttributions(list);
boolean returnVal = getDao().cascaeDeleteToAttributions(cause2, aeReport);
assertTrue(returnVal);
assertEquals(1, list.size());
}
public void testCascadeDeleteToAttributions_DiseaseAttribution(){
DiseaseAttribution d1 = new DiseaseAttribution();
DiseaseHistory dh1 = new DiseaseHistory();
dh1.setId(4);
d1.setCause(dh1);
DiseaseAttribution d2 = new DiseaseAttribution();
DiseaseHistory dh2 = new DiseaseHistory();
dh2.setId(5);
d2.setCause(dh2);
List<DiseaseAttribution> list = new ArrayList<DiseaseAttribution>();
list.add(d1);
list.add(d2);
ExpeditedAdverseEventReport aeReport = Fixtures.createSavableExpeditedReport();
aeReport.getAdverseEvents().get(0).setDiseaseAttributions(list);
boolean returnVal = getDao().cascaeDeleteToAttributions(dh2, aeReport);
assertTrue(returnVal);
assertEquals(1, list.size());
}
public void testCascadeDeleteToAtrributions_CourseAgentAttribution(){
ExpeditedAdverseEventReport aeReport = Fixtures.createSavableExpeditedReport();
List<CourseAgentAttribution> list = new ArrayList<CourseAgentAttribution>();
aeReport.getAdverseEvents().get(0).setCourseAgentAttributions(list);
CourseAgentAttribution a1 = new CourseAgentAttribution();
CourseAgent c1 = new CourseAgent();
CourseAgentAttribution a2 = new CourseAgentAttribution();
CourseAgent c2 = new CourseAgent();
c1.setId(3);
c2.setId(4);
a1.setCause(c1);
a2.setCause(c2);
list.add(a1);
list.add(a2);
boolean returnVal = getDao().cascaeDeleteToAttributions(c1, aeReport);
assertTrue(returnVal);
assertEquals(1, list.size());
}
public void testCascadeDeleteToAtrributions_OtherCauseAttribution(){
ExpeditedAdverseEventReport aeReport = Fixtures.createSavableExpeditedReport();
List<OtherCauseAttribution> list = new ArrayList<OtherCauseAttribution>();
aeReport.getAdverseEvents().get(0).setOtherCauseAttributions(list);
OtherCauseAttribution a1 = new OtherCauseAttribution();
OtherCause c1 = new OtherCause();
OtherCauseAttribution a2 = new OtherCauseAttribution();
OtherCause c2 = new OtherCause();
c1.setId(3);
c2.setId(4);
a1.setCause(c1);
a2.setCause(c2);
list.add(a1);
list.add(a2);
boolean returnVal = getDao().cascaeDeleteToAttributions(c1, aeReport);
assertTrue(returnVal);
assertEquals(1, list.size());
}
public void testCascadeDeleteToAtrributions_ConcomitantMedicationAttribution(){
ExpeditedAdverseEventReport aeReport = Fixtures.createSavableExpeditedReport();
List<ConcomitantMedicationAttribution> list = new ArrayList<ConcomitantMedicationAttribution>();
aeReport.getAdverseEvents().get(0).setConcomitantMedicationAttributions(list);
ConcomitantMedicationAttribution a1 = new ConcomitantMedicationAttribution();
ConcomitantMedication c1 = new ConcomitantMedication();
ConcomitantMedicationAttribution a2 = new ConcomitantMedicationAttribution();
ConcomitantMedication c2 = new ConcomitantMedication();
c1.setId(3);
c2.setId(4);
a1.setCause(c1);
a2.setCause(c2);
list.add(a1);
list.add(a2);
boolean returnVal = getDao().cascaeDeleteToAttributions(c1, aeReport);
assertTrue(returnVal);
assertEquals(1, list.size());
}
public void testCascadeDeleteToAtrributions_MedicalDeviceAttribution(){
ExpeditedAdverseEventReport aeReport = Fixtures.createSavableExpeditedReport();
List<DeviceAttribution> list = new ArrayList<DeviceAttribution>();
aeReport.getAdverseEvents().get(0).setDeviceAttributions(list);
DeviceAttribution a1 = new DeviceAttribution();
MedicalDevice c1 = new MedicalDevice();
DeviceAttribution a2 = new DeviceAttribution();
MedicalDevice c2 = new MedicalDevice();
c1.setId(3);
c2.setId(4);
a1.setCause(c1);
a2.setCause(c2);
list.add(a1);
list.add(a2);
boolean returnVal = getDao().cascaeDeleteToAttributions(c1, aeReport);
assertTrue(returnVal);
assertEquals(1, list.size());
}
public void testCascadeDeleteToAtrributions_SurgeryAttribution(){
ExpeditedAdverseEventReport aeReport = Fixtures.createSavableExpeditedReport();
List<SurgeryAttribution> list = new ArrayList<SurgeryAttribution>();
aeReport.getAdverseEvents().get(0).setSurgeryAttributions(list);
SurgeryAttribution a1 = new SurgeryAttribution();
SurgeryIntervention c1 = new SurgeryIntervention();
SurgeryAttribution a2 = new SurgeryAttribution();
SurgeryIntervention c2 = new SurgeryIntervention();
c1.setId(3);
c2.setId(4);
a1.setCause(c1);
a2.setCause(c2);
list.add(a1);
list.add(a2);
boolean returnVal = getDao().cascaeDeleteToAttributions(c1, aeReport);
assertTrue(returnVal);
assertEquals(1, list.size());
}
public void testSaveReviewComments() throws Exception {
final Date today = new Date();
ExpeditedAdverseEventReport loaded = getDao().getById(-1);
ReportReviewComment reviewComment = new ReportReviewComment();
reviewComment.setCreatedDate(new Date());
reviewComment.setAutoGeneratedText("Added by " );
reviewComment.setUserComment("abcd");
reviewComment.setEditable(true);
reviewComment.setUserId("5");
loaded.getReviewComments().add(reviewComment);
getDao().modifyOrSaveReviewStatusAndComments(loaded);
loaded = getDao().getById(-1);
assertEquals("abcd", loaded.getReviewComments().get(0).getUserComment());
}
private String getStringFromFile() throws Exception {
File testFile = new ClassPathResource("/gov/nih/nci/cabig/caaers/dao/testdata/ExpeditedAdverseEventReportString.txt").getFile();
BufferedReader bufRead = new BufferedReader(new FileReader(testFile));
String line = bufRead.readLine();
String str1 = "";
while (line != null) {
str1 = str1 + line;
line = bufRead.readLine();
}
return str1;
}
}
| caAERS/software/core/src/test/java/gov/nih/nci/cabig/caaers/dao/ExpeditedAdverseEventReportDaoTest.java | package gov.nih.nci.cabig.caaers.dao;
import static edu.nwu.bioinformatics.commons.testing.CoreTestCase.assertDayOfDate;
import static edu.nwu.bioinformatics.commons.testing.CoreTestCase.prependMessage;
import static gov.nih.nci.cabig.caaers.CaaersUseCase.CREATE_EXPEDITED_REPORT;
import edu.nwu.bioinformatics.commons.DateUtils;
import edu.nwu.bioinformatics.commons.testing.CoreTestCase;
import gov.nih.nci.cabig.caaers.CaaersUseCases;
import gov.nih.nci.cabig.caaers.DaoNoSecurityTestCase;
import gov.nih.nci.cabig.caaers.api.AdverseEventReportSerializer;
import gov.nih.nci.cabig.caaers.dao.report.ReportDefinitionDao;
import gov.nih.nci.cabig.caaers.domain.AdverseEvent;
import gov.nih.nci.cabig.caaers.domain.AdverseEventResponseDescription;
import gov.nih.nci.cabig.caaers.domain.Attribution;
import gov.nih.nci.cabig.caaers.domain.ConcomitantMedication;
import gov.nih.nci.cabig.caaers.domain.CourseAgent;
import gov.nih.nci.cabig.caaers.domain.CtcTerm;
import gov.nih.nci.cabig.caaers.domain.DelayUnits;
import gov.nih.nci.cabig.caaers.domain.DiseaseHistory;
import gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport;
import gov.nih.nci.cabig.caaers.domain.Fixtures;
import gov.nih.nci.cabig.caaers.domain.Grade;
import gov.nih.nci.cabig.caaers.domain.Hospitalization;
import gov.nih.nci.cabig.caaers.domain.Lab;
import gov.nih.nci.cabig.caaers.domain.LabValue;
import gov.nih.nci.cabig.caaers.domain.MedicalDevice;
import gov.nih.nci.cabig.caaers.domain.OtherCause;
import gov.nih.nci.cabig.caaers.domain.ParticipantHistory;
import gov.nih.nci.cabig.caaers.domain.Physician;
import gov.nih.nci.cabig.caaers.domain.PostAdverseEventStatus;
import gov.nih.nci.cabig.caaers.domain.RadiationIntervention;
import gov.nih.nci.cabig.caaers.domain.ReportPerson;
import gov.nih.nci.cabig.caaers.domain.Reporter;
import gov.nih.nci.cabig.caaers.domain.SurgeryIntervention;
import gov.nih.nci.cabig.caaers.domain.TreatmentInformation;
import gov.nih.nci.cabig.caaers.domain.attribution.ConcomitantMedicationAttribution;
import gov.nih.nci.cabig.caaers.domain.attribution.CourseAgentAttribution;
import gov.nih.nci.cabig.caaers.domain.attribution.DeviceAttribution;
import gov.nih.nci.cabig.caaers.domain.attribution.DiseaseAttribution;
import gov.nih.nci.cabig.caaers.domain.attribution.OtherCauseAttribution;
import gov.nih.nci.cabig.caaers.domain.attribution.RadiationAttribution;
import gov.nih.nci.cabig.caaers.domain.attribution.SurgeryAttribution;
import gov.nih.nci.cabig.caaers.domain.report.Report;
import gov.nih.nci.cabig.caaers.domain.workflow.ReportReviewComment;
import gov.nih.nci.cabig.ctms.lang.DateTools;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.core.io.ClassPathResource;
/**
* @author Rhett Sutphin
*/
@CaaersUseCases( { CREATE_EXPEDITED_REPORT })
public class ExpeditedAdverseEventReportDaoTest extends DaoNoSecurityTestCase<ExpeditedAdverseEventReportDao> {
private CtcTermDao ctcTermDao = (CtcTermDao) getApplicationContext().getBean("ctcTermDao");
private AnatomicSiteDao anatomicSiteDao = (AnatomicSiteDao) getApplicationContext().getBean(
"anatomicSiteDao");
private InterventionSiteDao interventionSiteDao = (InterventionSiteDao) getApplicationContext()
.getBean("interventionSiteDao");
private ReportDefinitionDao reportDefinitionDao = (ReportDefinitionDao) getApplicationContext()
.getBean("reportDefinitionDao");
private AdverseEventReportingPeriodDao reportingPeriodDao = (AdverseEventReportingPeriodDao) getApplicationContext().getBean("adverseEventReportingPeriodDao");
public void testGet() throws Exception {
ExpeditedAdverseEventReport loaded = getDao().getById(-1);
assertEquals("Wrong AE 0", -70, (int) loaded.getAdverseEvents().get(0).getId());
assertEquals("Wrong AE 1", -11, (int) loaded.getAdverseEvents().get(1).getId());
assertEquals("Wrong assignment", -14, (int) loaded.getReportingPeriod().getAssignment().getId());
CoreTestCase.assertDayOfDate("Wrong created at (date)", 2004, Calendar.SEPTEMBER, 4, loaded
.getCreatedAt());
CoreTestCase.assertTimeOfDate("Wrong created at (time)", 13, 15, 30, 0, loaded
.getCreatedAt());
}
public void testGetLabs() throws Exception {
ExpeditedAdverseEventReport loaded = getDao().getById(-1);
assertEquals("Wrong number of labs", 3, loaded.getLabs().size());
assertEquals("Wrong lab 0", -21, (int) loaded.getLabs().get(0).getId());
assertEquals("Wrong lab 1", -20, (int) loaded.getLabs().get(1).getId());
assertEquals("Wrong lab 2", -22, (int) loaded.getLabs().get(2).getId());
Lab l1 = loaded.getLabs().get(1);
assertSame("Wrong report", loaded, l1.getReport());
assertEquals("Wrong units", "hectares/liter", l1.getUnits());
assertLabValue("Wrong baseline", "3.66", 2003, Calendar.APRIL, 17, l1.getBaseline());
assertLabValue("Wrong nadir", "0.4", 2007, Calendar.MARCH, 14, l1.getNadir());
assertLabValue("Wrong nadir", "3.54", 2007, Calendar.MARCH, 19, l1.getRecovery());
}
private static void assertLabValue(String message, String expectedValue, int expectedYear,
int expectedMonth, int expectedDay, LabValue actual) {
assertDayOfDate(prependMessage(message) + "wrong date", expectedYear, expectedMonth,
expectedDay, actual.getDate());
assertEquals(prependMessage(message) + "wrong value", expectedValue, actual.getValue());
}
public void testGetConcomitantMedications() throws Exception {
ExpeditedAdverseEventReport loaded = getDao().getById(-1);
assertEquals("Wrong number of concomitant meds", 2, loaded.getConcomitantMedications()
.size());
assertEquals("Wrong con med 0", -31, (int) loaded.getConcomitantMedications().get(0)
.getId());
assertEquals("Wrong con med 1", -30, (int) loaded.getConcomitantMedications().get(1)
.getId());
ConcomitantMedication cm1 = loaded.getConcomitantMedications().get(1);
assertSame("Wrong report", loaded, cm1.getReport());
assertNull("Wrong agent name", cm1.getAgentName());
}
public void testGetTreatmentInformation() throws Exception {
ExpeditedAdverseEventReport loaded = getDao().getById(-1);
assertNotNull("No treatment info", loaded.getTreatmentInformation());
TreatmentInformation actual = loaded.getTreatmentInformation();
assertEquals("Wrong treatment information", -10, (int) actual.getId());
assertDayOfDate("Wrong first course date", 2005, Calendar.JUNE, 4, actual
.getFirstCourseDate());
assertDayOfDate("Wrong adverse event course date", 2006, Calendar.JULY, 9, actual
.getAdverseEventCourse().getDate());
assertEquals("Wrong adverse event course number", 8, (int) actual.getAdverseEventCourse()
.getNumber());
assertEquals("Wrong number of course agents", 2, actual.getCourseAgents().size());
assertEquals("Wrong course agent 0", -19, (int) actual.getCourseAgents().get(0).getId());
assertNotNull("Worng association to TreatmentAssignment", actual.getTreatmentAssignment());
assertEquals("Wrong treatmentAssignment code", "TAC010", actual.getTreatmentAssignment()
.getCode());
CourseAgent agent1 = actual.getCourseAgents().get(1);
assertEquals("Wrong course agent 1", -20, (int) agent1.getId());
assertEquals("Wrong delay in minutes", new BigDecimal(240), agent1.getAdministrationDelay());
assertEquals("Wrong delay amount", new BigDecimal(4), agent1.getAdministrationDelayAmount());
assertEquals("Wrong delay units", DelayUnits.HOURS, agent1.getAdministrationDelayUnits());
assertEquals("Wrong dose amount", "17.4", agent1.getDose().getAmount());
assertEquals("Wrong dose units", "mg", agent1.getDose().getUnits());
assertEquals("Wrong dose route", "aural", agent1.getDose().getRoute());
assertEquals("Wrong duration", "8 times every third hour", agent1.getDurationAndSchedule());
assertEquals("Wrong total dose", new BigDecimal("7"), agent1
.getTotalDoseAdministeredThisCourse());
assertDayOfDate("Wrong last administered date", 2006, Calendar.JULY, 10, agent1
.getLastAdministeredDate());
}
public void testGetOtherCauses() throws Exception {
ExpeditedAdverseEventReport loaded = getDao().getById(-1);
assertEquals("Wrong number of causes", 3, loaded.getOtherCauses().size());
assertEquals("Wrong cause 0", -81, (int) loaded.getOtherCauses().get(0).getId());
assertEquals("Wrong cause 1", -80, (int) loaded.getOtherCauses().get(1).getId());
assertEquals("Wrong cause 2", -82, (int) loaded.getOtherCauses().get(2).getId());
assertEquals("Wrong text for cause 1", "Crossed against light", loaded.getOtherCauses()
.get(1).getText());
}
public void testGetResponseDescription() throws Exception {
AdverseEventResponseDescription actual = getDao().getById(-1).getResponseDescription();
assertEquals("Wrong present status", PostAdverseEventStatus.RECOVERED_WITH_SEQUELAE, actual
.getPresentStatus());
assertEquals("Wrong event description", "It was real bad", actual.getEventDescription());
assertEquals("Wrong retreated flag", Boolean.FALSE, actual.getRetreated());
assertDayOfDate("Wrong date removed", 2012, Calendar.MARCH, 4, actual.getRecoveryDate());
}
public void testGetReports() throws Exception {
List<Report> actual = getDao().getById(-1).getReports();
assertNotNull(actual);
assertEquals("Wrong number of reports", 2, actual.size());
assertEquals("Wrong report 0", -40, (int) actual.get(1).getId());
Report actualReport1 = actual.get(0);
assertNotNull(actualReport1);
assertEquals("Wrong report 1", -41, (int) actualReport1.getId());
assertEquals("Wrong def for report 1", -30, (int) actualReport1.getReportDefinition()
.getId());
}
public void testGetReporter() throws Exception {
Reporter actual = getDao().getById(-1).getReporter();
assertNotNull("No reporter", actual);
assertEquals("Wrong reporter", -100, (int) actual.getId());
assertEquals("DiMaggio", actual.getLastName());
assertEquals("Wrong number of contact mechanisms", 2, actual.getContactMechanisms().size());
assertEquals("joltin@joe.com", actual.getContactMechanisms().get(ReportPerson.EMAIL));
assertEquals("212 555-1212", actual.getContactMechanisms().get(ReportPerson.PHONE));
}
public void testGetPhysician() throws Exception {
Physician actual = getDao().getById(-1).getPhysician();
assertNotNull("No physician", actual);
assertEquals("Wrong reporter", -101, (int) actual.getId());
assertEquals("Sandpiper", actual.getLastName());
assertEquals("Wrong number of contact mechanisms", 0, actual.getContactMechanisms().size());
}
public void testGetDiseaseHistory() throws Exception {
DiseaseHistory actual = getDao().getById(-1).getDiseaseHistory();
assertNotNull("No disease history", actual);
assertEquals("Wrong history", -53, (int) actual.getId());
assertEquals("Wrong primary disease site", -1, (int) actual.getCodedPrimaryDiseaseSite()
.getId());
assertEquals("Wrong diagnosis date.DAY", new Integer(4), actual.getDiagnosisDate().getDay());
assertEquals("Wrong diagnosis date.Month", new Integer(1), actual.getDiagnosisDate().getMonth());
assertEquals("Wrong diagnosis date.Year", new Integer(2007), actual.getDiagnosisDate().getYear());
assertEquals("Wrong number of metastatic disease sites", 1, actual
.getMetastaticDiseaseSites().size());
assertEquals("Wrong metastatic disease site", -5, (int) actual.getMetastaticDiseaseSites()
.get(0).getId());
assertTrue(true);
}
public void testGetParticipantHistory() throws Exception {
ParticipantHistory actual = getDao().getById(-1).getParticipantHistory();
assertNotNull("No participant history", actual);
assertEquals("Wrong history", -57, (int) actual.getId());
assertEquals("Wrong height", new BigDecimal("134.3"), actual.getHeight().getQuantity());
assertEquals("Wrong height unit", "cm", actual.getHeight().getUnit());
assertEquals("Wrong weight", new BigDecimal("54.2"), actual.getWeight().getQuantity());
assertEquals("Wrong weight unit", "kg", actual.getWeight().getUnit());
assertEquals("Wrong baseline", "About here", actual.getBaselinePerformanceStatus());
}
public void testSaveBasics() throws Exception {
doSaveTest(new SaveTester() {
public void setupReport(ExpeditedAdverseEventReport report) {
CtcTerm term = ctcTermDao.getById(3012);
AdverseEvent event0 = new AdverseEvent();
event0.setGrade(Grade.MILD);
event0.setAdverseEventCtcTerm(Fixtures.createAdverseEventCtcTerm(event0, term));
event0.setExpected(Boolean.FALSE);
event0.setHospitalization(Hospitalization.NO);
event0.setStartDate(new Timestamp(DateUtils.createDate(2004, Calendar.APRIL, 25)
.getTime() + 600000));
report.getReportingPeriod().addAdverseEvent(event0);
AdverseEvent event1 = new AdverseEvent();
event1.setGrade(Grade.SEVERE);
event1.setAdverseEventCtcTerm(Fixtures.createAdverseEventCtcTerm(event0, term));
event1.setExpected(Boolean.FALSE);
event1.setHospitalization(Hospitalization.YES);
report.getReportingPeriod().addAdverseEvent(event1);
report.getAdverseEvents().clear();
report.addAdverseEvent(event0);
report.addAdverseEvent(event1);
}
public void assertCorrect(ExpeditedAdverseEventReport loaded) {
assertEquals("Wrong assignment", -14, (int) loaded.getAssignment().getId());
assertEquals("Wrong number of AEs", 2, loaded.getAdverseEvents().size());
AdverseEvent loadedEvent0 = loaded.getAdverseEvents().get(0);
assertNotNull("Cascaded AE not found", loadedEvent0);
assertEquals("Wrong grade", Grade.MILD, loadedEvent0.getGrade());
assertEquals("Wrong CTC term", 3012, (int) loadedEvent0.getAdverseEventCtcTerm()
.getCtcTerm().getId());
assertNotNull("No report", loadedEvent0.getReport());
assertEquals("Wrong hospitalization", Hospitalization.NO,
loadedEvent0.getHospitalization());
assertEquals("Wrong expectedness", Boolean.FALSE, loadedEvent0.getExpected());
assertNotNull("Second cascaded AE not found", loaded.getAdverseEvents().get(1));
}
});
}
public void testSaveBasicsWithReordering() throws Exception {
Integer reportId = null;
{
ExpeditedAdverseEventReport report = createMinimalAeReport();
CtcTerm term = ctcTermDao.getById(3012);
AdverseEvent event0 = new AdverseEvent();
event0.setGrade(Grade.MILD);
event0.setAdverseEventCtcTerm(Fixtures.createAdverseEventCtcTerm(event0, term));
event0.setExpected(Boolean.FALSE);
event0.setHospitalization(Hospitalization.NO);
event0.setStartDate(new Timestamp(DateUtils.createDate(2004, Calendar.APRIL, 25)
.getTime() + 600000));
report.getReportingPeriod().addAdverseEvent(event0);
AdverseEvent event1 = new AdverseEvent();
event1.setGrade(Grade.SEVERE);
event1.setAdverseEventCtcTerm(Fixtures.createAdverseEventCtcTerm(event1, term));
event1.setExpected(Boolean.FALSE);
event1.setHospitalization(Hospitalization.YES);
report.getReportingPeriod().addAdverseEvent(event1);
AdverseEvent event2 = new AdverseEvent();
event2.setGrade(Grade.DEATH);
event2.setAdverseEventCtcTerm(Fixtures.createAdverseEventCtcTerm(event2, term));
event2.setExpected(Boolean.FALSE);
event2.setHospitalization(Hospitalization.YES);
report.getReportingPeriod().addAdverseEvent(event2);
report.getAdverseEvents().clear();
report.addAdverseEvent(event0);
report.addAdverseEvent(event1);
report.addAdverseEvent(event2);
getDao().save(report);
reportId = report.getId();
assertNotNull(reportId);
}
interruptSession();
{
ExpeditedAdverseEventReport loaded = getDao().getById(reportId);
assertNotNull(loaded);
assertEquals("Wrong number of AEs", 3, loaded.getAdverseEvents().size());
AdverseEvent loadedEvent0 = loaded.getAdverseEvents().get(0);
assertNotNull("Cascaded AE not found", loadedEvent0);
assertEquals("Wrong grade", Grade.MILD, loadedEvent0.getGrade());
assertNotNull("Second cascaded AE not found", loaded.getAdverseEvents().get(1));
assertEquals("Wrong grade", Grade.SEVERE, loaded.getAdverseEvents().get(1).getGrade());
assertNotNull("Third cascaded AE not found", loaded.getAdverseEvents().get(2));
assertEquals("Wrong grade", Grade.DEATH, loaded.getAdverseEvents().get(2).getGrade());
//reorder
loaded.getAdverseEvents().remove(loadedEvent0);
loaded.getAdverseEvents().add(1, loadedEvent0);
getDao().save(loaded);
}
interruptSession();
{
ExpeditedAdverseEventReport loaded = getDao().getById(reportId);
assertNotNull(loaded);
assertEquals("Wrong number of AEs", 3, loaded.getAdverseEvents().size());
AdverseEvent loadedEvent0 = loaded.getAdverseEvents().get(0);
assertNotNull("Cascaded AE not found", loadedEvent0);
assertEquals("Wrong grade", Grade.SEVERE, loadedEvent0.getGrade());
assertNotNull("Second cascaded AE not found", loaded.getAdverseEvents().get(1));
assertEquals("Wrong grade", Grade.MILD, loaded.getAdverseEvents().get(1).getGrade());
assertNotNull("Third cascaded AE not found", loaded.getAdverseEvents().get(2));
assertEquals("Wrong grade", Grade.DEATH, loaded.getAdverseEvents().get(2).getGrade());
}
}
public void testSaveNewReportWithConMedWithAttribution() throws Exception {
doSaveTest(new SaveTester() {
public void setupReport(ExpeditedAdverseEventReport report) {
ConcomitantMedication conMed = report.getConcomitantMedications().get(0);
conMed.setId(-30);
conMed.setVersion(0);
conMed.setAgentName("agentName");
AdverseEvent ae0 = report.getAdverseEvents().get(0);
report.getAdverseEvents().get(0).getConcomitantMedicationAttributions().add(
new ConcomitantMedicationAttribution());
ConcomitantMedicationAttribution conMedAttrib = ae0
.getConcomitantMedicationAttributions().get(0);
conMedAttrib.setCause(conMed);
conMedAttrib.setAttribution(Attribution.PROBABLE);
}
public void assertCorrect(ExpeditedAdverseEventReport loaded) {
assertNotNull("Report not found", loaded);
assertEquals(1, loaded.getConcomitantMedications().size());
List<ConcomitantMedicationAttribution> attribs = loaded.getAdverseEvents().get(0)
.getConcomitantMedicationAttributions();
assertEquals(1, attribs.size());
assertEquals("Wrong number of con med attribs", "agentName", attribs.get(0)
.getCause().getAgentName());
}
});
}
public void testSaveNewReportWithTreatment() throws Exception {
doSaveTest(new SaveTester() {
public void setupReport(ExpeditedAdverseEventReport report) {
TreatmentInformation ti = new TreatmentInformation();
ti.getAdverseEventCourse().setDate(DateUtils.createDate(2006, Calendar.MAY, 4));
ti.getAdverseEventCourse().setNumber(4);
ti.setFirstCourseDate(DateTools.createDate(2005, Calendar.JULY, 30));
ti.getCourseAgents().get(0).setAdministrationDelay(new BigDecimal(480));
ti.getCourseAgents().get(0).getDose().setAmount("45.2");
// TODO: load the treatmentAssignment and add it, before saving.
report.setTreatmentInformation(ti);
}
public void assertCorrect(ExpeditedAdverseEventReport loaded) {
TreatmentInformation ti = loaded.getTreatmentInformation();
assertNotNull("Should have treatment info", ti);
assertDayOfDate("Wrong first course date", 2005, Calendar.JULY, 30, ti
.getFirstCourseDate());
assertEquals("Wrong AE course number", 4, (int) ti.getAdverseEventCourse()
.getNumber());
assertDayOfDate("Wrong AE course date", 2006, Calendar.MAY, 4, ti
.getAdverseEventCourse().getDate());
assertEquals("Wrong number of course agents", 1, ti.getCourseAgents().size());
CourseAgent ca = ti.getCourseAgents().get(0);
assertEquals(new BigDecimal(480), ca.getAdministrationDelay());
assertEquals("45.2", ca.getDose().getAmount());
}
});
}
public void testSaveOtherCauses() throws Exception {
doSaveTest(new SaveTester() {
public void setupReport(ExpeditedAdverseEventReport report) {
report.getOtherCauses().get(0).setText("Insomnia");
report.getOtherCauses().get(1).setText("Bus");
}
public void assertCorrect(ExpeditedAdverseEventReport loaded) {
assertEquals("Wrong number of other causes", 2, loaded.getOtherCauses().size());
assertEquals("Wrong cause 0", "Insomnia", loaded.getOtherCauses().get(0).getText());
assertEquals("Wrong cause 1", "Bus", loaded.getOtherCauses().get(1).getText());
}
});
}
public void testSaveNewContactMechanisms() throws Exception {
doSaveTest(new SaveTester() {
public void setupReport(ExpeditedAdverseEventReport report) {
report.getPhysician().getContactMechanisms().put("phone", "312-333-2100");
}
public void assertCorrect(ExpeditedAdverseEventReport loaded) {
assertEquals(2, loaded.getPhysician().getContactMechanisms().size());
assertEquals("312-333-2100", loaded.getPhysician().getContactMechanisms().get(
"phone"));
}
});
}
public void testDeleteContactMechanism() throws Exception {
{
ExpeditedAdverseEventReport report = getDao().getById(-1);
assertEquals(2, report.getReporter().getContactMechanisms().size());
report.getReporter().getContactMechanisms().remove("e-mail");
assertEquals("Not removed from memory copy", 1, report.getReporter()
.getContactMechanisms().size());
getDao().save(report);
}
interruptSession();
ExpeditedAdverseEventReport reloaded = getDao().getById(-1);
assertEquals("Removal not persisted", 1, reloaded.getReporter().getContactMechanisms()
.size());
}
public void testUpdateContactMechanism() throws Exception {
{
ExpeditedAdverseEventReport report = getDao().getById(-1);
assertEquals(2, report.getReporter().getContactMechanisms().size());
report.getReporter().getContactMechanisms().put("e-mail", "clipper@yankee.com");
getDao().save(report);
}
interruptSession();
ExpeditedAdverseEventReport reloaded = getDao().getById(-1);
assertEquals("Wrong number of mechanisms after reload", 2, reloaded.getReporter()
.getContactMechanisms().size());
assertEquals("Change not persisted", "clipper@yankee.com", reloaded.getReporter()
.getContactMechanisms().get("e-mail"));
}
public void testSaveNewAdditionalInformation() throws Exception {
doSaveTest(new SaveTester() {
public void setupReport(ExpeditedAdverseEventReport report) {
report.getAdditionalInformation().setConsults(Boolean.TRUE);
}
public void assertCorrect(ExpeditedAdverseEventReport loaded) {
assertEquals(Boolean.TRUE, loaded.getAdditionalInformation().getConsults());
}
});
}
public void testSaveNewMedicalDevice() throws Exception {
doSaveTest(new SaveTester() {
public void setupReport(ExpeditedAdverseEventReport report) {
report.getMedicalDevices().get(0).setBrandName("IBM");
}
public void assertCorrect(ExpeditedAdverseEventReport loaded) {
assertEquals("IBM", loaded.getMedicalDevices().get(0).getBrandName());
}
});
}
public void testSaveNewRadiationIntervention() throws Exception {
doSaveTest(new SaveTester() {
public void setupReport(ExpeditedAdverseEventReport report) {
report.getRadiationInterventions().get(0).setDaysElapsed("120");
}
public void assertCorrect(ExpeditedAdverseEventReport loaded) {
assertEquals("120", loaded.getRadiationInterventions().get(0).getDaysElapsed());
}
});
}
public void testSaveNewSurgeryIntervention() throws Exception {
doSaveTest(new SaveTester() {
public void setupReport(ExpeditedAdverseEventReport report) {
report.getSurgeryInterventions().get(0).setInterventionSite(
interventionSiteDao.getById(-33));
}
public void assertCorrect(ExpeditedAdverseEventReport loaded) {
assertEquals(-33, (int) loaded.getSurgeryInterventions().get(0)
.getInterventionSite().getId());
}
});
}
public void testSaveSkipsPhysicianWhenNotSavable() throws Exception {
doSaveTest(new SaveTester() {
public void setupReport(ExpeditedAdverseEventReport report) {
report.getPhysician().setLastName(null);
}
public void assertCorrect(ExpeditedAdverseEventReport loaded) {
assertNull(loaded.getPhysician());
}
});
}
public void testSaveSkipsReporterWhenNotSavable() throws Exception {
doSaveTest(new SaveTester() {
public void setupReport(ExpeditedAdverseEventReport report) {
report.getReporter().setFirstName(null);
}
public void assertCorrect(ExpeditedAdverseEventReport loaded) {
assertNull(loaded.getReporter());
}
});
}
public void testSaveWhenDetached(){
ExpeditedAdverseEventReport report = getDao().getById(-1);
interruptSession();
getDao().save(report);
}
public void testSaveSavesReporterWhenSavable() throws Exception {
doSaveTest(new SaveTester() {
private static final String FIRST_NAME = "Joe";
private static final String LAST_NAME = "Arimathea";
private static final String ADDRESS = "joe@arimatheaonline.net";
private static final String PHONE = "312-HY-GRAIL";
public void setupReport(ExpeditedAdverseEventReport report) {
report.getReporter().setFirstName(FIRST_NAME);
report.getReporter().setLastName(LAST_NAME);
report.getReporter().getContactMechanisms().put(ReportPerson.EMAIL, ADDRESS);
report.getReporter().getContactMechanisms().put(ReportPerson.PHONE, PHONE);
}
public void assertCorrect(ExpeditedAdverseEventReport loaded) {
assertEquals(FIRST_NAME, loaded.getReporter().getFirstName());
assertEquals(LAST_NAME, loaded.getReporter().getLastName());
assertEquals(ADDRESS, loaded.getReporter().getContactMechanisms().get(
ReportPerson.EMAIL));
assertEquals(PHONE, loaded.getReporter().getContactMechanisms().get(
ReportPerson.PHONE));
}
});
}
public void testSaveSavesPhysicianWhenSavable() throws Exception {
doSaveTest(new SaveTester() {
private static final String FIRST_NAME = "Henry";
private static final String LAST_NAME = "Jones";
private static final String ADDRESS = "jonessr@indianaonline.net";
private static final String PHONE = "773-LOST-BOK";
public void setupReport(ExpeditedAdverseEventReport report) {
report.getPhysician().setFirstName(FIRST_NAME);
report.getPhysician().setLastName(LAST_NAME);
report.getPhysician().getContactMechanisms().put(ReportPerson.EMAIL, ADDRESS);
report.getPhysician().getContactMechanisms().put(ReportPerson.PHONE, PHONE);
}
public void assertCorrect(ExpeditedAdverseEventReport loaded) {
assertEquals(FIRST_NAME, loaded.getPhysician().getFirstName());
assertEquals(LAST_NAME, loaded.getPhysician().getLastName());
assertEquals(ADDRESS, loaded.getPhysician().getContactMechanisms().get(
ReportPerson.EMAIL));
assertEquals(PHONE, loaded.getPhysician().getContactMechanisms().get(
ReportPerson.PHONE));
}
});
}
// public void testSaveSavesSubmittableReports() throws Exception {
// doSaveTest(new SaveTester() {
// public void setupReport(ExpeditedAdverseEventReport report) {
// Report submittable = new Report();
// submittable.setDueOn(new Date());
// submittable.setCreatedOn(new Date());
// // submittable.setName("What is this field for?");
// submittable.setReportDefinition(reportDefinitionDao.getById(-30));
// report.addReport(submittable);
// }
//
// public void assertCorrect(ExpeditedAdverseEventReport loaded) {
// assertEquals("Report not saved", 1, loaded.getReports().size());
// assertEquals("Report has wrong definition",
// -30, (int) loaded.getReports().get(0).getReportDefinition().getId());
// }
// });
// }
public void testDeleteOrphanAdverseEvent() throws Exception {
{
ExpeditedAdverseEventReport loaded = getDao().getById(-1);
assertEquals("Wrong number of AEs initially", 2, loaded.getAdverseEvents().size());
assertEquals("Wrong initial AE 0", -70, (int) loaded.getAdverseEvents().get(0).getId());
assertEquals("Wrong initial AE 1", -11, (int) loaded.getAdverseEvents().get(1).getId());
loaded.getAdverseEvents().remove(0);
getDao().save(loaded);
}
interruptSession();
ExpeditedAdverseEventReport reloaded = getDao().getById(-1);
assertEquals("Wrong number of AEs when reloaded", 1, reloaded.getAdverseEvents().size());
assertEquals("Wrong AE when reloaded", -11, (int) reloaded.getAdverseEvents().get(0)
.getId());
}
public void testDeleteMetastaticDiseaseSiteDoesNotDeleteAnatomicSite() throws Exception {
{
ExpeditedAdverseEventReport loaded = getDao().getById(-1);
assertEquals("Data not as initially expected", 1, loaded.getDiseaseHistory()
.getMetastaticDiseaseSites().size());
assertEquals("Data not as initially expected", -33, (int) loaded.getDiseaseHistory()
.getMetastaticDiseaseSites().get(0).getCodedSite().getId());
loaded.getDiseaseHistory().getMetastaticDiseaseSites().remove(0);
getDao().save(loaded);
}
interruptSession();
ExpeditedAdverseEventReport reloaded = getDao().getById(-1);
assertEquals("Metastatic site not removed", 0, reloaded.getDiseaseHistory()
.getMetastaticDiseaseSites().size());
assertNotNull("Anatomic site deleted", anatomicSiteDao.getById(-33));
}
public void testSearchExpeditedReportByCtcTermPartial() throws Exception {
List<ExpeditedAdverseEventReport> results;
Map<String, String> m = new HashMap<String, String>();
m.put("ctcTerm", "Auditory/Ear");
results = getDao().searchExpeditedReports(m);
assertEquals("Wrong number of results", 1, results.size());
}
public void testSearchExpeditedReportByParticipant() throws Exception {
List<ExpeditedAdverseEventReport> results;
Map<String, String> m = new HashMap<String, String>();
m.put("participantFirstName", "Michael");
m.put("participantLastName", "Jordan");
m.put("participantEthnicity", "ethnicity");
m.put("participantGender", "Male");
m.put("participantDateOfBirth","01/02/2006");
m.put("participantIdentifier", "13js77");
results = getDao().searchExpeditedReports(m);
assertEquals("Wrong number of results", 1, results.size());
}
public void testSearchExpeditedReportByStudy() throws Exception {
List<ExpeditedAdverseEventReport> results;
Map<String, String> m = new HashMap<String, String>();
m.put("studyShortTitle", "That");
m.put("studyIdentifier", "nci_test");
results = getDao().searchExpeditedReports(m);
assertEquals("Wrong number of results", 1, results.size());
}
//10043882
public void testSearchExpeditedReportByCtepCodeAndCategory() throws Exception {
List<ExpeditedAdverseEventReport> results;
Map<String, String> m = new HashMap<String, String>();
m.put("ctcCtepCode", "10043882");
m.put("ctcCategory", "auditory/ear");
results = getDao().searchExpeditedReports(m);
assertEquals("Wrong number of results", 1, results.size());
}
public void testSerializeExpeditedAdverseEventReport() throws Exception {
ExpeditedAdverseEventReport aer = getDao().getById(-1);
AdverseEventReportSerializer aeser = (AdverseEventReportSerializer) getApplicationContext()
.getBean("adverseEventReportSerializer");
String xml = aeser.serialize(aer, null);
System.out.println(xml);
//assertEquals(xml,getStringFromFile());
}
public void testHasSubmittedReport(){
ExpeditedAdverseEventReport loaded = getDao().getById(-1);
assertFalse(loaded.getHasSubmittedAmendableReport());
}
private void doSaveTest(SaveTester tester) {
Integer savedId;
{
ExpeditedAdverseEventReport report = createMinimalAeReport();
tester.setupReport(report);
getDao().save(report);
assertNotNull("No ID for new report", report.getId());
savedId = report.getId();
}
interruptSession();
{
ExpeditedAdverseEventReport loaded = getDao().getById(savedId);
assertNotNull("Saved report not found", loaded);
tester.assertCorrect(loaded);
}
}
private ExpeditedAdverseEventReport createMinimalAeReport() {
ExpeditedAdverseEventReport report = Fixtures.createSavableExpeditedReport();
report.setReportingPeriod(reportingPeriodDao.getById(-14));
report.getAdverseEvents().get(0).setAdverseEventCtcTerm(
Fixtures.createAdverseEventCtcTerm(report.getAdverseEvents().get(0),
ctcTermDao.getById(3012)));
return report;
}
private static interface SaveTester {
void setupReport(ExpeditedAdverseEventReport report);
void assertCorrect(ExpeditedAdverseEventReport loaded);
}
public void testGetByCriteria(){
List<ExpeditedAdverseEventReport> reports = getDao().getByCriteria(null, null);
assertTrue(reports.isEmpty());
}
public void testReassociate(){
ExpeditedAdverseEventReport report = getDao().getById(-1);
interruptSession();
try{
report.getTreatmentInformation().getCourseAgentsInternal().size();
fail("should throw lazy exception");
}catch(Exception e){
}
getDao().reassociate(report);
assertEquals(2,report.getTreatmentInformation().getCourseAgentsInternal().size());
}
public void testDeleteAttribution(){
RadiationAttribution rAttribution1 = new RadiationAttribution();
RadiationIntervention cause = new RadiationIntervention();
cause.setId(5);
rAttribution1.setCause(cause);
RadiationAttribution rAttribution2 = new RadiationAttribution();
RadiationIntervention cause2 = new RadiationIntervention();
cause2.setId(6);
rAttribution2.setCause(cause2);
List<RadiationAttribution> list = new ArrayList<RadiationAttribution>();
list.add(rAttribution1);
list.add(rAttribution2);
getDao().deleteAttribution(rAttribution1.getCause(), list, null);
assertEquals(1,list.size());
}
public void testCascaeDeleteToAttributions(){
RadiationAttribution rAttribution1 = new RadiationAttribution();
RadiationIntervention cause = new RadiationIntervention();
cause.setId(5);
rAttribution1.setCause(cause);
RadiationAttribution rAttribution2 = new RadiationAttribution();
RadiationIntervention cause2 = new RadiationIntervention();
cause2.setId(6);
rAttribution2.setCause(cause2);
List<RadiationAttribution> list = new ArrayList<RadiationAttribution>();
list.add(rAttribution1);
list.add(rAttribution2);
ExpeditedAdverseEventReport aeReport = Fixtures.createSavableExpeditedReport();
aeReport.getAdverseEvents().get(0).setRadiationAttributions(list);
boolean returnVal = getDao().cascaeDeleteToAttributions(cause2, aeReport);
assertTrue(returnVal);
assertEquals(1, list.size());
}
public void testCascadeDeleteToAttributions_DiseaseAttribution(){
DiseaseAttribution d1 = new DiseaseAttribution();
DiseaseHistory dh1 = new DiseaseHistory();
dh1.setId(4);
d1.setCause(dh1);
DiseaseAttribution d2 = new DiseaseAttribution();
DiseaseHistory dh2 = new DiseaseHistory();
dh2.setId(5);
d2.setCause(dh2);
List<DiseaseAttribution> list = new ArrayList<DiseaseAttribution>();
list.add(d1);
list.add(d2);
ExpeditedAdverseEventReport aeReport = Fixtures.createSavableExpeditedReport();
aeReport.getAdverseEvents().get(0).setDiseaseAttributions(list);
boolean returnVal = getDao().cascaeDeleteToAttributions(dh2, aeReport);
assertTrue(returnVal);
assertEquals(1, list.size());
}
public void testCascadeDeleteToAtrributions_CourseAgentAttribution(){
ExpeditedAdverseEventReport aeReport = Fixtures.createSavableExpeditedReport();
List<CourseAgentAttribution> list = new ArrayList<CourseAgentAttribution>();
aeReport.getAdverseEvents().get(0).setCourseAgentAttributions(list);
CourseAgentAttribution a1 = new CourseAgentAttribution();
CourseAgent c1 = new CourseAgent();
CourseAgentAttribution a2 = new CourseAgentAttribution();
CourseAgent c2 = new CourseAgent();
c1.setId(3);
c2.setId(4);
a1.setCause(c1);
a2.setCause(c2);
list.add(a1);
list.add(a2);
boolean returnVal = getDao().cascaeDeleteToAttributions(c1, aeReport);
assertTrue(returnVal);
assertEquals(1, list.size());
}
public void testCascadeDeleteToAtrributions_OtherCauseAttribution(){
ExpeditedAdverseEventReport aeReport = Fixtures.createSavableExpeditedReport();
List<OtherCauseAttribution> list = new ArrayList<OtherCauseAttribution>();
aeReport.getAdverseEvents().get(0).setOtherCauseAttributions(list);
OtherCauseAttribution a1 = new OtherCauseAttribution();
OtherCause c1 = new OtherCause();
OtherCauseAttribution a2 = new OtherCauseAttribution();
OtherCause c2 = new OtherCause();
c1.setId(3);
c2.setId(4);
a1.setCause(c1);
a2.setCause(c2);
list.add(a1);
list.add(a2);
boolean returnVal = getDao().cascaeDeleteToAttributions(c1, aeReport);
assertTrue(returnVal);
assertEquals(1, list.size());
}
public void testCascadeDeleteToAtrributions_ConcomitantMedicationAttribution(){
ExpeditedAdverseEventReport aeReport = Fixtures.createSavableExpeditedReport();
List<ConcomitantMedicationAttribution> list = new ArrayList<ConcomitantMedicationAttribution>();
aeReport.getAdverseEvents().get(0).setConcomitantMedicationAttributions(list);
ConcomitantMedicationAttribution a1 = new ConcomitantMedicationAttribution();
ConcomitantMedication c1 = new ConcomitantMedication();
ConcomitantMedicationAttribution a2 = new ConcomitantMedicationAttribution();
ConcomitantMedication c2 = new ConcomitantMedication();
c1.setId(3);
c2.setId(4);
a1.setCause(c1);
a2.setCause(c2);
list.add(a1);
list.add(a2);
boolean returnVal = getDao().cascaeDeleteToAttributions(c1, aeReport);
assertTrue(returnVal);
assertEquals(1, list.size());
}
public void testCascadeDeleteToAtrributions_MedicalDeviceAttribution(){
ExpeditedAdverseEventReport aeReport = Fixtures.createSavableExpeditedReport();
List<DeviceAttribution> list = new ArrayList<DeviceAttribution>();
aeReport.getAdverseEvents().get(0).setDeviceAttributions(list);
DeviceAttribution a1 = new DeviceAttribution();
MedicalDevice c1 = new MedicalDevice();
DeviceAttribution a2 = new DeviceAttribution();
MedicalDevice c2 = new MedicalDevice();
c1.setId(3);
c2.setId(4);
a1.setCause(c1);
a2.setCause(c2);
list.add(a1);
list.add(a2);
boolean returnVal = getDao().cascaeDeleteToAttributions(c1, aeReport);
assertTrue(returnVal);
assertEquals(1, list.size());
}
public void testCascadeDeleteToAtrributions_SurgeryAttribution(){
ExpeditedAdverseEventReport aeReport = Fixtures.createSavableExpeditedReport();
List<SurgeryAttribution> list = new ArrayList<SurgeryAttribution>();
aeReport.getAdverseEvents().get(0).setSurgeryAttributions(list);
SurgeryAttribution a1 = new SurgeryAttribution();
SurgeryIntervention c1 = new SurgeryIntervention();
SurgeryAttribution a2 = new SurgeryAttribution();
SurgeryIntervention c2 = new SurgeryIntervention();
c1.setId(3);
c2.setId(4);
a1.setCause(c1);
a2.setCause(c2);
list.add(a1);
list.add(a2);
boolean returnVal = getDao().cascaeDeleteToAttributions(c1, aeReport);
assertTrue(returnVal);
assertEquals(1, list.size());
}
public void testSaveReviewComments() throws Exception {
final Date today = new Date();
ExpeditedAdverseEventReport loaded = getDao().getById(-1);
ReportReviewComment reviewComment = new ReportReviewComment();
reviewComment.setCreatedDate(new Date());
reviewComment.setAutoGeneratedText("Added by " );
reviewComment.setUserComment("abcd");
reviewComment.setEditable(true);
reviewComment.setUserId("5");
loaded.getReviewComments().add(reviewComment);
getDao().modifyOrSaveReviewStatusAndComments(loaded);
loaded = getDao().getById(-1);
assertEquals("abcd", loaded.getReviewComments().get(0).getUserComment());
}
private String getStringFromFile() throws Exception {
File testFile = new ClassPathResource("/gov/nih/nci/cabig/caaers/dao/testdata/ExpeditedAdverseEventReportString.txt").getFile();
BufferedReader bufRead = new BufferedReader(new FileReader(testFile));
String line = bufRead.readLine();
String str1 = "";
while (line != null) {
str1 = str1 + line;
line = bufRead.readLine();
}
return str1;
}
}
| fixing hudson testcases
SVN-Revision: 11130
| caAERS/software/core/src/test/java/gov/nih/nci/cabig/caaers/dao/ExpeditedAdverseEventReportDaoTest.java | fixing hudson testcases | |
Java | bsd-3-clause | 3c4d8084a6f442e515a9b0cf7993d8fda08835d3 | 0 | NCIP/rembrandt,NCIP/rembrandt,NCIP/rembrandt,NCIP/rembrandt,NCIP/rembrandt,NCIP/rembrandt | /*
* @author: SahniH
* Created on Nov 11, 2004
* @version $ Revision: 1.0 $
*
* The caBIO Software License, Version 1.0
*
* Copyright 2004 SAIC. This software was developed in conjunction with the National Cancer
* Institute, and so to the extent government employees are co-authors, any rights in such works
* shall be subject to Title 17 of the United States Code, section 105.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions
* and the disclaimer of Article 3, below. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 2. The end-user documentation included with the redistribution, if any, must include the
* following acknowledgment:
*
* "This product includes software developed by the SAIC and the National Cancer
* Institute."
*
* If no such end-user documentation is to be included, this acknowledgment shall appear in the
* software itself, wherever such third-party acknowledgments normally appear.
*
* 3. The names "The National Cancer Institute", "NCI" and "SAIC" must not be used to endorse or
* promote products derived from this software.
*
* 4. This license does not authorize the incorporation of this software into any proprietary
* programs. This license does not authorize the recipient to use any trademarks owned by either
* NCI or SAIC-Frederick.
*
*
* 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE
* DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, SAIC, OR
* THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package gov.nih.nci.rembrandt.queryservice.resultset.kaplanMeierPlot;
import gov.nih.nci.caintegrator.dto.de.CytobandDE;
import gov.nih.nci.caintegrator.dto.de.DatumDE;
import gov.nih.nci.caintegrator.dto.de.GeneIdentifierDE;
import gov.nih.nci.caintegrator.ui.graphing.data.kaplanmeier.KaplanMeierSampleInfo;
import gov.nih.nci.rembrandt.queryservice.resultset.gene.ReporterResultset;
import gov.nih.nci.rembrandt.queryservice.resultset.sample.SampleViewResultsContainer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
/**
* @author Himanso
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
*/
public class KaplanMeierPlotContainer extends SampleViewResultsContainer {
private static Logger logger = Logger.getLogger(KaplanMeierPlotContainer.class);
private GeneIdentifierDE.GeneSymbol geneSymbol;
private CytobandDE cytobandDE;
/**
* @return Returns the geneSymbol.
*/
public GeneIdentifierDE.GeneSymbol getGeneSymbol() {
return this.geneSymbol;
}
/**
* @param geneSymbol
* The geneSymbol to set.
*/
public void setGeneSymbol(GeneIdentifierDE.GeneSymbol geneSymbol) {
this.geneSymbol = geneSymbol;
}
public KaplanMeierSampleInfo[] getSummaryKMPlotSamples() {
List<KaplanMeierSampleInfo> kmSampleInfoArray = new ArrayList<KaplanMeierSampleInfo>();
Collection samples = getBioSpecimenResultsets();
//Clear the Previous collection
for (Iterator sampleIterator = samples.iterator(); sampleIterator.hasNext();) {
SampleKaplanMeierPlotResultset sample = (SampleKaplanMeierPlotResultset) sampleIterator.next();
if(sample != null && sample.getCensor()!= null && sample.getSurvivalLength() != null&& sample.getSummaryReporterFoldChange()!= null){
Long time = (Long) (sample.getSurvivalLength().getValue());
Integer censor = new Integer((sample.getCensor().getValue().toString()));
Double value = (Double) sample.getSummaryReporterFoldChange().getValue();
KaplanMeierSampleInfo kmSampleInfo = new KaplanMeierSampleInfo(time.intValue(), censor.intValue(), value.doubleValue());
kmSampleInfoArray.add(kmSampleInfo);
}
}
return (KaplanMeierSampleInfo[]) kmSampleInfoArray.toArray(new KaplanMeierSampleInfo[kmSampleInfoArray.size()]);
}
public KaplanMeierSampleInfo[] getKMPlotSamplesForReporter(String reporterName){
List<KaplanMeierSampleInfo> kmSampleInfoArray = new ArrayList<KaplanMeierSampleInfo>();
Collection samples = getBioSpecimenResultsets();
for (Iterator sampleIterator = samples.iterator(); sampleIterator.hasNext();) {
SampleKaplanMeierPlotResultset sample = (SampleKaplanMeierPlotResultset) sampleIterator.next();
if(sample != null && sample.getSurvivalLength()!= null && sample.getCensor()!= null && sample.getCensor().getValue() != null){
ReporterResultset reporterResultset = sample.getReporterResultset(reporterName);
if (reporterResultset != null && reporterResultset.getValue() != null){
Long time = (Long) (sample.getSurvivalLength().getValue());
Integer censor = new Integer((sample.getCensor().getValue().toString()));
DatumDE datumDE = reporterResultset.getValue();
Double value = (Double) datumDE.getValue();
KaplanMeierSampleInfo kmSampleInfo = new KaplanMeierSampleInfo(time.intValue(), censor.intValue(), value.doubleValue());
kmSampleInfoArray.add(kmSampleInfo);
}
}
}
return (KaplanMeierSampleInfo[]) kmSampleInfoArray.toArray(new KaplanMeierSampleInfo[kmSampleInfoArray.size()]);
}
public List getAssociatedReporters(){
List reporterNames = null;
Collection samples = getBioSpecimenResultsets();
if(!samples.isEmpty()){
Iterator sampleIterator = samples.iterator();
SampleKaplanMeierPlotResultset sample = (SampleKaplanMeierPlotResultset) sampleIterator.next();
reporterNames = sample.getReporterNames();
}
return reporterNames;
}
/**
* @return Returns the cytobandDE.
*/
public CytobandDE getCytobandDE() {
return cytobandDE;
}
/**
* @param cytobandDE The cytobandDE to set.
*/
public void setCytobandDE(CytobandDE cytobandDE) {
this.cytobandDE = cytobandDE;
}
} | src/gov/nih/nci/rembrandt/queryservice/resultset/kaplanMeierPlot/KaplanMeierPlotContainer.java | /*
* @author: SahniH
* Created on Nov 11, 2004
* @version $ Revision: 1.0 $
*
* The caBIO Software License, Version 1.0
*
* Copyright 2004 SAIC. This software was developed in conjunction with the National Cancer
* Institute, and so to the extent government employees are co-authors, any rights in such works
* shall be subject to Title 17 of the United States Code, section 105.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions
* and the disclaimer of Article 3, below. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 2. The end-user documentation included with the redistribution, if any, must include the
* following acknowledgment:
*
* "This product includes software developed by the SAIC and the National Cancer
* Institute."
*
* If no such end-user documentation is to be included, this acknowledgment shall appear in the
* software itself, wherever such third-party acknowledgments normally appear.
*
* 3. The names "The National Cancer Institute", "NCI" and "SAIC" must not be used to endorse or
* promote products derived from this software.
*
* 4. This license does not authorize the incorporation of this software into any proprietary
* programs. This license does not authorize the recipient to use any trademarks owned by either
* NCI or SAIC-Frederick.
*
*
* 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE
* DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, SAIC, OR
* THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package gov.nih.nci.rembrandt.queryservice.resultset.kaplanMeierPlot;
import gov.nih.nci.caintegrator.dto.de.CytobandDE;
import gov.nih.nci.caintegrator.dto.de.DatumDE;
import gov.nih.nci.caintegrator.dto.de.GeneIdentifierDE;
import gov.nih.nci.caintegrator.ui.graphing.data.kaplanmeier.KaplanMeierSampleInfo;
import gov.nih.nci.rembrandt.queryservice.resultset.gene.ReporterResultset;
import gov.nih.nci.rembrandt.queryservice.resultset.sample.SampleViewResultsContainer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
/**
* @author Himanso
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
*/
public class KaplanMeierPlotContainer extends SampleViewResultsContainer {
private static Logger logger = Logger.getLogger(KaplanMeierPlotContainer.class);
private GeneIdentifierDE.GeneSymbol geneSymbol;
private CytobandDE cytobandDE;
/**
* @return Returns the geneSymbol.
*/
public GeneIdentifierDE.GeneSymbol getGeneSymbol() {
return this.geneSymbol;
}
/**
* @param geneSymbol
* The geneSymbol to set.
*/
public void setGeneSymbol(GeneIdentifierDE.GeneSymbol geneSymbol) {
this.geneSymbol = geneSymbol;
}
public KaplanMeierSampleInfo[] getSummaryKMPlotSamples() {
List<KaplanMeierSampleInfo> kmSampleInfoArray = new ArrayList<KaplanMeierSampleInfo>();
Collection samples = getBioSpecimenResultsets();
//Clear the Previous collection
for (Iterator sampleIterator = samples.iterator(); sampleIterator.hasNext();) {
SampleKaplanMeierPlotResultset sample = (SampleKaplanMeierPlotResultset) sampleIterator.next();
if(sample != null && sample.getCensor()!= null && sample.getSurvivalLength() != null&& sample.getSummaryReporterFoldChange()!= null){
Long time = (Long) (sample.getSurvivalLength().getValue());
Integer censor = new Integer((sample.getCensor().getValue().toString()));
Double value = (Double) sample.getSummaryReporterFoldChange().getValue();
KaplanMeierSampleInfo kmSampleInfo = new KaplanMeierSampleInfo(time.intValue(), censor.intValue(), value.doubleValue());
kmSampleInfoArray.add(kmSampleInfo);
}
}
return (KaplanMeierSampleInfo[]) kmSampleInfoArray.toArray(new KaplanMeierSampleInfo[kmSampleInfoArray.size()]);
}
public KaplanMeierSampleInfo[] getKMPlotSamplesForReporter(String reporterName){
List<KaplanMeierSampleInfo> kmSampleInfoArray = new ArrayList<KaplanMeierSampleInfo>();
Collection samples = getBioSpecimenResultsets();
for (Iterator sampleIterator = samples.iterator(); sampleIterator.hasNext();) {
SampleKaplanMeierPlotResultset sample = (SampleKaplanMeierPlotResultset) sampleIterator.next();
ReporterResultset reporterResultset = sample.getReporterResultset(reporterName);
if (reporterResultset != null && reporterResultset.getValue() != null){
Long time = (Long) (sample.getSurvivalLength().getValue());
Integer censor = new Integer((sample.getCensor().getValue().toString()));
DatumDE datumDE = reporterResultset.getValue();
Double value = (Double) datumDE.getValue();
KaplanMeierSampleInfo kmSampleInfo = new KaplanMeierSampleInfo(time.intValue(), censor.intValue(), value.doubleValue());
kmSampleInfoArray.add(kmSampleInfo);
}
}
return (KaplanMeierSampleInfo[]) kmSampleInfoArray.toArray(new KaplanMeierSampleInfo[kmSampleInfoArray.size()]);
}
public List getAssociatedReporters(){
List reporterNames = null;
Collection samples = getBioSpecimenResultsets();
if(!samples.isEmpty()){
Iterator sampleIterator = samples.iterator();
SampleKaplanMeierPlotResultset sample = (SampleKaplanMeierPlotResultset) sampleIterator.next();
reporterNames = sample.getReporterNames();
}
return reporterNames;
}
/**
* @return Returns the cytobandDE.
*/
public CytobandDE getCytobandDE() {
return cytobandDE;
}
/**
* @param cytobandDE The cytobandDE to set.
*/
public void setCytobandDE(CytobandDE cytobandDE) {
this.cytobandDE = cytobandDE;
}
} | fixed NullPointerException for missing censor and survival data for copy number
SVN-Revision: 1866
| src/gov/nih/nci/rembrandt/queryservice/resultset/kaplanMeierPlot/KaplanMeierPlotContainer.java | fixed NullPointerException for missing censor and survival data for copy number | |
Java | bsd-3-clause | ff9b64f4003c400240057a4d20191cffa3f37446 | 0 | UCDenver-ccp/ccp-nlp,UCDenver-ccp/ccp-nlp | /*
Copyright (c) 2012, Regents of the University of Colorado
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Colorado nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package edu.ucdenver.ccp.nlp.uima.util;
import java.io.File;
import java.io.FilenameFilter;
/**
* FilenameFilter that accepts files ending with "xcas"
*
* @author Colorado Computational Pharmacology, UC Denver; ccpsupport@ucdenver.edu
*
*/
public class XCASFilenameFilter implements FilenameFilter {
public XCASFilenameFilter() {
}
public boolean accept(File dir, String name) {
return name.endsWith("xcas");
}
} | ccp-nlp-uima/src/main/java/edu/ucdenver/ccp/nlp/uima/util/XCASFilenameFilter.java | /*
Copyright (c) 2012, Regents of the University of Colorado
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Colorado nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package edu.ucdenver.ccp.nlp.uima.util;
import java.io.File;
import java.io.FilenameFilter;
/**
* @author Colorado Computational Pharmacology, UC Denver; ccpsupport@ucdenver.edu
*
*/
public class XCASFilenameFilter implements FilenameFilter {
public XCASFilenameFilter() {
}
public boolean accept(File dir, String name) {
return name.endsWith("xcas");
}
} | added javadoc
| ccp-nlp-uima/src/main/java/edu/ucdenver/ccp/nlp/uima/util/XCASFilenameFilter.java | added javadoc | |
Java | mit | 6c37944c65b99884121eb6e5e2e741c1a4bca6a4 | 0 | sake/bouncycastle-java | package org.bouncycastle.math.ec;
import java.math.BigInteger;
import java.util.Random;
public abstract class ECFieldElement
implements ECConstants
{
BigInteger x;
protected ECFieldElement(BigInteger x)
{
this.x = x;
}
public BigInteger toBigInteger()
{
return x;
}
public abstract String getFieldName();
public abstract ECFieldElement add(ECFieldElement b);
public abstract ECFieldElement subtract(ECFieldElement b);
public abstract ECFieldElement multiply(ECFieldElement b);
public abstract ECFieldElement divide(ECFieldElement b);
public abstract ECFieldElement negate();
public abstract ECFieldElement square();
public abstract ECFieldElement invert();
public abstract ECFieldElement sqrt();
public String toString()
{
return this.x.toString(2);
}
public static class Fp extends ECFieldElement
{
BigInteger q;
public Fp(BigInteger q, BigInteger x)
{
super(x);
if (x.compareTo(q) >= 0)
{
throw new IllegalArgumentException("x value too large in field element");
}
this.q = q;
}
/**
* return the field name for this field.
*
* @return the string "Fp".
*/
public String getFieldName()
{
return "Fp";
}
public BigInteger getQ()
{
return q;
}
public ECFieldElement add(ECFieldElement b)
{
return new Fp(q, x.add(b.x).mod(q));
}
public ECFieldElement subtract(ECFieldElement b)
{
return new Fp(q, x.subtract(b.x).mod(q));
}
public ECFieldElement multiply(ECFieldElement b)
{
return new Fp(q, x.multiply(b.x).mod(q));
}
public ECFieldElement divide(ECFieldElement b)
{
return new Fp(q, x.multiply(b.x.modInverse(q)).mod(q));
}
public ECFieldElement negate()
{
return new Fp(q, x.negate().mod(q));
}
public ECFieldElement square()
{
return new Fp(q, x.multiply(x).mod(q));
}
public ECFieldElement invert()
{
return new Fp(q, x.modInverse(q));
}
// D.1.4 91
/**
* return a sqrt root - the routine verifies that the calculation
* returns the right value - if none exists it returns null.
*/
public ECFieldElement sqrt()
{
if (!q.testBit(0))
{
throw new RuntimeException("not done yet");
}
// p mod 4 == 3
if (q.testBit(1))
{
// z = g^(u+1) + p, p = 4u + 3
ECFieldElement z = new Fp(q, x.modPow(q.shiftRight(2).add(ONE), q));
return z.square().equals(this) ? z : null;
}
// p mod 4 == 1
BigInteger qMinusOne = q.subtract(ECConstants.ONE);
BigInteger legendreExponent = qMinusOne.shiftRight(1);
if (!(x.modPow(legendreExponent, q).equals(ECConstants.ONE)))
return null;
BigInteger u = qMinusOne.shiftRight(2);
BigInteger k = u.shiftLeft(1).add(ECConstants.ONE);
BigInteger Q = this.x;
BigInteger fourQ = Q.shiftLeft(2).mod(q);
BigInteger U, V;
do
{
Random rand = new Random();
BigInteger P;
do
{
P = new BigInteger(q.bitLength(), rand);
}
while (P.compareTo(q) >= 0
|| !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, q).equals(qMinusOne)));
BigInteger[] result = lucasSequence(q, P, Q, k);
U = result[0];
V = result[1];
if (V.multiply(V).mod(q).equals(fourQ))
{
// Integer division by 2, mod q
if (V.testBit(0))
{
V = V.add(q);
}
V = V.shiftRight(1);
//assert V.multiply(V).mod(q).equals(x);
return new ECFieldElement.Fp(q, V);
}
}
while (U.equals(ECConstants.ONE) || U.equals(qMinusOne));
return null;
// BigInteger qMinusOne = q.subtract(ECConstants.ONE);
// BigInteger legendreExponent = qMinusOne.shiftRight(1); //divide(ECConstants.TWO);
// if (!(x.modPow(legendreExponent, q).equals(ECConstants.ONE)))
// {
// return null;
// }
//
// Random rand = new Random();
// BigInteger fourX = x.shiftLeft(2);
//
// BigInteger r;
// do
// {
// r = new BigInteger(q.bitLength(), rand);
// }
// while (r.compareTo(q) >= 0
// || !(r.multiply(r).subtract(fourX).modPow(legendreExponent, q).equals(qMinusOne)));
//
// BigInteger n1 = qMinusOne.shiftRight(2); //.divide(ECConstants.FOUR);
// BigInteger n2 = n1.add(ECConstants.ONE); //q.add(ECConstants.THREE).divide(ECConstants.FOUR);
//
// BigInteger wOne = WOne(r, x, q);
// BigInteger wSum = W(n1, wOne, q).add(W(n2, wOne, q)).mod(q);
// BigInteger twoR = r.shiftLeft(1); //ECConstants.TWO.multiply(r);
//
// BigInteger root = twoR.modPow(q.subtract(ECConstants.TWO), q)
// .multiply(x).mod(q)
// .multiply(wSum).mod(q);
//
// return new Fp(q, root);
}
// private static BigInteger W(BigInteger n, BigInteger wOne, BigInteger p)
// {
// if (n.equals(ECConstants.ONE))
// {
// return wOne;
// }
// boolean isEven = !n.testBit(0);
// n = n.shiftRight(1);//divide(ECConstants.TWO);
// if (isEven)
// {
// BigInteger w = W(n, wOne, p);
// return w.multiply(w).subtract(ECConstants.TWO).mod(p);
// }
// BigInteger w1 = W(n.add(ECConstants.ONE), wOne, p);
// BigInteger w2 = W(n, wOne, p);
// return w1.multiply(w2).subtract(wOne).mod(p);
// }
//
// private BigInteger WOne(BigInteger r, BigInteger x, BigInteger p)
// {
// return r.multiply(r).multiply(x.modPow(q.subtract(ECConstants.TWO), q)).subtract(ECConstants.TWO).mod(p);
// }
private static BigInteger[] lucasSequence(
BigInteger p,
BigInteger P,
BigInteger Q,
BigInteger k)
{
int n = k.bitLength();
int s = k.getLowestSetBit();
BigInteger Uh = ECConstants.ONE;
BigInteger Vl = ECConstants.TWO;
BigInteger Vh = P;
BigInteger Ql = ECConstants.ONE;
BigInteger Qh = ECConstants.ONE;
for (int j = n - 1; j >= s + 1; --j)
{
Ql = Ql.multiply(Qh).mod(p);
if (k.testBit(j))
{
Qh = Ql.multiply(Q).mod(p);
Uh = Uh.multiply(Vh).mod(p);
Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p);
Vh = Vh.multiply(Vh).subtract(Qh.shiftLeft(1)).mod(p);
}
else
{
Qh = Ql;
Uh = Uh.multiply(Vl).subtract(Ql).mod(p);
Vh = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p);
Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p);
}
}
Ql = Ql.multiply(Qh).mod(p);
Qh = Ql.multiply(Q).mod(p);
Uh = Uh.multiply(Vl).subtract(Ql).mod(p);
Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p);
Ql = Ql.multiply(Qh).mod(p);
for (int j = 1; j <= s; ++j)
{
Uh = Uh.multiply(Vl).mod(p);
Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p);
Ql = Ql.multiply(Ql).mod(p);
}
return new BigInteger[]{ Uh, Vl };
}
public boolean equals(Object other)
{
if (other == this)
{
return true;
}
if (!(other instanceof ECFieldElement.Fp))
{
return false;
}
ECFieldElement.Fp o = (ECFieldElement.Fp)other;
return q.equals(o.q) && x.equals(o.x);
}
public int hashCode()
{
return q.hashCode() ^ x.hashCode();
}
}
/**
* Class representing the Elements of the finite field
* <code>F<sub>2<sup>m</sup></sub></code> in polynomial basis (PB)
* representation. Both trinomial (TPB) and pentanomial (PPB) polynomial
* basis representations are supported. Gaussian normal basis (GNB)
* representation is not supported.
*/
public static class F2m extends ECFieldElement
{
/**
* Indicates gaussian normal basis representation (GNB). Number chosen
* according to X9.62. GNB is not implemented at present.
*/
public static final int GNB = 1;
/**
* Indicates trinomial basis representation (TPB). Number chosen
* according to X9.62.
*/
public static final int TPB = 2;
/**
* Indicates pentanomial basis representation (PPB). Number chosen
* according to X9.62.
*/
public static final int PPB = 3;
/**
* TPB or PPB.
*/
private int representation;
/**
* The exponent <code>m</code> of <code>F<sub>2<sup>m</sup></sub></code>.
*/
private int m;
/**
* TPB: The integer <code>k</code> where <code>x<sup>m</sup> +
* x<sup>k</sup> + 1</code> represents the reduction polynomial
* <code>f(z)</code>.<br>
* PPB: The integer <code>k1</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br>
*/
private int k1;
/**
* TPB: Always set to <code>0</code><br>
* PPB: The integer <code>k2</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br>
*/
private int k2;
/**
* TPB: Always set to <code>0</code><br>
* PPB: The integer <code>k3</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br>
*/
private int k3;
/**
* Constructor for PPB.
* @param m The exponent <code>m</code> of
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param x The BigInteger representing the value of the field element.
*/
public F2m(
int m,
int k1,
int k2,
int k3,
BigInteger x)
{
super(x);
if ((k2 == 0) && (k3 == 0))
{
this.representation = TPB;
}
else
{
if (k2 >= k3)
{
throw new IllegalArgumentException(
"k2 must be smaller than k3");
}
if (k2 <= 0)
{
throw new IllegalArgumentException(
"k2 must be larger than 0");
}
this.representation = PPB;
}
if (x.signum() < 0)
{
throw new IllegalArgumentException("x value cannot be negative");
}
this.m = m;
this.k1 = k1;
this.k2 = k2;
this.k3 = k3;
}
/**
* Constructor for TPB.
* @param m The exponent <code>m</code> of
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param k The integer <code>k</code> where <code>x<sup>m</sup> +
* x<sup>k</sup> + 1</code> represents the reduction
* polynomial <code>f(z)</code>.
* @param x The BigInteger representing the value of the field element.
*/
public F2m(int m, int k, BigInteger x)
{
// Set k1 to k, and set k2 and k3 to 0
this(m, k, 0, 0, x);
}
public String getFieldName()
{
return "F2m";
}
/**
* Checks, if the ECFieldElements <code>a</code> and <code>b</code>
* are elements of the same field <code>F<sub>2<sup>m</sup></sub></code>
* (having the same representation).
* @param a
* @param b
* @throws IllegalArgumentException if <code>a</code> and <code>b</code>
* are not elements of the same field
* <code>F<sub>2<sup>m</sup></sub></code> (having the same
* representation).
*/
public static void checkFieldElements(
ECFieldElement a,
ECFieldElement b)
{
if ((!(a instanceof F2m)) || (!(b instanceof F2m)))
{
throw new IllegalArgumentException("Field elements are not "
+ "both instances of ECFieldElement.F2m");
}
if ((a.x.signum() < 0) || (b.x.signum() < 0))
{
throw new IllegalArgumentException(
"x value may not be negative");
}
ECFieldElement.F2m aF2m = (ECFieldElement.F2m)a;
ECFieldElement.F2m bF2m = (ECFieldElement.F2m)b;
if ((aF2m.m != bF2m.m) || (aF2m.k1 != bF2m.k1)
|| (aF2m.k2 != bF2m.k2) || (aF2m.k3 != bF2m.k3))
{
throw new IllegalArgumentException("Field elements are not "
+ "elements of the same field F2m");
}
if (aF2m.representation != bF2m.representation)
{
// Should never occur
throw new IllegalArgumentException(
"One of the field "
+ "elements are not elements has incorrect representation");
}
}
/**
* Computes <code>z * a(z) mod f(z)</code>, where <code>f(z)</code> is
* the reduction polynomial of <code>this</code>.
* @param a The polynomial <code>a(z)</code> to be multiplied by
* <code>z mod f(z)</code>.
* @return <code>z * a(z) mod f(z)</code>
*/
private BigInteger multZModF(final BigInteger a)
{
// Left-shift of a(z)
BigInteger az = a.shiftLeft(1);
if (az.testBit(this.m))
{
// If the coefficient of z^m in a(z) equals 1, reduction
// modulo f(z) is performed: Add f(z) to to a(z):
// Step 1: Unset mth coeffient of a(z)
az = az.clearBit(this.m);
// Step 2: Add r(z) to a(z), where r(z) is defined as
// f(z) = z^m + r(z), and k1, k2, k3 are the positions of
// the non-zero coefficients in r(z)
az = az.flipBit(0);
az = az.flipBit(this.k1);
if (this.representation == PPB)
{
az = az.flipBit(this.k2);
az = az.flipBit(this.k3);
}
}
return az;
}
public ECFieldElement add(final ECFieldElement b)
{
// No check performed here for performance reasons. Instead the
// elements involved are checked in ECPoint.F2m
// checkFieldElements(this, b);
if (b.x.signum() == 0)
{
return this;
}
return new F2m(this.m, this.k1, this.k2, this.k3, this.x.xor(b.x));
}
public ECFieldElement subtract(final ECFieldElement b)
{
// Addition and subtraction are the same in F2m
return add(b);
}
public ECFieldElement multiply(final ECFieldElement b)
{
// Left-to-right shift-and-add field multiplication in F2m
// Input: Binary polynomials a(z) and b(z) of degree at most m-1
// Output: c(z) = a(z) * b(z) mod f(z)
// No check performed here for performance reasons. Instead the
// elements involved are checked in ECPoint.F2m
// checkFieldElements(this, b);
final BigInteger az = this.x;
BigInteger bz = b.x;
BigInteger cz;
// Compute c(z) = a(z) * b(z) mod f(z)
if (az.testBit(0))
{
cz = bz;
}
else
{
cz = ECConstants.ZERO;
}
for (int i = 1; i < this.m; i++)
{
// b(z) := z * b(z) mod f(z)
bz = multZModF(bz);
if (az.testBit(i))
{
// If the coefficient of x^i in a(z) equals 1, b(z) is added
// to c(z)
cz = cz.xor(bz);
}
}
return new ECFieldElement.F2m(m, this.k1, this.k2, this.k3, cz);
}
public ECFieldElement divide(final ECFieldElement b)
{
// There may be more efficient implementations
ECFieldElement bInv = b.invert();
return multiply(bInv);
}
public ECFieldElement negate()
{
// -x == x holds for all x in F2m
return this;
}
public ECFieldElement square()
{
// Naive implementation, can probably be speeded up using modular
// reduction
return multiply(this);
}
public ECFieldElement invert()
{
// Inversion in F2m using the extended Euclidean algorithm
// Input: A nonzero polynomial a(z) of degree at most m-1
// Output: a(z)^(-1) mod f(z)
// u(z) := a(z)
BigInteger uz = this.x;
if (uz.signum() <= 0)
{
throw new ArithmeticException("x is zero or negative, " +
"inversion is impossible");
}
// v(z) := f(z)
BigInteger vz = ECConstants.ONE.shiftLeft(m);
vz = vz.setBit(0);
vz = vz.setBit(this.k1);
if (this.representation == PPB)
{
vz = vz.setBit(this.k2);
vz = vz.setBit(this.k3);
}
// g1(z) := 1, g2(z) := 0
BigInteger g1z = ECConstants.ONE;
BigInteger g2z = ECConstants.ZERO;
// while u != 1
while (!(uz.equals(ECConstants.ZERO)))
{
// j := deg(u(z)) - deg(v(z))
int j = uz.bitLength() - vz.bitLength();
// If j < 0 then: u(z) <-> v(z), g1(z) <-> g2(z), j := -j
if (j < 0)
{
final BigInteger uzCopy = uz;
uz = vz;
vz = uzCopy;
final BigInteger g1zCopy = g1z;
g1z = g2z;
g2z = g1zCopy;
j = -j;
}
// u(z) := u(z) + z^j * v(z)
// Note, that no reduction modulo f(z) is required, because
// deg(u(z) + z^j * v(z)) <= max(deg(u(z)), j + deg(v(z)))
// = max(deg(u(z)), deg(u(z)) - deg(v(z)) + deg(v(z))
// = deg(u(z))
uz = uz.xor(vz.shiftLeft(j));
// g1(z) := g1(z) + z^j * g2(z)
g1z = g1z.xor(g2z.shiftLeft(j));
// if (g1z.bitLength() > this.m) {
// throw new ArithmeticException(
// "deg(g1z) >= m, g1z = " + g1z.toString(2));
// }
}
return new ECFieldElement.F2m(
this.m, this.k1, this.k2, this.k3, g2z);
}
public ECFieldElement sqrt()
{
throw new RuntimeException("Not implemented");
}
/**
* @return the representation of the field
* <code>F<sub>2<sup>m</sup></sub></code>, either of
* TPB (trinomial
* basis representation) or
* PPB (pentanomial
* basis representation).
*/
public int getRepresentation()
{
return this.representation;
}
/**
* @return the degree <code>m</code> of the reduction polynomial
* <code>f(z)</code>.
*/
public int getM()
{
return this.m;
}
/**
* @return TPB: The integer <code>k</code> where <code>x<sup>m</sup> +
* x<sup>k</sup> + 1</code> represents the reduction polynomial
* <code>f(z)</code>.<br>
* PPB: The integer <code>k1</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br>
*/
public int getK1()
{
return this.k1;
}
/**
* @return TPB: Always returns <code>0</code><br>
* PPB: The integer <code>k2</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br>
*/
public int getK2()
{
return this.k2;
}
/**
* @return TPB: Always set to <code>0</code><br>
* PPB: The integer <code>k3</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br>
*/
public int getK3()
{
return this.k3;
}
public boolean equals(Object anObject)
{
if (anObject == this)
{
return true;
}
if (!(anObject instanceof ECFieldElement.F2m))
{
return false;
}
ECFieldElement.F2m b = (ECFieldElement.F2m)anObject;
return ((this.m == b.m) && (this.k1 == b.k1) && (this.k2 == b.k2)
&& (this.k3 == b.k3)
&& (this.representation == b.representation)
&& (this.x.equals(b.x)));
}
public int hashCode()
{
return x.hashCode() ^ m ^ k1 ^ k2 ^ k3;
}
}
}
| src/org/bouncycastle/math/ec/ECFieldElement.java | package org.bouncycastle.math.ec;
import java.math.BigInteger;
import java.util.Random;
public abstract class ECFieldElement
implements ECConstants
{
BigInteger x;
protected ECFieldElement(BigInteger x)
{
this.x = x;
}
public BigInteger toBigInteger()
{
return x;
}
public abstract String getFieldName();
public abstract ECFieldElement add(ECFieldElement b);
public abstract ECFieldElement subtract(ECFieldElement b);
public abstract ECFieldElement multiply(ECFieldElement b);
public abstract ECFieldElement divide(ECFieldElement b);
public abstract ECFieldElement negate();
public abstract ECFieldElement square();
public abstract ECFieldElement invert();
public abstract ECFieldElement sqrt();
public String toString()
{
return this.x.toString(2);
}
public static class Fp extends ECFieldElement
{
BigInteger q;
public Fp(BigInteger q, BigInteger x)
{
super(x);
if (x.compareTo(q) >= 0)
{
throw new IllegalArgumentException("x value too large in field element");
}
this.q = q;
}
/**
* return the field name for this field.
*
* @return the string "Fp".
*/
public String getFieldName()
{
return "Fp";
}
public BigInteger getQ()
{
return q;
}
public ECFieldElement add(ECFieldElement b)
{
return new Fp(q, x.add(b.x).mod(q));
}
public ECFieldElement subtract(ECFieldElement b)
{
return new Fp(q, x.subtract(b.x).mod(q));
}
public ECFieldElement multiply(ECFieldElement b)
{
return new Fp(q, x.multiply(b.x).mod(q));
}
public ECFieldElement divide(ECFieldElement b)
{
return new Fp(q, x.multiply(b.x.modInverse(q)).mod(q));
}
public ECFieldElement negate()
{
return new Fp(q, x.negate().mod(q));
}
public ECFieldElement square()
{
return new Fp(q, x.multiply(x).mod(q));
}
public ECFieldElement invert()
{
return new Fp(q, x.modInverse(q));
}
// D.1.4 91
/**
* return a sqrt root - the routine verifies that the calculation
* returns the right value - if none exists it returns null.
*/
public ECFieldElement sqrt()
{
if (!q.testBit(0))
{
throw new RuntimeException("not done yet");
}
// p mod 4 == 3
if (q.testBit(1))
{
// z = g^(u+1) + p, p = 4u + 3
ECFieldElement z = new Fp(q, x.modPow(q.shiftRight(2).add(ONE), q));
return z.square().equals(this) ? z : null;
}
// p mod 4 == 1
BigInteger qMinusOne = q.subtract(ECConstants.ONE);
BigInteger legendreExponent = qMinusOne.shiftRight(1);
if (!(x.modPow(legendreExponent, q).equals(ECConstants.ONE)))
return null;
BigInteger u = qMinusOne.shiftRight(2);
BigInteger k = u.shiftLeft(1).add(ECConstants.ONE);
BigInteger Q = this.x;
BigInteger fourQ = Q.shiftLeft(2).mod(q);
BigInteger U, V;
do
{
Random rand = new Random();
BigInteger P;
do
{
P = new BigInteger(q.bitLength(), rand);
}
while (P.compareTo(q) >= 0
|| !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, q).equals(qMinusOne)));
BigInteger[] result = lucasSequence(q, P, Q, k);
U = result[0];
V = result[1];
if (V.multiply(V).mod(q).equals(fourQ))
{
// Integer division by 2, mod q
if (V.testBit(0))
{
V = V.add(q);
}
V = V.shiftRight(1);
//assert V.multiply(V).mod(q).equals(x);
return new ECFieldElement.Fp(q, V);
}
}
while (U.equals(ECConstants.ONE) || U.equals(qMinusOne));
return null;
// BigInteger qMinusOne = q.subtract(ECConstants.ONE);
// BigInteger legendreExponent = qMinusOne.shiftRight(1); //divide(ECConstants.TWO);
// if (!(x.modPow(legendreExponent, q).equals(ECConstants.ONE)))
// {
// return null;
// }
//
// Random rand = new Random();
// BigInteger fourX = x.shiftLeft(2);
//
// BigInteger r;
// do
// {
// r = new BigInteger(q.bitLength(), rand);
// }
// while (r.compareTo(q) >= 0
// || !(r.multiply(r).subtract(fourX).modPow(legendreExponent, q).equals(qMinusOne)));
//
// BigInteger n1 = qMinusOne.shiftRight(2); //.divide(ECConstants.FOUR);
// BigInteger n2 = n1.add(ECConstants.ONE); //q.add(ECConstants.THREE).divide(ECConstants.FOUR);
//
// BigInteger wOne = WOne(r, x, q);
// BigInteger wSum = W(n1, wOne, q).add(W(n2, wOne, q)).mod(q);
// BigInteger twoR = r.shiftLeft(1); //ECConstants.TWO.multiply(r);
//
// BigInteger root = twoR.modPow(q.subtract(ECConstants.TWO), q)
// .multiply(x).mod(q)
// .multiply(wSum).mod(q);
//
// return new Fp(q, root);
}
// private static BigInteger W(BigInteger n, BigInteger wOne, BigInteger p)
// {
// if (n.equals(ECConstants.ONE))
// {
// return wOne;
// }
// boolean isEven = !n.testBit(0);
// n = n.shiftRight(1);//divide(ECConstants.TWO);
// if (isEven)
// {
// BigInteger w = W(n, wOne, p);
// return w.multiply(w).subtract(ECConstants.TWO).mod(p);
// }
// BigInteger w1 = W(n.add(ECConstants.ONE), wOne, p);
// BigInteger w2 = W(n, wOne, p);
// return w1.multiply(w2).subtract(wOne).mod(p);
// }
//
// private BigInteger WOne(BigInteger r, BigInteger x, BigInteger p)
// {
// return r.multiply(r).multiply(x.modPow(q.subtract(ECConstants.TWO), q)).subtract(ECConstants.TWO).mod(p);
// }
private static BigInteger[] lucasSequence(
BigInteger p,
BigInteger P,
BigInteger Q,
BigInteger k)
{
int n = k.bitLength();
int s = k.getLowestSetBit();
BigInteger Uh = ECConstants.ONE;
BigInteger Vl = ECConstants.TWO;
BigInteger Vh = P;
BigInteger Ql = ECConstants.ONE;
BigInteger Qh = ECConstants.ONE;
for (int j = n - 1; j >= s + 1; --j)
{
Ql = Ql.multiply(Qh).mod(p);
if (k.testBit(j))
{
Qh = Ql.multiply(Q).mod(p);
Uh = Uh.multiply(Vh).mod(p);
Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p);
Vh = Vh.multiply(Vh).subtract(Qh.shiftLeft(1)).mod(p);
}
else
{
Qh = Ql;
Uh = Uh.multiply(Vl).subtract(Ql).mod(p);
Vh = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p);
Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p);
}
}
Ql = Ql.multiply(Qh).mod(p);
Qh = Ql.multiply(Q).mod(p);
Uh = Uh.multiply(Vl).subtract(Ql).mod(p);
Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p);
Ql = Ql.multiply(Qh).mod(p);
for (int j = 1; j <= s; ++j)
{
Uh = Uh.multiply(Vl).mod(p);
Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p);
Ql = Ql.multiply(Ql).mod(p);
}
return new BigInteger[]{ Uh, Vl };
}
public boolean equals(Object other)
{
if (other == this)
{
return true;
}
if (!(other instanceof ECFieldElement.Fp))
{
return false;
}
ECFieldElement.Fp o = (ECFieldElement.Fp)other;
return q.equals(o.q) && x.equals(o.x);
}
public int hashCode()
{
return q.hashCode() ^ x.hashCode();
}
}
/**
* Class representing the Elements of the finite field
* <code>F<sub>2<sup>m</sup></sub></code> in polynomial basis (PB)
* representation. Both trinomial (TPB) and pentanomial (PPB) polynomial
* basis representations are supported. Gaussian normal basis (GNB)
* representation is not supported.
*/
public static class F2m extends ECFieldElement
{
/**
* Indicates gaussian normal basis representation (GNB). Number chosen
* according to X9.62. GNB is not implemented at present.
*/
public static final int GNB = 1;
/**
* Indicates trinomial basis representation (TPB). Number chosen
* according to X9.62.
*/
public static final int TPB = 2;
/**
* Indicates pentanomial basis representation (PPB). Number chosen
* according to X9.62.
*/
public static final int PPB = 3;
/**
* TPB or PPB.
*/
private int representation;
/**
* The exponent <code>m</code> of <code>F<sub>2<sup>m</sup></sub></code>.
*/
private int m;
/**
* TPB: The integer <code>k</code> where <code>x<sup>m</sup> +
* x<sup>k</sup> + 1</code> represents the reduction polynomial
* <code>f(z)</code>.<br>
* PPB: The integer <code>k1</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br>
*/
private int k1;
/**
* TPB: Always set to <code>0</code><br>
* PPB: The integer <code>k2</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br>
*/
private int k2;
/**
* TPB: Always set to <code>0</code><br>
* PPB: The integer <code>k3</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br>
*/
private int k3;
/**
* Constructor for PPB.
* @param m The exponent <code>m</code> of
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param x The BigInteger representing the value of the field element.
*/
public F2m(
int m,
int k1,
int k2,
int k3,
BigInteger x)
{
super(x);
if ((k2 == 0) && (k3 == 0))
{
this.representation = TPB;
}
else
{
if (k2 >= k3)
{
throw new IllegalArgumentException(
"k2 must be smaller than k3");
}
if (k2 <= 0)
{
throw new IllegalArgumentException(
"k2 must be larger than 0");
}
this.representation = PPB;
}
if (x.signum() < 0)
{
throw new IllegalArgumentException("x value cannot be negative");
}
this.m = m;
this.k1 = k1;
this.k2 = k2;
this.k3 = k3;
}
/**
* Constructor for TPB.
* @param m The exponent <code>m</code> of
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param k The integer <code>k</code> where <code>x<sup>m</sup> +
* x<sup>k</sup> + 1</code> represents the reduction
* polynomial <code>f(z)</code>.
* @param x The BigInteger representing the value of the field element.
*/
public F2m(int m, int k, BigInteger x)
{
// Set k1 to k, and set k2 and k3 to 0
this(m, k, 0, 0, x);
}
public String getFieldName()
{
return "F2m";
}
/**
* Checks, if the ECFieldElements <code>a</code> and <code>b</code>
* are elements of the same field <code>F<sub>2<sup>m</sup></sub></code>
* (having the same representation).
* @param a
* @param b
* @throws IllegalArgumentException if <code>a</code> and <code>b</code>
* are not elements of the same field
* <code>F<sub>2<sup>m</sup></sub></code> (having the same
* representation).
*/
public static void checkFieldElements(
ECFieldElement a,
ECFieldElement b)
{
if ((!(a instanceof F2m)) || (!(b instanceof F2m)))
{
throw new IllegalArgumentException("Field elements are not "
+ "both instances of ECFieldElement.F2m");
}
if ((a.x.signum() < 0) || (b.x.signum() < 0))
{
throw new IllegalArgumentException(
"x value may not be negative");
}
ECFieldElement.F2m aF2m = (ECFieldElement.F2m)a;
ECFieldElement.F2m bF2m = (ECFieldElement.F2m)b;
if ((aF2m.m != bF2m.m) || (aF2m.k1 != bF2m.k1)
|| (aF2m.k2 != bF2m.k2) || (aF2m.k3 != bF2m.k3))
{
throw new IllegalArgumentException("Field elements are not "
+ "elements of the same field F2m");
}
if (aF2m.representation != bF2m.representation)
{
// Should never occur
throw new IllegalArgumentException(
"One of the field "
+ "elements are not elements has incorrect representation");
}
}
/**
* Computes <code>z * a(z) mod f(z)</code>, where <code>f(z)</code> is
* the reduction polynomial of <code>this</code>.
* @param a The polynomial <code>a(z)</code> to be multiplied by
* <code>z mod f(z)</code>.
* @return <code>z * a(z) mod f(z)</code>
*/
private BigInteger multZModF(final BigInteger a)
{
// Left-shift of a(z)
BigInteger az = a.shiftLeft(1);
if (az.testBit(this.m))
{
// If the coefficient of z^m in a(z) equals 1, reduction
// modulo f(z) is performed: Add f(z) to to a(z):
// Step 1: Unset mth coeffient of a(z)
az = az.clearBit(this.m);
// Step 2: Add r(z) to a(z), where r(z) is defined as
// f(z) = z^m + r(z), and k1, k2, k3 are the positions of
// the non-zero coefficients in r(z)
az = az.flipBit(0);
az = az.flipBit(this.k1);
if (this.representation == PPB)
{
az = az.flipBit(this.k2);
az = az.flipBit(this.k3);
}
}
return az;
}
public ECFieldElement add(final ECFieldElement b)
{
// No check performed here for performance reasons. Instead the
// elements involved are checked in ECPoint.F2m
// checkFieldElements(this, b);
return new F2m(this.m, this.k1, this.k2, this.k3, this.x.xor(b.x));
}
public ECFieldElement subtract(final ECFieldElement b)
{
// Addition and subtraction are the same in F2m
return add(b);
}
public ECFieldElement multiply(final ECFieldElement b)
{
// Left-to-right shift-and-add field multiplication in F2m
// Input: Binary polynomials a(z) and b(z) of degree at most m-1
// Output: c(z) = a(z) * b(z) mod f(z)
// No check performed here for performance reasons. Instead the
// elements involved are checked in ECPoint.F2m
// checkFieldElements(this, b);
final BigInteger az = this.x;
BigInteger bz = b.x;
BigInteger cz;
// Compute c(z) = a(z) * b(z) mod f(z)
if (az.testBit(0))
{
cz = bz;
}
else
{
cz = ECConstants.ZERO;
}
for (int i = 1; i < this.m; i++)
{
// b(z) := z * b(z) mod f(z)
bz = multZModF(bz);
if (az.testBit(i))
{
// If the coefficient of x^i in a(z) equals 1, b(z) is added
// to c(z)
cz = cz.xor(bz);
}
}
return new ECFieldElement.F2m(m, this.k1, this.k2, this.k3, cz);
}
public ECFieldElement divide(final ECFieldElement b)
{
// There may be more efficient implementations
ECFieldElement bInv = b.invert();
return multiply(bInv);
}
public ECFieldElement negate()
{
// -x == x holds for all x in F2m, hence a copy of this is returned
return new F2m(this.m, this.k1, this.k2, this.k3, this.x);
}
public ECFieldElement square()
{
// Naive implementation, can probably be speeded up using modular
// reduction
return multiply(this);
}
public ECFieldElement invert()
{
// Inversion in F2m using the extended Euclidean algorithm
// Input: A nonzero polynomial a(z) of degree at most m-1
// Output: a(z)^(-1) mod f(z)
// u(z) := a(z)
BigInteger uz = this.x;
if (uz.signum() <= 0)
{
throw new ArithmeticException("x is zero or negative, " +
"inversion is impossible");
}
// v(z) := f(z)
BigInteger vz = ECConstants.ONE.shiftLeft(m);
vz = vz.setBit(0);
vz = vz.setBit(this.k1);
if (this.representation == PPB)
{
vz = vz.setBit(this.k2);
vz = vz.setBit(this.k3);
}
// g1(z) := 1, g2(z) := 0
BigInteger g1z = ECConstants.ONE;
BigInteger g2z = ECConstants.ZERO;
// while u != 1
while (!(uz.equals(ECConstants.ZERO)))
{
// j := deg(u(z)) - deg(v(z))
int j = uz.bitLength() - vz.bitLength();
// If j < 0 then: u(z) <-> v(z), g1(z) <-> g2(z), j := -j
if (j < 0)
{
final BigInteger uzCopy = uz;
uz = vz;
vz = uzCopy;
final BigInteger g1zCopy = g1z;
g1z = g2z;
g2z = g1zCopy;
j = -j;
}
// u(z) := u(z) + z^j * v(z)
// Note, that no reduction modulo f(z) is required, because
// deg(u(z) + z^j * v(z)) <= max(deg(u(z)), j + deg(v(z)))
// = max(deg(u(z)), deg(u(z)) - deg(v(z)) + deg(v(z))
// = deg(u(z))
uz = uz.xor(vz.shiftLeft(j));
// g1(z) := g1(z) + z^j * g2(z)
g1z = g1z.xor(g2z.shiftLeft(j));
// if (g1z.bitLength() > this.m) {
// throw new ArithmeticException(
// "deg(g1z) >= m, g1z = " + g1z.toString(2));
// }
}
return new ECFieldElement.F2m(
this.m, this.k1, this.k2, this.k3, g2z);
}
public ECFieldElement sqrt()
{
throw new RuntimeException("Not implemented");
}
/**
* @return the representation of the field
* <code>F<sub>2<sup>m</sup></sub></code>, either of
* TPB (trinomial
* basis representation) or
* PPB (pentanomial
* basis representation).
*/
public int getRepresentation()
{
return this.representation;
}
/**
* @return the degree <code>m</code> of the reduction polynomial
* <code>f(z)</code>.
*/
public int getM()
{
return this.m;
}
/**
* @return TPB: The integer <code>k</code> where <code>x<sup>m</sup> +
* x<sup>k</sup> + 1</code> represents the reduction polynomial
* <code>f(z)</code>.<br>
* PPB: The integer <code>k1</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br>
*/
public int getK1()
{
return this.k1;
}
/**
* @return TPB: Always returns <code>0</code><br>
* PPB: The integer <code>k2</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br>
*/
public int getK2()
{
return this.k2;
}
/**
* @return TPB: Always set to <code>0</code><br>
* PPB: The integer <code>k3</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br>
*/
public int getK3()
{
return this.k3;
}
public boolean equals(Object anObject)
{
if (anObject == this)
{
return true;
}
if (!(anObject instanceof ECFieldElement.F2m))
{
return false;
}
ECFieldElement.F2m b = (ECFieldElement.F2m)anObject;
return ((this.m == b.m) && (this.k1 == b.k1) && (this.k2 == b.k2)
&& (this.k3 == b.k3)
&& (this.representation == b.representation)
&& (this.x.equals(b.x)));
}
public int hashCode()
{
return x.hashCode() ^ m ^ k1 ^ k2 ^ k3;
}
}
}
| A couple of small optimisations
| src/org/bouncycastle/math/ec/ECFieldElement.java | A couple of small optimisations | |
Java | mit | 7e6b6bd22b02c3540ea820ee1454ef450d1e5004 | 0 | team1306/Robot2016 |
package org.usfirst.frc.team1306.robot;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Robot extends IterativeRobot {
//this is a test comment
Command autonomousCommand;
SendableChooser chooser;
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
chooser = new SendableChooser();
// chooser.addObject("My Auto", new MyAutoCommand());
SmartDashboard.putData("Auto mode", chooser);
}
/**
* This function is called once each time the robot enters Disabled mode.
* You can use it to reset any subsystem information you want to clear when
* the robot is disabled.
*/
public void disabledInit(){
}
public void disabledPeriodic() {
Scheduler.getInstance().run();
}
/**
* This autonomous (along with the chooser code above) shows how to select between different autonomous modes
* using the dashboard. The sendable chooser code works with the Java SmartDashboard. If you prefer the LabVIEW
* Dashboard, remove all of the chooser code and uncomment the getString code to get the auto name from the text box
* below the Gyro
*
* You can add additional auto modes by adding additional commands to the chooser code above (like the commented example)
* or additional comparisons to the switch structure below with additional strings & commands.
*/
public void autonomousInit() {
autonomousCommand = (Command) chooser.getSelected();
/* String autoSelected = SmartDashboard.getString("Auto Selector", "Default");
switch(autoSelected) {
case "My Auto":
autonomousCommand = new MyAutoCommand();
break;
case "Default Auto":
default:
autonomousCommand = new ExampleCommand();
break;
} */
// schedule the autonomous command (example)
if (autonomousCommand != null) autonomousCommand.start();
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
Scheduler.getInstance().run();
}
public void teleopInit() {
// This makes sure that the autonomous stops running when
// teleop starts running. If you want the autonomous to
// continue until interrupted by another command, remove
// this line or comment it out.
if (autonomousCommand != null) autonomousCommand.cancel();
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
Scheduler.getInstance().run();
}
/**
* This function is called periodically during test mode
*/
public void testPeriodic() {
LiveWindow.run();
}
}
| src/org/usfirst/frc/team1306/robot/Robot.java |
package org.usfirst.frc.team1306.robot;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Robot extends IterativeRobot {
Command autonomousCommand;
SendableChooser chooser;
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
chooser = new SendableChooser();
// chooser.addObject("My Auto", new MyAutoCommand());
SmartDashboard.putData("Auto mode", chooser);
}
/**
* This function is called once each time the robot enters Disabled mode.
* You can use it to reset any subsystem information you want to clear when
* the robot is disabled.
*/
public void disabledInit(){
}
public void disabledPeriodic() {
Scheduler.getInstance().run();
}
/**
* This autonomous (along with the chooser code above) shows how to select between different autonomous modes
* using the dashboard. The sendable chooser code works with the Java SmartDashboard. If you prefer the LabVIEW
* Dashboard, remove all of the chooser code and uncomment the getString code to get the auto name from the text box
* below the Gyro
*
* You can add additional auto modes by adding additional commands to the chooser code above (like the commented example)
* or additional comparisons to the switch structure below with additional strings & commands.
*/
public void autonomousInit() {
autonomousCommand = (Command) chooser.getSelected();
/* String autoSelected = SmartDashboard.getString("Auto Selector", "Default");
switch(autoSelected) {
case "My Auto":
autonomousCommand = new MyAutoCommand();
break;
case "Default Auto":
default:
autonomousCommand = new ExampleCommand();
break;
} */
// schedule the autonomous command (example)
if (autonomousCommand != null) autonomousCommand.start();
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
Scheduler.getInstance().run();
}
public void teleopInit() {
// This makes sure that the autonomous stops running when
// teleop starts running. If you want the autonomous to
// continue until interrupted by another command, remove
// this line or comment it out.
if (autonomousCommand != null) autonomousCommand.cancel();
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
Scheduler.getInstance().run();
}
/**
* This function is called periodically during test mode
*/
public void testPeriodic() {
LiveWindow.run();
}
}
| test1
| src/org/usfirst/frc/team1306/robot/Robot.java | test1 | |
Java | mit | 5c59f6770b02218e0b0236e1021cec333eab3963 | 0 | amarts/robolectric,erichaugh/robolectric,plackemacher/robolectric,ecgreb/robolectric,wyvx/robolectric,yuzhong-google/robolectric,amarts/robolectric,tyronen/robolectric,karlicoss/robolectric,jingle1267/robolectric,gb112211/robolectric,WonderCsabo/robolectric,tyronen/robolectric,tmrudick/robolectric,spotify/robolectric,zhongyu05/robolectric,trevorrjohn/robolectric,ChengCorp/robolectric,ocadotechnology/robolectric,holmari/robolectric,davidsun/robolectric,macklinu/robolectric,charlesmunger/robolectric,holmari/robolectric,gruszczy/robolectric,jongerrish/robolectric,ecgreb/robolectric,pivotal-oscar/robolectric,hgl888/robolectric,charlesmunger/robolectric,tec27/robolectric,rossimo/robolectric,cc12703/robolectric,spotify/robolectric,holmari/robolectric,yuzhong-google/robolectric,karlicoss/robolectric,davidsun/robolectric,tec27/robolectric,trevorrjohn/robolectric,gabrielduque/robolectric,zhongyu05/robolectric,eric-kansas/robolectric,gruszczy/robolectric,wyvx/robolectric,tuenti/robolectric,svenji/robolectric,jongerrish/robolectric,gabrielduque/robolectric,macklinu/robolectric,daisy1754/robolectric,rburgst/robolectric,cc12703/robolectric,spotify/robolectric,cc12703/robolectric,rburgst/robolectric,zbsz/robolectric,ecgreb/robolectric,trevorrjohn/robolectric,toluju/robolectric,paulpv/robolectric,macklinu/robolectric,tyronen/robolectric,yuzhong-google/robolectric,1zaman/robolectric,rburgst/robolectric,karlicoss/robolectric,charlesmunger/robolectric,rongou/robolectric,kriegfrj/robolectric,pivotal-oscar/robolectric,rossimo/robolectric,fiower/robolectric,WonderCsabo/robolectric,fiower/robolectric,wyvx/robolectric,zhongyu05/robolectric,VikingDen/robolectric,tjohn/robolectric,gb112211/robolectric,davidsun/robolectric,plackemacher/robolectric,hgl888/robolectric,lexs/robolectric,eric-kansas/robolectric,tec27/robolectric,mag/robolectric,rossimo/robolectric,ocadotechnology/robolectric,kriegfrj/robolectric,eric-kansas/robolectric,jongerrish/robolectric,fiower/robolectric,svenji/robolectric,1zaman/robolectric,WonderCsabo/robolectric,mag/robolectric,daisy1754/robolectric,gruszczy/robolectric,daisy1754/robolectric,rongou/robolectric,rongou/robolectric,jingle1267/robolectric,1zaman/robolectric,cesar1000/robolectric,paulpv/robolectric,amarts/robolectric,jongerrish/robolectric,tmrudick/robolectric,tjohn/robolectric,jingle1267/robolectric,hgl888/robolectric,tmrudick/robolectric,zbsz/robolectric,lexs/robolectric,plackemacher/robolectric,VikingDen/robolectric,tuenti/robolectric,paulpv/robolectric,diegotori/robolectric,zbsz/robolectric,tjohn/robolectric,ChengCorp/robolectric,mag/robolectric,erichaugh/robolectric,gabrielduque/robolectric,cesar1000/robolectric,svenji/robolectric,ChengCorp/robolectric,VikingDen/robolectric,toluju/robolectric,diegotori/robolectric,cesar1000/robolectric,gb112211/robolectric,lexs/robolectric,pivotal-oscar/robolectric,toluju/robolectric,erichaugh/robolectric,ocadotechnology/robolectric,kriegfrj/robolectric,tuenti/robolectric,diegotori/robolectric | package com.xtremelabs.robolectric.tester.android.database;
import android.net.Uri;
import java.util.ArrayList;
import java.util.List;
public class SimpleTestCursor extends TestCursor {
public Uri uri;
public String[] projection;
public String selection;
public String[] selectionArgs;
public String sortOrder;
protected Object[][] results = new Object[0][0];
protected List<String> columnNames= new ArrayList<String>();
int resultsIndex = -1;
boolean closeWasCalled;
@Override
public void setQuery(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
this.uri = uri;
this.projection = projection;
this.selection = selection;
this.selectionArgs = selectionArgs;
this.sortOrder = sortOrder;
}
@Override
public int getColumnIndex(String columnName) {
return columnNames.indexOf(columnName);
}
@Override
public String getString(int columnIndex) {
return (String) results[resultsIndex][columnIndex];
}
@Override
public long getLong(int columnIndex) {
return (Long) results[resultsIndex][columnIndex];
}
@Override
public boolean moveToNext() {
++resultsIndex;
return resultsIndex < results.length;
}
@Override
public void close() {
closeWasCalled = true;
}
public void setColumnNames(ArrayList<String> columnNames) {
this.columnNames = columnNames;
}
public void setResults(Object[][] results) {
this.results = results;
}
public boolean getCloseWasCalled() {
return closeWasCalled;
}
}
| src/main/java/com/xtremelabs/robolectric/tester/android/database/SimpleTestCursor.java | package com.xtremelabs.robolectric.tester.android.database;
import android.net.Uri;
import java.util.ArrayList;
import java.util.List;
public class SimpleTestCursor extends TestCursor {
public Uri uri;
public String[] projection;
public String selection;
public String[] selectionArgs;
public String sortOrder;
Object[][] results = new Object[0][0];
List<String> columnNames= new ArrayList<String>();
int resultsIndex = -1;
boolean closeWasCalled;
@Override
public void setQuery(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
this.uri = uri;
this.projection = projection;
this.selection = selection;
this.selectionArgs = selectionArgs;
this.sortOrder = sortOrder;
}
@Override
public int getColumnIndex(String columnName) {
return columnNames.indexOf(columnName);
}
@Override
public String getString(int columnIndex) {
return (String) results[resultsIndex][columnIndex];
}
@Override
public long getLong(int columnIndex) {
return (Long) results[resultsIndex][columnIndex];
}
@Override
public boolean moveToNext() {
++resultsIndex;
return resultsIndex < results.length;
}
@Override
public void close() {
closeWasCalled = true;
}
public void setColumnNames(ArrayList<String> columnNames) {
this.columnNames = columnNames;
}
public void setResults(Object[][] results) {
this.results = results;
}
public boolean getCloseWasCalled() {
return closeWasCalled;
}
}
| Update src/main/java/com/xtremelabs/robolectric/tester/android/database/SimpleTestCursor.java
Added "protected" to results and columnNames to make it easier to subclass | src/main/java/com/xtremelabs/robolectric/tester/android/database/SimpleTestCursor.java | Update src/main/java/com/xtremelabs/robolectric/tester/android/database/SimpleTestCursor.java | |
Java | mit | f87a042d46970d1337820d10b1e4b42bce084368 | 0 | kmdouglass/Micro-Manager,kmdouglass/Micro-Manager |
/*
* HyperstackControls.java
*
* Created on Jul 15, 2010, 2:54:37 PM
*/
package org.micromanager.imagedisplay;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import com.swtdesigner.SwingResourceManager;
import ij.ImagePlus;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentAdapter;
import java.awt.FlowLayout;
import java.awt.Font;
import java.lang.Math;
import java.text.ParseException;
import java.util.concurrent.TimeUnit;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import net.miginfocom.swing.MigLayout;
import org.json.JSONException;
import org.json.JSONObject;
import org.micromanager.internalinterfaces.DisplayControls;
import org.micromanager.internalinterfaces.LiveModeListener;
import org.micromanager.MMStudio;
import org.micromanager.utils.MDUtils;
import org.micromanager.utils.NumberUtils;
import org.micromanager.utils.ReportingUtils;
public class HyperstackControls extends DisplayControls implements LiveModeListener {
private final static int DEFAULT_FPS = 10;
private final static double MAX_FPS = 5000;
// Height in pixels of our controls, not counting scrollbars.
private final static int CONTROLS_HEIGHT = 65;
private final VirtualAcquisitionDisplay display_;
private EventBus bus_;
// Last known mouse positions.
private int mouseX_ = -1;
private int mouseY_ = -1;
// JPanel that holds all controls.
private JPanel subPanel_;
// Controls common to both control sets
private ScrollerPanel scrollerPanel_;
private JLabel pixelInfoLabel_;
// Displays information on the currently-displayed image.
private JLabel imageInfoLabel_;
// Displays the countdown to the next frame.
private JLabel countdownLabel_;
private JButton showFolderButton_;
private JButton saveButton_;
private JLabel fpsLabel_;
// Standard control set
private javax.swing.JTextField fpsField_;
private JButton abortButton_;
private javax.swing.JToggleButton pauseAndResumeToggleButton_;
// Snap/live control set
private JButton snapButton_;
private JButton snapToAlbumButton_;
private JButton liveButton_;
/**
* @param shouldUseLiveControls - indicates if we should use the buttons for
* the "Snap/Live" window or the buttons for normal displays.
* @param isAcquisition - indicates if we should auto-size the scrollbars
* to the dataset or not (in an acquisition we resize them as images
* come in, instead).
*/
public HyperstackControls(VirtualAcquisitionDisplay display,
EventBus bus, boolean shouldUseLiveControls, boolean isAcquisition) {
super(new FlowLayout(FlowLayout.LEADING));
bus_ = bus;
initComponents(display, shouldUseLiveControls, isAcquisition);
display_ = display;
bus_.register(this);
MMStudio.getInstance().getSnapLiveManager().addLiveModeListener(this);
}
private void initComponents(VirtualAcquisitionDisplay display,
final boolean shouldUseLiveControls, boolean isAcquisition) {
// This layout minimizes space between components.
subPanel_ = new JPanel(new MigLayout("insets 0, fillx, align center"));
JPanel labelsPanel = new JPanel(new MigLayout("insets 0"));
pixelInfoLabel_ = new JLabel(" ");
pixelInfoLabel_.setMinimumSize(new Dimension(150, 10));
pixelInfoLabel_.setFont(new java.awt.Font("Lucida Grande", 0, 10));
labelsPanel.add(pixelInfoLabel_);
imageInfoLabel_ = new JLabel(" ");
imageInfoLabel_.setMinimumSize(new Dimension(150, 10));
imageInfoLabel_.setFont(new java.awt.Font("Lucida Grande", 0, 10));
labelsPanel.add(imageInfoLabel_);
countdownLabel_ = new JLabel(" ");
countdownLabel_.setMinimumSize(new Dimension(150, 10));
countdownLabel_.setFont(new java.awt.Font("Lucida Grande", 0, 10));
labelsPanel.add(countdownLabel_);
subPanel_.add(labelsPanel, "span, growx, align center, wrap");
// During an acquisition, we want the scrollbars to grow automatically
// as new images show up. When showing a fixed dataset, though, we want
// to show all the available image coordinates from the start.
int numChannels = 0, numFrames = 0, numSlices = 0, numPositions = 0;
if (!isAcquisition) {
// Loading a proper dataset; extract the dataset dimensions from the
// metadata.
numChannels = display.getNumChannels();
// We use a special method to get the number of frames, since the
// display object will just return the claimed number of frames,
// which may be inaccurate if e.g. acquisition was aborted partway
// through the experiment.
// TODO: should we be using similar methods for other axes?
numFrames = display.getImageCache().lastAcquiredFrame() + 1;
numSlices = display.getNumSlices();
// Positions have to be handled specially, since our display doesn't
// actually know about them -- it normally relies on us!
JSONObject tags = display.getImageCache().getSummaryMetadata();
numPositions = 0;
try {
numPositions = MDUtils.getNumPositions(tags);
}
catch (JSONException e) {
// Oh well, no positions for us.
}
}
scrollerPanel_ = new ScrollerPanel(
bus_, new String[]{"channel", "position", "time", "z"},
new Integer[]{numChannels, numPositions, numFrames, numSlices},
DEFAULT_FPS);
subPanel_.add(scrollerPanel_, "span, growx, wrap 0px");
// Hacky layout to minimize gaps between components.
JPanel buttonPanel = new JPanel(new MigLayout("insets 0",
"[]0[]0[]0[]0[]0[]"));
showFolderButton_ = new JButton();
saveButton_ = new JButton();
buttonPanel.add(showFolderButton_);
buttonPanel.add(saveButton_);
showFolderButton_.setBackground(new java.awt.Color(255, 255, 255));
showFolderButton_.setIcon(
new javax.swing.ImageIcon(
getClass().getResource("/org/micromanager/icons/folder.png")));
showFolderButton_.setToolTipText("Show containing folder");
showFolderButton_.setFocusable(false);
showFolderButton_.setHorizontalTextPosition(
javax.swing.SwingConstants.CENTER);
showFolderButton_.setMaximumSize(new java.awt.Dimension(30, 28));
showFolderButton_.setMinimumSize(new java.awt.Dimension(30, 28));
showFolderButton_.setPreferredSize(new java.awt.Dimension(30, 28));
showFolderButton_.setVerticalTextPosition(
javax.swing.SwingConstants.BOTTOM);
showFolderButton_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showFolderButtonActionPerformed(evt);
}
});
saveButton_.setBackground(new java.awt.Color(255, 255, 255));
saveButton_.setIcon(
new javax.swing.ImageIcon(
getClass().getResource("/org/micromanager/icons/disk.png")));
saveButton_.setToolTipText("Save as...");
saveButton_.setFocusable(false);
saveButton_.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
saveButton_.setMaximumSize(new java.awt.Dimension(30, 28));
saveButton_.setMinimumSize(new java.awt.Dimension(30, 28));
saveButton_.setPreferredSize(new java.awt.Dimension(30, 28));
saveButton_.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
saveButton_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveButtonActionPerformed(evt, shouldUseLiveControls);
}
});
// This control is added by both Snap/Live, and Standard, but in
// different places on each.
fpsLabel_ = new JLabel(" ", SwingConstants.RIGHT);
fpsLabel_.setFont(new java.awt.Font("Lucida Grande", 0, 10));
fpsLabel_.setFocusable(false);
if (shouldUseLiveControls) {
makeSnapLiveControls(buttonPanel);
}
else {
makeStandardControls(buttonPanel);
}
subPanel_.add(buttonPanel);
add(subPanel_);
// Propagate resizing through to our JPanel, adjusting slightly the
// amount of space we give them to create a border.
addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
Dimension curSize = getSize();
subPanel_.setSize(new Dimension(curSize.width - 10, curSize.height - 10));
invalidate();
validate();
}
});
}
/**
* Generate the controls used for the "Snap/Live" window.
*/
private void makeSnapLiveControls(JPanel buttonPanel) {
snapButton_ = new JButton();
snapButton_.setFocusable(false);
snapButton_.setIconTextGap(6);
snapButton_.setText("Snap");
snapButton_.setMinimumSize(new Dimension(90,28));
snapButton_.setPreferredSize(new Dimension(90,28));
snapButton_.setMaximumSize(new Dimension(90,28));
snapButton_.setIcon(SwingResourceManager.getIcon(
MMStudio.class, "/org/micromanager/icons/camera.png"));
snapButton_.setFont(new Font("Arial", Font.PLAIN, 10));
snapButton_.setToolTipText("Snap single image");
snapButton_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MMStudio.getInstance().doSnap();
}
});
liveButton_ = new JButton();
liveButton_.setIcon(SwingResourceManager.getIcon(
MMStudio.class,
"/org/micromanager/icons/camera_go.png"));
liveButton_.setIconTextGap(6);
liveButton_.setText("Live");
liveButton_.setMinimumSize(new Dimension(90,28));
liveButton_.setPreferredSize(new Dimension(90,28));
liveButton_.setMaximumSize(new Dimension(90,28));
liveButton_.setFocusable(false);
liveButton_.setToolTipText("Continuous live view");
liveButton_.setFont(new Font("Arial", Font.PLAIN, 10));
liveButton_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
liveButtonAction();
}
});
snapToAlbumButton_ = new JButton("Album");
snapToAlbumButton_.setIcon(SwingResourceManager.getIcon(MMStudio.class,
"/org/micromanager/icons/arrow_right.png"));
snapToAlbumButton_.setIconTextGap(6);
snapToAlbumButton_.setToolTipText("Add current image to album");
snapToAlbumButton_.setFocusable(false);
snapToAlbumButton_.setMaximumSize(new Dimension(90, 28));
snapToAlbumButton_.setMinimumSize(new Dimension(90, 28));
snapToAlbumButton_.setPreferredSize(new Dimension(90, 28));
snapToAlbumButton_.setFont(new Font("Arial", Font.PLAIN, 10));
snapToAlbumButton_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
snapToAlbumButtonActionPerformed();
}
});
buttonPanel.add(snapButton_);
buttonPanel.add(liveButton_);
buttonPanel.add(snapToAlbumButton_);
fpsLabel_.setText(" ");
buttonPanel.add(fpsLabel_, "span, wrap, width 120px, align right");
}
/**
* Generate the controls used on a standard dataset display (i.e. not the
* snap/live window).
*/
private void makeStandardControls(JPanel buttonPanel) {
fpsField_ = new javax.swing.JTextField(String.valueOf(DEFAULT_FPS), 4);
abortButton_ = new JButton();
pauseAndResumeToggleButton_ = new javax.swing.JToggleButton();
buttonPanel.add(abortButton_);
buttonPanel.add(pauseAndResumeToggleButton_);
// Make a new panel to hold the FPS info, since they need to be
// together.
JPanel fpsPanel = new JPanel(new MigLayout("insets 0"));
fpsPanel.add(fpsLabel_);
fpsPanel.add(fpsField_);
buttonPanel.add(fpsPanel, "span, gapleft push, wrap");
fpsField_.setToolTipText(
"Set the speed at which the acquisition is played back.");
fpsField_.addFocusListener(new java.awt.event.FocusAdapter() {
@Override
public void focusLost(java.awt.event.FocusEvent evt) {
fpsField_FocusLost(evt);
}
});
fpsField_.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyReleased(java.awt.event.KeyEvent evt) {
fpsField_KeyReleased(evt);
}
});
abortButton_.setBackground(new java.awt.Color(255, 255, 255));
abortButton_.setIcon(
new javax.swing.ImageIcon(
getClass().getResource("/org/micromanager/icons/cancel.png")));
abortButton_.setToolTipText("Stop acquisition");
abortButton_.setFocusable(false);
abortButton_.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
abortButton_.setMaximumSize(new java.awt.Dimension(30, 28));
abortButton_.setMinimumSize(new java.awt.Dimension(30, 28));
abortButton_.setPreferredSize(new java.awt.Dimension(30, 28));
abortButton_.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
abortButton_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
abortButtonActionPerformed(evt);
}
});
pauseAndResumeToggleButton_.setIcon(
new javax.swing.ImageIcon(getClass().getResource(
"/org/micromanager/icons/control_pause.png")));
pauseAndResumeToggleButton_.setToolTipText("Pause acquisition");
pauseAndResumeToggleButton_.setFocusable(false);
pauseAndResumeToggleButton_.setMargin(new java.awt.Insets(0, 0, 0, 0));
pauseAndResumeToggleButton_.setMaximumSize(new java.awt.Dimension(30, 28));
pauseAndResumeToggleButton_.setMinimumSize(new java.awt.Dimension(30, 28));
pauseAndResumeToggleButton_.setPreferredSize(
new java.awt.Dimension(30, 28));
pauseAndResumeToggleButton_.setPressedIcon(
new javax.swing.ImageIcon(getClass().getResource(
"/org/micromanager/icons/resultset_next.png")));
pauseAndResumeToggleButton_.setSelectedIcon(
new javax.swing.ImageIcon(getClass().getResource(
"/org/micromanager/icons/resultset_next.png")));
pauseAndResumeToggleButton_.addActionListener(
new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pauseAndResumeToggleButtonActionPerformed(evt);
}
});
}
/**
* User moused over the display; update our indication of pixel intensities.
* TODO: only providing the first intensity; what about multichannel
* images?
*/
@Subscribe
public void onMouseMoved(MouseIntensityEvent event) {
mouseX_ = event.x_;
mouseY_ = event.y_;
setPixelInfo(mouseX_, mouseY_, event.intensities_[0]);
}
/**
* Update our pixel info text.
*/
private void setPixelInfo(int x, int y, int intensity) {
pixelInfoLabel_.setText(String.format("x=%d, y=%d, value=%d",
x, y, intensity));
}
/**
* Our ScrollerPanel is informing us that we need to display a different
* image.
*/
@Subscribe
public void onSetImage(ScrollerPanel.SetImageEvent event) {
int position = -1;
int channel = -1;
int frame = -1;
int slice = -1;
try {
position = event.getPositionForAxis("position");
display_.updatePosition(position);
// Positions for ImageJ are 1-indexed but positions from the event are
// 0-indexed.
channel = event.getPositionForAxis("channel") + 1;
frame = event.getPositionForAxis("time") + 1;
slice = event.getPositionForAxis("z") + 1;
// Ensure that the ImagePlus thinks it is big enough for us to set
// its position correctly.
ImagePlus plus = display_.getHyperImage();
if (plus instanceof IMMImagePlus) {
IMMImagePlus tmp = (IMMImagePlus) plus;
if (plus.getNFrames() < frame) {
tmp.setNFramesUnverified(frame);
}
if (plus.getNChannels() < channel) {
tmp.setNChannelsUnverified(channel);
}
if (plus.getNSlices() < slice) {
tmp.setNSlicesUnverified(slice);
}
}
else { // Must be MMComposite Image
MMCompositeImage tmp = (MMCompositeImage) plus;
if (plus.getNFrames() < frame) {
tmp.setNFramesUnverified(frame);
}
if (plus.getNChannels() < channel) {
tmp.setNChannelsUnverified(channel);
}
if (plus.getNSlices() < slice) {
tmp.setNSlicesUnverified(slice);
}
}
plus.setPosition(channel, slice, frame);
display_.updateAndDraw(true);
}
catch (Exception e) {
// This can happen, rarely, with an ArrayIndexOutOfBoundsException
// in IJ code that draws the new image, called by way of the
// updatePosition() call above. No idea what causes it, but it's
// rare enough that debugging is a pain.
ReportingUtils.logError(e, String.format("Failed to set image at %d, %d, %d, %d", position, frame, slice, channel));
}
}
/**
* A new image has been made available. Update our pixel info, assuming
* we have a valid mouse position.
*/
@Subscribe
public void onNewImage(NewImageEvent event) {
if (mouseX_ != -1 && mouseY_ != -1) {
try {
int intensity = display_.getIntensityAt(mouseX_, mouseY_);
setPixelInfo(mouseX_, mouseY_, intensity);
}
catch (Exception e) {
ReportingUtils.logError(e, "Error in HyperstackControls onNewImage");
}
}
}
/**
* Our ScrollerPanel is informing us that its layout has changed.
*/
@Subscribe
public void onLayoutChange(ScrollerPanel.LayoutChangedEvent event) {
invalidate();
validate();
}
private void showFolderButtonActionPerformed(java.awt.event.ActionEvent evt) {
display_.showFolder();
}
private void fpsField_FocusLost(java.awt.event.FocusEvent evt) {
updateFPS();
}
private void fpsField_KeyReleased(java.awt.event.KeyEvent evt) {
updateFPS();
}
private void abortButtonActionPerformed(java.awt.event.ActionEvent evt) {
display_.abort();
}
private void pauseAndResumeToggleButtonActionPerformed(java.awt.event.ActionEvent evt) {
display_.pause();
}
private void saveButtonActionPerformed(java.awt.event.ActionEvent evt, final boolean isSimpleDisplay) {
new Thread() {
@Override
public void run() {
// We don't want to tie the Snap/Live display to a specific
// file since its contents get overwritten regularly.
display_.saveAs(!isSimpleDisplay);
}
}.start();
}
private void snapToAlbumButtonActionPerformed() {
try {
MMStudio gui = MMStudio.getInstance();
gui.copyFromLiveModeToAlbum(display_);
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
}
private void liveButtonAction() {
MMStudio.getInstance().enableLiveMode(!MMStudio.getInstance().isLiveModeOn());
}
private void updateFPS() {
// There's no FPS field when using the Snap/Live window
if (fpsField_ != null) {
try {
double fps = NumberUtils.displayStringToDouble(fpsField_.getText());
// Constrain the FPS to a sane range.
fps = Math.max(1.0, Math.min(fps, MAX_FPS));
scrollerPanel_.setFramesPerSecond(fps);
} catch (ParseException ex) {
// No recognizable number (e.g. because the field is empty); just
// do nothing.
}
}
}
@Override
public synchronized void setImageInfoLabel(String text) {
imageInfoLabel_.setText(text);
}
private void updateStatusLine(JSONObject tags) {
String status = "";
try {
String xyPosition;
try {
xyPosition = MDUtils.getPositionName(tags);
if (xyPosition != null && !xyPosition.contentEquals("null")) {
status += xyPosition + ", ";
}
} catch (Exception e) {
//Oh well...
}
try {
double seconds = MDUtils.getElapsedTimeMs(tags) / 1000;
status += elapsedTimeDisplayString(seconds);
} catch (JSONException ex) {
ReportingUtils.logError("MetaData did not contain ElapsedTime-ms field");
}
String zPosition;
try {
zPosition = NumberUtils.doubleToDisplayString(MDUtils.getZPositionUm(tags));
status += ", z: " + zPosition + " um";
} catch (Exception e) {
}
String chan;
try {
chan = MDUtils.getChannelName(tags);
if (chan != null && !chan.contentEquals("null")) {
status += ", " + chan;
}
} catch (Exception ex) {
}
setImageInfoLabel(status);
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
}
public static String elapsedTimeDisplayString(double seconds) {
// Use "12.34s" up to 60 s; "12m 34.56s" up to 1 h, and
// "1h 23m 45s" beyond that.
long wholeSeconds = (long) Math.floor(seconds);
double fraction = seconds - wholeSeconds;
long hours = TimeUnit.SECONDS.toHours(wholeSeconds);
wholeSeconds -= TimeUnit.HOURS.toSeconds(hours);
String hoursString = "";
if (hours > 0) {
hoursString = hours + "h ";
}
long minutes = TimeUnit.SECONDS.toMinutes(wholeSeconds);
wholeSeconds -= TimeUnit.MINUTES.toSeconds(minutes);
String minutesString = "";
if (minutes > 0) {
minutesString = minutes + "m ";
}
String secondsString;
if (hours == 0 && fraction > 0.01) {
secondsString = String.format("%.2fs", wholeSeconds + fraction);
}
else {
secondsString = wholeSeconds + "s";
}
return hoursString + minutesString + secondsString;
}
@Override
public void newImageUpdate(JSONObject tags) {
if (tags == null) {
return;
}
updateStatusLine(tags);
if (!display_.acquisitionIsRunning() || display_.getNextWakeTime() <= 0) {
// No acquisition to display a countdown for.
return;
}
final long nextImageTime = display_.getNextWakeTime();
if (System.nanoTime() / 1000000 >= nextImageTime) {
// Already past the next image time.
return;
}
// TODO: why the try/catch block here?
try {
final Timer timer = new Timer("Next frame display");
TimerTask task = new TimerTask() {
@Override
public void run() {
double timeRemainingS = (nextImageTime - System.nanoTime() / 1000000.0) / 1000;
if (timeRemainingS > 0 &&
display_.acquisitionIsRunning()) {
countdownLabel_.setText(
String.format("Next frame: %.2fs", timeRemainingS));
} else {
timer.cancel();
countdownLabel_.setText("");
}
}
};
timer.schedule(task, 500, 100);
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
}
@Override
public void acquiringImagesUpdate(boolean state) {
// NB currently there's no situation in which one of these will be null
// when the other isn't, but on the other hand who knows what the future
// will bring?
if (abortButton_ != null) {
abortButton_.setEnabled(state);
}
if (pauseAndResumeToggleButton_ != null) {
pauseAndResumeToggleButton_.setEnabled(state);
}
}
@Override
public void imagesOnDiskUpdate(boolean enabled) {
showFolderButton_.setEnabled(enabled);
}
public void prepareForClose() {
scrollerPanel_.prepareForClose();
bus_.unregister(this);
MMStudio.getInstance().getSnapLiveManager().removeLiveModeListener(this);
}
@Override
public void setPosition(int p) {
scrollerPanel_.setPosition("position", p);
}
@Override
public int getPosition() {
return scrollerPanel_.getPosition("position");
}
@Override
public void setChannel(int c) {
scrollerPanel_.setPosition("channel", c);
}
/**
* New information on our FPS; update a label.
*/
@Subscribe
public void onFPSUpdate(FPSEvent event) {
// Default to assuming we'll be blanking the label.
String newLabel = "";
if (event.getDataFPS() != 0) {
newLabel = String.format("FPS: %.1f (display %.1f)",
event.getDataFPS(), event.getDisplayFPS());
}
else if (fpsField_ != null) {
// No new data, but we do have an FPS text field for animations, so
// switch fpsLabel_ to being an indicator for that.
newLabel = "Playback FPS:";
}
fpsLabel_.setText(newLabel);
}
/**
* Live mode was toggled; if we have a "live mode" button, it needs to be
* toggled on/off; likewise, the Snap button should be disabled/enabled.
*/
public void liveModeEnabled(boolean isEnabled) {
if (liveButton_ == null) {
return;
}
String label = isEnabled ? "Stop Live" : "Live";
String iconPath = isEnabled ? "/org/micromanager/icons/cancel.png" : "/org/micromanager/icons/camera_go.png";
liveButton_.setIcon(
SwingResourceManager.getIcon(MMStudio.class, iconPath));
liveButton_.setText(label);
if (snapButton_ != null) {
snapButton_.setEnabled(!isEnabled);
}
}
public int getNumPositions() {
return scrollerPanel_.getMaxPosition("position");
}
}
| mmstudio/src/org/micromanager/imagedisplay/HyperstackControls.java |
/*
* HyperstackControls.java
*
* Created on Jul 15, 2010, 2:54:37 PM
*/
package org.micromanager.imagedisplay;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import com.swtdesigner.SwingResourceManager;
import ij.ImagePlus;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentAdapter;
import java.awt.FlowLayout;
import java.awt.Font;
import java.lang.Math;
import java.text.ParseException;
import java.util.concurrent.TimeUnit;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import net.miginfocom.swing.MigLayout;
import org.json.JSONException;
import org.json.JSONObject;
import org.micromanager.internalinterfaces.DisplayControls;
import org.micromanager.internalinterfaces.LiveModeListener;
import org.micromanager.MMStudio;
import org.micromanager.utils.MDUtils;
import org.micromanager.utils.NumberUtils;
import org.micromanager.utils.ReportingUtils;
public class HyperstackControls extends DisplayControls implements LiveModeListener {
private final static int DEFAULT_FPS = 10;
private final static double MAX_FPS = 5000;
// Height in pixels of our controls, not counting scrollbars.
private final static int CONTROLS_HEIGHT = 65;
private final VirtualAcquisitionDisplay display_;
private EventBus bus_;
// Last known mouse positions.
private int mouseX_ = -1;
private int mouseY_ = -1;
// JPanel that holds all controls.
private JPanel subPanel_;
// Controls common to both control sets
private ScrollerPanel scrollerPanel_;
private JLabel pixelInfoLabel_;
// Displays information on the currently-displayed image.
private JLabel imageInfoLabel_;
// Displays the countdown to the next frame.
private JLabel countdownLabel_;
private JButton showFolderButton_;
private JButton saveButton_;
private JLabel fpsLabel_;
// Standard control set
private javax.swing.JTextField fpsField_;
private JButton abortButton_;
private javax.swing.JToggleButton pauseAndResumeToggleButton_;
// Snap/live control set
private JButton snapButton_;
private JButton snapToAlbumButton_;
private JButton liveButton_;
/**
* @param shouldUseLiveControls - indicates if we should use the buttons for
* the "Snap/Live" window or the buttons for normal displays.
* @param isAcquisition - indicates if we should auto-size the scrollbars
* to the dataset or not (in an acquisition we resize them as images
* come in, instead).
*/
public HyperstackControls(VirtualAcquisitionDisplay display,
EventBus bus, boolean shouldUseLiveControls, boolean isAcquisition) {
super(new FlowLayout(FlowLayout.LEADING));
bus_ = bus;
initComponents(display, shouldUseLiveControls, isAcquisition);
display_ = display;
bus_.register(this);
MMStudio.getInstance().getSnapLiveManager().addLiveModeListener(this);
}
private void initComponents(VirtualAcquisitionDisplay display,
final boolean shouldUseLiveControls, boolean isAcquisition) {
// This layout minimizes space between components.
subPanel_ = new JPanel(new MigLayout("insets 0, fillx, align center"));
JPanel labelsPanel = new JPanel(new MigLayout("insets 0"));
pixelInfoLabel_ = new JLabel(" ");
pixelInfoLabel_.setMinimumSize(new Dimension(150, 10));
pixelInfoLabel_.setFont(new java.awt.Font("Lucida Grande", 0, 10));
labelsPanel.add(pixelInfoLabel_);
imageInfoLabel_ = new JLabel(" ");
imageInfoLabel_.setMinimumSize(new Dimension(150, 10));
imageInfoLabel_.setFont(new java.awt.Font("Lucida Grande", 0, 10));
labelsPanel.add(imageInfoLabel_);
countdownLabel_ = new JLabel(" ");
countdownLabel_.setMinimumSize(new Dimension(150, 10));
countdownLabel_.setFont(new java.awt.Font("Lucida Grande", 0, 10));
labelsPanel.add(countdownLabel_);
subPanel_.add(labelsPanel, "span, growx, align center, wrap");
// During an acquisition, we want the scrollbars to grow automatically
// as new images show up. When showing a fixed dataset, though, we want
// to show all the available image coordinates from the start.
int numChannels = 0, numFrames = 0, numSlices = 0, numPositions = 0;
if (!isAcquisition) {
// Loading a proper dataset; extract the dataset dimensions from the
// metadata.
numChannels = display.getNumChannels();
// We use a special method to get the number of frames, since the
// display object will just return the claimed number of frames,
// which may be inaccurate if e.g. acquisition was aborted partway
// through the experiment.
// TODO: should we be using similar methods for other axes?
numFrames = display.getImageCache().lastAcquiredFrame() + 1;
numSlices = display.getNumSlices();
// Positions have to be handled specially, since our display doesn't
// actually know about them -- it normally relies on us!
JSONObject tags = display.getImageCache().getSummaryMetadata();
numPositions = 0;
try {
numPositions = MDUtils.getNumPositions(tags);
}
catch (JSONException e) {
// Oh well, no positions for us.
}
}
scrollerPanel_ = new ScrollerPanel(
bus_, new String[]{"channel", "position", "time", "z"},
new Integer[]{numChannels, numPositions, numFrames, numSlices},
DEFAULT_FPS);
subPanel_.add(scrollerPanel_, "span, growx, wrap 0px");
// Hacky layout to minimize gaps between components.
JPanel buttonPanel = new JPanel(new MigLayout("insets 0",
"[]0[]0[]0[]0[]0[]"));
showFolderButton_ = new JButton();
saveButton_ = new JButton();
buttonPanel.add(showFolderButton_);
buttonPanel.add(saveButton_);
showFolderButton_.setBackground(new java.awt.Color(255, 255, 255));
showFolderButton_.setIcon(
new javax.swing.ImageIcon(
getClass().getResource("/org/micromanager/icons/folder.png")));
showFolderButton_.setToolTipText("Show containing folder");
showFolderButton_.setFocusable(false);
showFolderButton_.setHorizontalTextPosition(
javax.swing.SwingConstants.CENTER);
showFolderButton_.setMaximumSize(new java.awt.Dimension(30, 28));
showFolderButton_.setMinimumSize(new java.awt.Dimension(30, 28));
showFolderButton_.setPreferredSize(new java.awt.Dimension(30, 28));
showFolderButton_.setVerticalTextPosition(
javax.swing.SwingConstants.BOTTOM);
showFolderButton_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showFolderButtonActionPerformed(evt);
}
});
saveButton_.setBackground(new java.awt.Color(255, 255, 255));
saveButton_.setIcon(
new javax.swing.ImageIcon(
getClass().getResource("/org/micromanager/icons/disk.png")));
saveButton_.setToolTipText("Save as...");
saveButton_.setFocusable(false);
saveButton_.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
saveButton_.setMaximumSize(new java.awt.Dimension(30, 28));
saveButton_.setMinimumSize(new java.awt.Dimension(30, 28));
saveButton_.setPreferredSize(new java.awt.Dimension(30, 28));
saveButton_.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
saveButton_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveButtonActionPerformed(evt, shouldUseLiveControls);
}
});
// This control is added by both Snap/Live, and Standard, but in
// different places on each.
fpsLabel_ = new JLabel(" ", SwingConstants.RIGHT);
fpsLabel_.setFont(new java.awt.Font("Lucida Grande", 0, 10));
fpsLabel_.setFocusable(false);
if (shouldUseLiveControls) {
makeSnapLiveControls(buttonPanel);
}
else {
makeStandardControls(buttonPanel);
}
subPanel_.add(buttonPanel);
add(subPanel_);
// Propagate resizing through to our JPanel, adjusting slightly the
// amount of space we give them to create a border.
addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
Dimension curSize = getSize();
subPanel_.setSize(new Dimension(curSize.width - 10, curSize.height - 10));
invalidate();
validate();
}
});
}
/**
* Generate the controls used for the "Snap/Live" window.
*/
private void makeSnapLiveControls(JPanel buttonPanel) {
snapButton_ = new JButton();
snapButton_.setFocusable(false);
snapButton_.setIconTextGap(6);
snapButton_.setText("Snap");
snapButton_.setMinimumSize(new Dimension(90,28));
snapButton_.setPreferredSize(new Dimension(90,28));
snapButton_.setMaximumSize(new Dimension(90,28));
snapButton_.setIcon(SwingResourceManager.getIcon(
MMStudio.class, "/org/micromanager/icons/camera.png"));
snapButton_.setFont(new Font("Arial", Font.PLAIN, 10));
snapButton_.setToolTipText("Snap single image");
snapButton_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MMStudio.getInstance().doSnap();
}
});
liveButton_ = new JButton();
liveButton_.setIcon(SwingResourceManager.getIcon(
MMStudio.class,
"/org/micromanager/icons/camera_go.png"));
liveButton_.setIconTextGap(6);
liveButton_.setText("Live");
liveButton_.setMinimumSize(new Dimension(90,28));
liveButton_.setPreferredSize(new Dimension(90,28));
liveButton_.setMaximumSize(new Dimension(90,28));
liveButton_.setFocusable(false);
liveButton_.setToolTipText("Continuous live view");
liveButton_.setFont(new Font("Arial", Font.PLAIN, 10));
liveButton_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
liveButtonAction();
}
});
snapToAlbumButton_ = new JButton("Album");
snapToAlbumButton_.setIcon(SwingResourceManager.getIcon(MMStudio.class,
"/org/micromanager/icons/arrow_right.png"));
snapToAlbumButton_.setIconTextGap(6);
snapToAlbumButton_.setToolTipText("Add current image to album");
snapToAlbumButton_.setFocusable(false);
snapToAlbumButton_.setMaximumSize(new Dimension(90, 28));
snapToAlbumButton_.setMinimumSize(new Dimension(90, 28));
snapToAlbumButton_.setPreferredSize(new Dimension(90, 28));
snapToAlbumButton_.setFont(new Font("Arial", Font.PLAIN, 10));
snapToAlbumButton_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
snapToAlbumButtonActionPerformed();
}
});
buttonPanel.add(snapButton_);
buttonPanel.add(liveButton_);
buttonPanel.add(snapToAlbumButton_);
fpsLabel_.setText(" ");
buttonPanel.add(fpsLabel_, "span, wrap, width 120px, align right");
}
/**
* Generate the controls used on a standard dataset display (i.e. not the
* snap/live window).
*/
private void makeStandardControls(JPanel buttonPanel) {
fpsField_ = new javax.swing.JTextField(String.valueOf(DEFAULT_FPS), 4);
abortButton_ = new JButton();
pauseAndResumeToggleButton_ = new javax.swing.JToggleButton();
buttonPanel.add(abortButton_);
buttonPanel.add(pauseAndResumeToggleButton_);
// Make a new panel to hold the FPS info, since they need to be
// together.
JPanel fpsPanel = new JPanel(new MigLayout("insets 0"));
fpsPanel.add(fpsLabel_);
fpsPanel.add(fpsField_);
buttonPanel.add(fpsPanel, "span, gapleft push, wrap");
fpsField_.setToolTipText(
"Set the speed at which the acquisition is played back.");
fpsField_.addFocusListener(new java.awt.event.FocusAdapter() {
@Override
public void focusLost(java.awt.event.FocusEvent evt) {
fpsField_FocusLost(evt);
}
});
fpsField_.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyReleased(java.awt.event.KeyEvent evt) {
fpsField_KeyReleased(evt);
}
});
abortButton_.setBackground(new java.awt.Color(255, 255, 255));
abortButton_.setIcon(
new javax.swing.ImageIcon(
getClass().getResource("/org/micromanager/icons/cancel.png")));
abortButton_.setToolTipText("Stop acquisition");
abortButton_.setFocusable(false);
abortButton_.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
abortButton_.setMaximumSize(new java.awt.Dimension(30, 28));
abortButton_.setMinimumSize(new java.awt.Dimension(30, 28));
abortButton_.setPreferredSize(new java.awt.Dimension(30, 28));
abortButton_.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
abortButton_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
abortButtonActionPerformed(evt);
}
});
pauseAndResumeToggleButton_.setIcon(
new javax.swing.ImageIcon(getClass().getResource(
"/org/micromanager/icons/control_pause.png")));
pauseAndResumeToggleButton_.setToolTipText("Pause acquisition");
pauseAndResumeToggleButton_.setFocusable(false);
pauseAndResumeToggleButton_.setMargin(new java.awt.Insets(0, 0, 0, 0));
pauseAndResumeToggleButton_.setMaximumSize(new java.awt.Dimension(30, 28));
pauseAndResumeToggleButton_.setMinimumSize(new java.awt.Dimension(30, 28));
pauseAndResumeToggleButton_.setPreferredSize(
new java.awt.Dimension(30, 28));
pauseAndResumeToggleButton_.setPressedIcon(
new javax.swing.ImageIcon(getClass().getResource(
"/org/micromanager/icons/resultset_next.png")));
pauseAndResumeToggleButton_.setSelectedIcon(
new javax.swing.ImageIcon(getClass().getResource(
"/org/micromanager/icons/resultset_next.png")));
pauseAndResumeToggleButton_.addActionListener(
new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pauseAndResumeToggleButtonActionPerformed(evt);
}
});
}
/**
* User moused over the display; update our indication of pixel intensities.
* TODO: only providing the first intensity; what about multichannel
* images?
*/
@Subscribe
public void onMouseMoved(MouseIntensityEvent event) {
mouseX_ = event.x_;
mouseY_ = event.y_;
setPixelInfo(mouseX_, mouseY_, event.intensities_[0]);
}
/**
* Update our pixel info text.
*/
private void setPixelInfo(int x, int y, int intensity) {
pixelInfoLabel_.setText(String.format("x=%d, y=%d, value=%d",
x, y, intensity));
}
/**
* Our ScrollerPanel is informing us that we need to display a different
* image.
*/
@Subscribe
public void onSetImage(ScrollerPanel.SetImageEvent event) {
int position = -1;
int channel = -1;
int frame = -1;
int slice = -1;
try {
position = event.getPositionForAxis("position");
display_.updatePosition(position);
// Positions for ImageJ are 1-indexed but positions from the event are
// 0-indexed.
channel = event.getPositionForAxis("channel") + 1;
frame = event.getPositionForAxis("time") + 1;
slice = event.getPositionForAxis("z") + 1;
// Ensure that the ImagePlus thinks it is big enough for us to set
// its position correctly.
ImagePlus plus = display_.getHyperImage();
if (plus instanceof IMMImagePlus) {
IMMImagePlus tmp = (IMMImagePlus) plus;
tmp.setNFramesUnverified(frame);
tmp.setNChannelsUnverified(channel);
tmp.setNSlicesUnverified(slice);
}
else { // Must be MMComposite Image
MMCompositeImage tmp = (MMCompositeImage) plus;
tmp.setNFramesUnverified(frame);
tmp.setNChannelsUnverified(channel);
tmp.setNSlicesUnverified(slice);
}
plus.setPosition(channel, slice, frame);
display_.updateAndDraw(true);
}
catch (Exception e) {
// This can happen, rarely, with an ArrayIndexOutOfBoundsException
// in IJ code that draws the new image, called by way of the
// updatePosition() call above. No idea what causes it, but it's
// rare enough that debugging is a pain.
ReportingUtils.logError(e, String.format("Failed to set image at %d, %d, %d, %d", position, frame, slice, channel));
}
}
/**
* A new image has been made available. Update our pixel info, assuming
* we have a valid mouse position.
*/
@Subscribe
public void onNewImage(NewImageEvent event) {
if (mouseX_ != -1 && mouseY_ != -1) {
try {
int intensity = display_.getIntensityAt(mouseX_, mouseY_);
setPixelInfo(mouseX_, mouseY_, intensity);
}
catch (Exception e) {
ReportingUtils.logError(e, "Error in HyperstackControls onNewImage");
}
}
}
/**
* Our ScrollerPanel is informing us that its layout has changed.
*/
@Subscribe
public void onLayoutChange(ScrollerPanel.LayoutChangedEvent event) {
invalidate();
validate();
}
private void showFolderButtonActionPerformed(java.awt.event.ActionEvent evt) {
display_.showFolder();
}
private void fpsField_FocusLost(java.awt.event.FocusEvent evt) {
updateFPS();
}
private void fpsField_KeyReleased(java.awt.event.KeyEvent evt) {
updateFPS();
}
private void abortButtonActionPerformed(java.awt.event.ActionEvent evt) {
display_.abort();
}
private void pauseAndResumeToggleButtonActionPerformed(java.awt.event.ActionEvent evt) {
display_.pause();
}
private void saveButtonActionPerformed(java.awt.event.ActionEvent evt, final boolean isSimpleDisplay) {
new Thread() {
@Override
public void run() {
// We don't want to tie the Snap/Live display to a specific
// file since its contents get overwritten regularly.
display_.saveAs(!isSimpleDisplay);
}
}.start();
}
private void snapToAlbumButtonActionPerformed() {
try {
MMStudio gui = MMStudio.getInstance();
gui.copyFromLiveModeToAlbum(display_);
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
}
private void liveButtonAction() {
MMStudio.getInstance().enableLiveMode(!MMStudio.getInstance().isLiveModeOn());
}
private void updateFPS() {
// There's no FPS field when using the Snap/Live window
if (fpsField_ != null) {
try {
double fps = NumberUtils.displayStringToDouble(fpsField_.getText());
// Constrain the FPS to a sane range.
fps = Math.max(1.0, Math.min(fps, MAX_FPS));
scrollerPanel_.setFramesPerSecond(fps);
} catch (ParseException ex) {
// No recognizable number (e.g. because the field is empty); just
// do nothing.
}
}
}
@Override
public synchronized void setImageInfoLabel(String text) {
imageInfoLabel_.setText(text);
}
private void updateStatusLine(JSONObject tags) {
String status = "";
try {
String xyPosition;
try {
xyPosition = MDUtils.getPositionName(tags);
if (xyPosition != null && !xyPosition.contentEquals("null")) {
status += xyPosition + ", ";
}
} catch (Exception e) {
//Oh well...
}
try {
double seconds = MDUtils.getElapsedTimeMs(tags) / 1000;
status += elapsedTimeDisplayString(seconds);
} catch (JSONException ex) {
ReportingUtils.logError("MetaData did not contain ElapsedTime-ms field");
}
String zPosition;
try {
zPosition = NumberUtils.doubleToDisplayString(MDUtils.getZPositionUm(tags));
status += ", z: " + zPosition + " um";
} catch (Exception e) {
}
String chan;
try {
chan = MDUtils.getChannelName(tags);
if (chan != null && !chan.contentEquals("null")) {
status += ", " + chan;
}
} catch (Exception ex) {
}
setImageInfoLabel(status);
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
}
public static String elapsedTimeDisplayString(double seconds) {
// Use "12.34s" up to 60 s; "12m 34.56s" up to 1 h, and
// "1h 23m 45s" beyond that.
long wholeSeconds = (long) Math.floor(seconds);
double fraction = seconds - wholeSeconds;
long hours = TimeUnit.SECONDS.toHours(wholeSeconds);
wholeSeconds -= TimeUnit.HOURS.toSeconds(hours);
String hoursString = "";
if (hours > 0) {
hoursString = hours + "h ";
}
long minutes = TimeUnit.SECONDS.toMinutes(wholeSeconds);
wholeSeconds -= TimeUnit.MINUTES.toSeconds(minutes);
String minutesString = "";
if (minutes > 0) {
minutesString = minutes + "m ";
}
String secondsString;
if (hours == 0 && fraction > 0.01) {
secondsString = String.format("%.2fs", wholeSeconds + fraction);
}
else {
secondsString = wholeSeconds + "s";
}
return hoursString + minutesString + secondsString;
}
@Override
public void newImageUpdate(JSONObject tags) {
if (tags == null) {
return;
}
updateStatusLine(tags);
if (!display_.acquisitionIsRunning() || display_.getNextWakeTime() <= 0) {
// No acquisition to display a countdown for.
return;
}
final long nextImageTime = display_.getNextWakeTime();
if (System.nanoTime() / 1000000 >= nextImageTime) {
// Already past the next image time.
return;
}
// TODO: why the try/catch block here?
try {
final Timer timer = new Timer("Next frame display");
TimerTask task = new TimerTask() {
@Override
public void run() {
double timeRemainingS = (nextImageTime - System.nanoTime() / 1000000.0) / 1000;
if (timeRemainingS > 0 &&
display_.acquisitionIsRunning()) {
countdownLabel_.setText(
String.format("Next frame: %.2fs", timeRemainingS));
} else {
timer.cancel();
countdownLabel_.setText("");
}
}
};
timer.schedule(task, 500, 100);
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
}
@Override
public void acquiringImagesUpdate(boolean state) {
// NB currently there's no situation in which one of these will be null
// when the other isn't, but on the other hand who knows what the future
// will bring?
if (abortButton_ != null) {
abortButton_.setEnabled(state);
}
if (pauseAndResumeToggleButton_ != null) {
pauseAndResumeToggleButton_.setEnabled(state);
}
}
@Override
public void imagesOnDiskUpdate(boolean enabled) {
showFolderButton_.setEnabled(enabled);
}
public void prepareForClose() {
scrollerPanel_.prepareForClose();
bus_.unregister(this);
MMStudio.getInstance().getSnapLiveManager().removeLiveModeListener(this);
}
@Override
public void setPosition(int p) {
scrollerPanel_.setPosition("position", p);
}
@Override
public int getPosition() {
return scrollerPanel_.getPosition("position");
}
@Override
public void setChannel(int c) {
scrollerPanel_.setPosition("channel", c);
}
/**
* New information on our FPS; update a label.
*/
@Subscribe
public void onFPSUpdate(FPSEvent event) {
// Default to assuming we'll be blanking the label.
String newLabel = "";
if (event.getDataFPS() != 0) {
newLabel = String.format("FPS: %.1f (display %.1f)",
event.getDataFPS(), event.getDisplayFPS());
}
else if (fpsField_ != null) {
// No new data, but we do have an FPS text field for animations, so
// switch fpsLabel_ to being an indicator for that.
newLabel = "Playback FPS:";
}
fpsLabel_.setText(newLabel);
}
/**
* Live mode was toggled; if we have a "live mode" button, it needs to be
* toggled on/off; likewise, the Snap button should be disabled/enabled.
*/
public void liveModeEnabled(boolean isEnabled) {
if (liveButton_ == null) {
return;
}
String label = isEnabled ? "Stop Live" : "Live";
String iconPath = isEnabled ? "/org/micromanager/icons/cancel.png" : "/org/micromanager/icons/camera_go.png";
liveButton_.setIcon(
SwingResourceManager.getIcon(MMStudio.class, iconPath));
liveButton_.setText(label);
if (snapButton_ != null) {
snapButton_.setEnabled(!isEnabled);
}
}
public int getNumPositions() {
return scrollerPanel_.getMaxPosition("position");
}
}
| [Display] Bugfix for prior commit r14968.
Now we only set the ImagePlus' size if we are in fact increasing it; previously
we would contract the ImagePlus if the scrollbars moved to the left. Oops.
git-svn-id: 03a8048b5ee8463be5048a3801110fb50f378627@14970 d0ab736e-dc22-4aeb-8dc9-08def0aa14fd
| mmstudio/src/org/micromanager/imagedisplay/HyperstackControls.java | [Display] Bugfix for prior commit r14968. | |
Java | mit | eb64b9124687b5178d86860a6d176338b64a8981 | 0 | njmube/OpERP,DevOpsDistilled/OpERP | package devopsdistilled.operp.client.view.taskpane;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import devopsdistilled.operp.client.view.MainWindow;
import devopsdistilled.operp.client.view.taskpane.iface.TaskPane;
public class PurchasesPane implements TaskPane {
private JPanel pane;
@Override
public String toString() {
return "Purchases";
}
@Override
public void makeCurrentWorkingTaskPane() {
pane = new JPanel();
pane.add(new JLabel("From Purchases Pane"));
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
MainWindow.getInstance().setTaskPane(pane);
}
});
}
}
| OpERP/src/main/java/devopsdistilled/operp/client/view/taskpane/PurchasesPane.java | package devopsdistilled.operp.client.view.taskpane;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import devopsdistilled.operp.client.view.MainWindow;
import devopsdistilled.operp.client.view.taskpane.iface.TaskPane;
public class PurchasesPane implements TaskPane {
@Override
public String toString() {
return "Purchases";
}
@Override
public void makeCurrentWorkingTaskPane() {
pane = new JPanel();
pane.add(new JLabel("From Purchases Pane"));
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
MainWindow.getInstance().setTaskPane(pane);
}
});
}
}
| Create field variable pane | OpERP/src/main/java/devopsdistilled/operp/client/view/taskpane/PurchasesPane.java | Create field variable pane | |
Java | mit | 6de0e14c1f64e366df34d0c1d6c7427733ff1d1f | 0 | mk74/locy,mk74/locy,mk74/locy,mk74/locy | package uk.ac.st_andrews.cs.host.mk74.energymeasurement.wifi80211;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
public class MainActivity extends Activity {
final private static int BATTERY_LEVEL_START=99;
final private static int BATTERY_LEVEL_END=98;
final private static int BATTERY_CHECK_FREQUENCY = 1;
public Date batteryLevelStartTime, batteryLevelEndTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//WiFi Setup
final WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
while(!wifiManager.isWifiEnabled()){
//wait till WiFI is enabled
}
//schedule new scan, only if previous is finished
IntentFilter i = new IntentFilter();
i.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
BroadcastReceiver receiver= new BroadcastReceiver(){
@Override
public void onReceive(Context c, Intent i){
wifiManager.startScan();
}
};
registerReceiver(receiver, i );
//run first scan, print results every sec and check battery life whether the given range was depleted
wifiManager.startScan();
TimerTask scanNetworksTask = new TimerTask() {
@Override
public void run() {
//print amount of visible networks
System.out.println(wifiManager.getScanResults().size());
//battery measurements && time which was needed to deplete the battery range
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStats = registerReceiver(null, ifilter);
int level = batteryStats.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
if(level == BATTERY_LEVEL_START && batteryLevelStartTime == null){
final String batteryOutput = "Battery level start is reached\n";
System.out.println(batteryOutput);
batteryLevelStartTime = new Date();
runOnUiThread(new Runnable(){
@Override
public void run() {
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(batteryOutput);
}
});
}
if(level == BATTERY_LEVEL_END && batteryLevelEndTime == null){
System.out.println("Battery level end is reached\n");
batteryLevelEndTime = new Date();
}
if(batteryLevelStartTime != null && batteryLevelEndTime != null){
int diffInSecs = (int) ((batteryLevelEndTime.getTime() - batteryLevelStartTime.getTime()) / 1000);
final String batteryOutput = "Time difference in secs is: " + diffInSecs + "\n";
System.out.println(batteryOutput);
runOnUiThread(new Runnable(){
@Override
public void run() {
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(batteryOutput);
}
});
}
}
};
Timer timer = new Timer();
long delay = BATTERY_CHECK_FREQUENCY * 1000;
long period = BATTERY_CHECK_FREQUENCY * 1000;
timer.schedule(scanNetworksTask, delay, period);
Window w = getWindow();
w.setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
| measurements/wifi802.11/src/uk/ac/st_andrews/cs/host/mk74/energymeasurement/wifi80211/MainActivity.java | package uk.ac.st_andrews.cs.host.mk74.energymeasurement.wifi80211;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
public class MainActivity extends Activity {
final private static int BATTERY_LEVEL_START=99;
final private static int BATTERY_LEVEL_END=98;
final private static int BATTERY_CHECK_FREQUENCY = 1;
public Date batteryLevelStartTime, batteryLevelEndTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//WiFi Setup
final WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
//schedule new scan, only if previous is finished
IntentFilter i = new IntentFilter();
i.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
BroadcastReceiver receiver= new BroadcastReceiver(){
@Override
public void onReceive(Context c, Intent i){
wifiManager.startScan();
}
};
registerReceiver(receiver, i );
//run first scan, print results every sec and check battery life whether the given range was depleted
wifiManager.startScan();
TimerTask scanNetworksTask = new TimerTask() {
@Override
public void run() {
//print available WiFi Scan results:
List<ScanResult> scans = wifiManager.getScanResults();
StringBuffer buff = new StringBuffer("");
Iterator<ScanResult> it = scans.iterator();
while(it.hasNext()){
ScanResult scanResult = it.next();
buff.append("SSID: " + scanResult.SSID+ "\tBSSID:" + scanResult.BSSID + "\tcapabilites" + scanResult.capabilities);
buff.append("\tfrequency:" + scanResult.frequency + "\tlevel:" + scanResult.level + "\n");
}
System.out.println(buff.toString());
//battery measurements && time which was needed to deplete the battery range
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStats = registerReceiver(null, ifilter);
int level = batteryStats.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
if(level == BATTERY_LEVEL_START && batteryLevelStartTime == null){
final String batteryOutput = "Battery level start is reached\n";
System.out.println(batteryOutput);
batteryLevelStartTime = new Date();
runOnUiThread(new Runnable(){
@Override
public void run() {
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(batteryOutput);
}
});
}
if(level == BATTERY_LEVEL_END && batteryLevelEndTime == null){
System.out.println("Battery level end is reached\n");
batteryLevelEndTime = new Date();
}
if(batteryLevelStartTime != null && batteryLevelEndTime != null){
int diffInSecs = (int) ((batteryLevelEndTime.getTime() - batteryLevelStartTime.getTime()) / 1000);
final String batteryOutput = "Time difference in secs is: " + diffInSecs + "\n";
System.out.println(batteryOutput);
runOnUiThread(new Runnable(){
@Override
public void run() {
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(batteryOutput);
}
});
}
}
};
Timer timer = new Timer();
long delay = BATTERY_CHECK_FREQUENCY * 1000;
long period = BATTERY_CHECK_FREQUENCY * 1000;
timer.schedule(scanNetworksTask, delay, period);
Window w = getWindow();
w.setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
| consistency with the rest of sample apps | measurements/wifi802.11/src/uk/ac/st_andrews/cs/host/mk74/energymeasurement/wifi80211/MainActivity.java | consistency with the rest of sample apps | |
Java | mit | 406bc90b04f1ead5d609dee9244d75c491dabcc4 | 0 | freesamael/npu-moboapp-programming-fall-2015,freesamael/npu-moboapp-programming-fall-2015,freesamael/npu-moboapp-programming-fall-2015,freesamael/npu-moboapp-programming-fall-2015,freesamael/npu-moboapp-programming-fall-2015 | package idv.samael.mrtapproachingstations;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.Toast;
import com.google.gson.Gson;
import java.util.List;
import retrofit.Call;
import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;
public class MainActivity extends AppCompatActivity {
private TrainInfoAdapter mAdapter;
private DataTaipeiService mService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Bind list view.
ListView trainList = (ListView) findViewById(R.id.list_mrt);
mAdapter = new TrainInfoAdapter(this);
if (trainList != null) {
trainList.setAdapter(mAdapter);
}
// Create web service wrapper.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://data.taipei")
.addConverterFactory(GsonConverterFactory.create())
.build();
mService = retrofit.create(DataTaipeiService.class);
// Refresh immediately.
refresh();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
refresh();
return true;
}
return super.onOptionsItemSelected(item);
}
private void refresh() {
// Clear old data.
mAdapter.getItems().clear();
mAdapter.notifyDataSetChanged();
// Update train info.
Call<ApproachingTrains> trainsCall = mService.listApproachingTrains();
trainsCall.enqueue(new Callback<ApproachingTrains>() {
@Override
public void onResponse(Response<ApproachingTrains> response, Retrofit retrofit) {
ApproachingTrains responseBody;
ApproachingTrains.ApproachingTrainsResult resultObject;
List<ApproachingTrains.TrainInfo> trainInfoList;
if ((responseBody = response.body()) != null &&
(resultObject = responseBody.result) != null &&
(trainInfoList = resultObject.results) != null) {
// Fill the list view.
for (ApproachingTrains.TrainInfo trainInfo : response.body().result.results) {
mAdapter.getItems().add(trainInfo);
}
mAdapter.notifyDataSetChanged();
}
}
@Override
public void onFailure(Throwable t) {
Log.e("Data.Taipei", t.getMessage(), t);
Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
| mrt-android/app/src/main/java/idv/samael/mrtapproachingstations/MainActivity.java | package idv.samael.mrtapproachingstations;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
import com.google.gson.Gson;
import retrofit.Call;
import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;
public class MainActivity extends AppCompatActivity {
private TrainInfoAdapter mAdapter;
private DataTaipeiService mService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Bind list view.
ListView trainList = (ListView) findViewById(R.id.list_mrt);
mAdapter = new TrainInfoAdapter(this);
if (trainList != null) {
trainList.setAdapter(mAdapter);
}
// Create web service wrapper.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://data.taipei")
.addConverterFactory(GsonConverterFactory.create())
.build();
mService = retrofit.create(DataTaipeiService.class);
// Refresh immediately.
refresh();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
refresh();
return true;
}
return super.onOptionsItemSelected(item);
}
private void refresh() {
// Clear old data.
mAdapter.getItems().clear();
mAdapter.notifyDataSetChanged();
// Update train info.
Call<ApproachingTrains> trainsCall = mService.listApproachingTrains();
trainsCall.enqueue(new Callback<ApproachingTrains>() {
@Override
public void onResponse(Response<ApproachingTrains> response, Retrofit retrofit) {
// Fill the list view.
for (ApproachingTrains.TrainInfo trainInfo : response.body().result.results) {
mAdapter.getItems().add(trainInfo);
}
mAdapter.notifyDataSetChanged();
}
@Override
public void onFailure(Throwable t) {
Log.e("Data.Taipei", t.getMessage(), t);
}
});
}
}
| Update refresh() method.
| mrt-android/app/src/main/java/idv/samael/mrtapproachingstations/MainActivity.java | Update refresh() method. | |
Java | mit | 3095ce33a7e72a7b73bcde57a4783ac32396e576 | 0 | fluxroot/pulse,fluxroot/pulse,jvoegele/pulse,jvoegele/pulse,jvoegele/pulse | /*
* Copyright 2013-2014 the original author or authors.
*
* This file is part of Pulse Chess.
*
* Pulse Chess is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pulse Chess 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Pulse Chess. If not, see <http://www.gnu.org/licenses/>.
*/
package com.fluxchess.pulse;
import com.fluxchess.jcpi.commands.IProtocol;
import com.fluxchess.jcpi.commands.ProtocolBestMoveCommand;
import com.fluxchess.jcpi.commands.ProtocolInformationCommand;
import com.fluxchess.jcpi.models.GenericMove;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Semaphore;
import static com.fluxchess.pulse.Color.WHITE;
import static com.fluxchess.pulse.MoveList.MoveVariation;
/**
* This class implements our search in a separate thread to keep the main
* thread available for more commands.
*/
public final class Search implements Runnable {
static final int MAX_PLY = 256;
static final int MAX_DEPTH = 64;
private final Thread thread = new Thread(this);
private final Semaphore semaphore = new Semaphore(0);
private final IProtocol protocol;
private final Board board;
private final Evaluation evaluation = new Evaluation();
// Depth search
private int searchDepth = MAX_DEPTH;
// Nodes search
private long searchNodes = Long.MAX_VALUE;
// Time & Clock & Ponder search
private long searchTime = 0;
private Timer timer = null;
private boolean timerStopped = false;
private boolean doTimeManagement = false;
// Moves search
private final MoveList searchMoves = new MoveList();
// Search parameters
private final MoveList rootMoves = new MoveList();
private boolean abort = false;
private long startTime = 0;
private long statusStartTime = 0;
private long totalNodes = 0;
private int initialDepth = 1;
private int currentDepth = initialDepth;
private int currentMaxDepth = initialDepth;
private int currentMove = Move.NOMOVE;
private int currentMoveNumber = 0;
private final MoveVariation[] pv = new MoveVariation[MAX_PLY + 1];
/**
* This is our search timer for time & clock & ponder searches.
*/
private final class SearchTimer extends TimerTask {
@Override
public void run() {
timerStopped = true;
// If we finished the first iteration, we should have a result.
// In this case abort the search.
if (!doTimeManagement || currentDepth > initialDepth) {
abort = true;
}
}
}
static Search newDepthSearch(IProtocol protocol, Board board, int searchDepth) {
if (protocol == null) throw new IllegalArgumentException();
if (board == null) throw new IllegalArgumentException();
if (searchDepth < 1 || searchDepth > MAX_DEPTH) throw new IllegalArgumentException();
Search search = new Search(protocol, board);
search.searchDepth = searchDepth;
return search;
}
static Search newNodesSearch(IProtocol protocol, Board board, long searchNodes) {
if (protocol == null) throw new IllegalArgumentException();
if (board == null) throw new IllegalArgumentException();
if (searchNodes < 1) throw new IllegalArgumentException();
Search search = new Search(protocol, board);
search.searchNodes = searchNodes;
return search;
}
static Search newTimeSearch(IProtocol protocol, Board board, long searchTime) {
if (protocol == null) throw new IllegalArgumentException();
if (board == null) throw new IllegalArgumentException();
if (searchTime < 1) throw new IllegalArgumentException();
Search search = new Search(protocol, board);
search.searchTime = searchTime;
search.timer = new Timer(true);
return search;
}
static Search newMovesSearch(IProtocol protocol, Board board, List<GenericMove> searchMoves) {
if (protocol == null) throw new IllegalArgumentException();
if (board == null) throw new IllegalArgumentException();
if (searchMoves == null) throw new IllegalArgumentException();
Search search = new Search(protocol, board);
for (GenericMove move : searchMoves) {
search.searchMoves.entries[search.searchMoves.size++].move = Move.valueOf(move, board);
}
return search;
}
static Search newInfiniteSearch(IProtocol protocol, Board board) {
if (protocol == null) throw new IllegalArgumentException();
if (board == null) throw new IllegalArgumentException();
return new Search(protocol, board);
}
static Search newClockSearch(
IProtocol protocol, Board board,
long whiteTimeLeft, long whiteTimeIncrement, long blackTimeLeft, long blackTimeIncrement, int movesToGo) {
Search search = newPonderSearch(
protocol, board,
whiteTimeLeft, whiteTimeIncrement, blackTimeLeft, blackTimeIncrement, movesToGo
);
search.timer = new Timer(true);
return search;
}
static Search newPonderSearch(
IProtocol protocol, Board board,
long whiteTimeLeft, long whiteTimeIncrement, long blackTimeLeft, long blackTimeIncrement, int movesToGo) {
if (protocol == null) throw new IllegalArgumentException();
if (board == null) throw new IllegalArgumentException();
if (whiteTimeLeft < 1) throw new IllegalArgumentException();
if (whiteTimeIncrement < 0) throw new IllegalArgumentException();
if (blackTimeLeft < 1) throw new IllegalArgumentException();
if (blackTimeIncrement < 0) throw new IllegalArgumentException();
if (movesToGo < 0) throw new IllegalArgumentException();
Search search = new Search(protocol, board);
long timeLeft;
long timeIncrement;
if (board.activeColor == WHITE) {
timeLeft = whiteTimeLeft;
timeIncrement = whiteTimeIncrement;
} else {
timeLeft = blackTimeLeft;
timeIncrement = blackTimeIncrement;
}
// Don't use all of our time. Search only for 95%. Always leave 1 second as
// buffer time.
long maxSearchTime = (long) (timeLeft * 0.95) - 1000L;
if (maxSearchTime < 1) {
// We don't have enough time left. Search only for 1 millisecond, meaning
// get a result as fast as we can.
maxSearchTime = 1;
}
// Assume that we still have to do movesToGo number of moves. For every next
// move (movesToGo - 1) we will receive a time increment.
search.searchTime = (maxSearchTime + (movesToGo - 1) * timeIncrement) / movesToGo;
if (search.searchTime > maxSearchTime) {
search.searchTime = maxSearchTime;
}
search.doTimeManagement = true;
return search;
}
private Search(IProtocol protocol, Board board) {
assert protocol != null;
assert board != null;
this.protocol = protocol;
this.board = board;
for (int i = 0; i < pv.length; ++i) {
pv[i] = new MoveVariation();
}
}
void start() {
if (!thread.isAlive()) {
thread.setDaemon(true);
thread.start();
try {
// Wait for initialization
semaphore.acquire();
} catch (InterruptedException e) {
// Do nothing
}
}
}
void stop() {
if (thread.isAlive()) {
// Signal the search thread that we want to stop it
abort = true;
try {
// Wait for the thread to die
thread.join(5000);
} catch (InterruptedException e) {
// Do nothing
}
}
}
void ponderhit() {
if (thread.isAlive()) {
// Enable time management
timer = new Timer(true);
timer.schedule(new SearchTimer(), searchTime);
// If we finished the first iteration, we should have a result.
// In this case check the stop conditions.
if (currentDepth > initialDepth) {
checkStopConditions();
}
}
}
public void run() {
// Do all initialization before releasing the main thread to JCPI
startTime = System.currentTimeMillis();
statusStartTime = startTime;
if (timer != null) {
timer.schedule(new SearchTimer(), searchTime);
}
// Populate root move list
boolean isCheck = board.isCheck();
MoveGenerator moveGenerator = MoveGenerator.getMoveGenerator(board, 1, 0, isCheck);
int move;
while ((move = moveGenerator.next()) != Move.NOMOVE) {
rootMoves.entries[rootMoves.size].move = move;
rootMoves.entries[rootMoves.size].pv.moves[0] = move;
rootMoves.entries[rootMoves.size].pv.size = 1;
++rootMoves.size;
}
// Go...
semaphore.release();
//### BEGIN Iterative Deepening
for (currentDepth = initialDepth; currentDepth <= searchDepth; ++currentDepth) {
currentMaxDepth = 0;
sendStatus(false);
searchRoot(currentDepth, -Evaluation.INFINITY, Evaluation.INFINITY);
// Sort the root move list, so that the next iteration begins with the
// best move first.
rootMoves.sort();
checkStopConditions();
if (abort) {
break;
}
}
//### ENDOF Iterative Deepening
if (timer != null) {
timer.cancel();
}
// Update all stats
sendStatus(true);
// Get the best move and convert it to a GenericMove
GenericMove bestMove = null;
GenericMove ponderMove = null;
if (rootMoves.size > 0) {
bestMove = Move.toGenericMove(rootMoves.entries[0].move);
if (rootMoves.entries[0].pv.size >= 2) {
ponderMove = Move.toGenericMove(rootMoves.entries[0].pv.moves[1]);
}
}
// Send the best move to the GUI
protocol.send(new ProtocolBestMoveCommand(bestMove, ponderMove));
}
private void checkStopConditions() {
// We will check the stop conditions only if we are using time management,
// that is if our timer != null.
if (timer != null && doTimeManagement) {
if (timerStopped) {
abort = true;
} else {
// Check if we have only one move to make
if (rootMoves.size == 1) {
abort = true;
} else
// Check if we have a checkmate
if (Math.abs(rootMoves.entries[0].value) >= Evaluation.CHECKMATE_THRESHOLD
&& currentDepth >= (Evaluation.CHECKMATE - Math.abs(rootMoves.entries[0].value))) {
abort = true;
}
}
}
}
private void updateSearch(int ply) {
++totalNodes;
if (ply > currentMaxDepth) {
currentMaxDepth = ply;
}
if (searchNodes <= totalNodes) {
// Hard stop on number of nodes
abort = true;
}
pv[ply].size = 0;
sendStatus();
}
private void searchRoot(int depth, int alpha, int beta) {
int ply = 0;
updateSearch(ply);
// Abort conditions
if (abort) {
return;
}
for (int i = 0; i < rootMoves.size; ++i) {
rootMoves.entries[i].value = -Evaluation.INFINITY;
}
for (int i = 0; i < rootMoves.size; ++i) {
int move = rootMoves.entries[i].move;
// Search only moves specified in searchedMoves
if (searchMoves.size > 0) {
boolean found = false;
for (int j = 0; j < searchMoves.size; ++j) {
if (move == searchMoves.entries[j].move) {
found = true;
break;
}
}
if (!found) {
continue;
}
}
currentMove = move;
currentMoveNumber = i + 1;
sendStatus(false);
board.makeMove(move);
int value = -search(depth - 1, -beta, -alpha, ply + 1);
board.undoMove(move);
if (abort) {
return;
}
// Do we have a better value?
if (value > alpha) {
alpha = value;
rootMoves.entries[i].value = value;
savePV(move, pv[ply + 1], rootMoves.entries[i].pv);
sendMove(rootMoves.entries[i]);
}
}
if (rootMoves.size == 0) {
// The root position is a checkmate or stalemate. We cannot search
// further. Abort!
abort = true;
}
}
private int search(int depth, int alpha, int beta, int ply) {
// We are at a leaf/horizon. So calculate that value.
if (depth <= 0) {
// Descend into quiescent
return quiescent(0, alpha, beta, ply);
}
updateSearch(ply);
// Abort conditions
if (abort || ply == MAX_PLY) {
return evaluation.evaluate(board);
}
// Check the repetition table and fifty move rule
if (board.isRepetition() || board.halfMoveClock >= 100) {
return Evaluation.DRAW;
}
// Initialize
int bestValue = -Evaluation.INFINITY;
int searchedMoves = 0;
boolean isCheck = board.isCheck();
MoveGenerator moveGenerator = MoveGenerator.getMoveGenerator(board, depth, ply, isCheck);
int move;
while ((move = moveGenerator.next()) != Move.NOMOVE) {
++searchedMoves;
board.makeMove(move);
int value = -search(depth - 1, -beta, -alpha, ply + 1);
board.undoMove(move);
if (abort) {
return bestValue;
}
// Pruning
if (value > bestValue) {
bestValue = value;
// Do we have a better value?
if (value > alpha) {
alpha = value;
savePV(move, pv[ply + 1], pv[ply]);
// Is the value higher than beta?
if (value >= beta) {
// Cut-off
break;
}
}
}
}
// If we cannot move, check for checkmate and stalemate.
if (searchedMoves == 0) {
if (isCheck) {
// We have a check mate. This is bad for us, so return a -CHECKMATE.
return -Evaluation.CHECKMATE + ply;
} else {
// We have a stale mate. Return the draw value.
return Evaluation.DRAW;
}
}
return bestValue;
}
private int quiescent(int depth, int alpha, int beta, int ply) {
updateSearch(ply);
// Abort conditions
if (abort || ply == MAX_PLY) {
return evaluation.evaluate(board);
}
// Check the repetition table and fifty move rule
if (board.isRepetition() || board.halfMoveClock >= 100) {
return Evaluation.DRAW;
}
// Initialize
int bestValue = -Evaluation.INFINITY;
int searchedMoves = 0;
boolean isCheck = board.isCheck();
//### BEGIN Stand pat
if (!isCheck) {
bestValue = evaluation.evaluate(board);
// Do we have a better value?
if (bestValue > alpha) {
alpha = bestValue;
// Is the value higher than beta?
if (bestValue >= beta) {
// Cut-off
return bestValue;
}
}
}
//### ENDOF Stand pat
// Only generate capturing moves or evasion moves, in case we are in check.
MoveGenerator moveGenerator = MoveGenerator.getMoveGenerator(board, depth, ply, isCheck);
int move;
while ((move = moveGenerator.next()) != Move.NOMOVE) {
++searchedMoves;
board.makeMove(move);
int value = -quiescent(depth - 1, -beta, -alpha, ply + 1);
board.undoMove(move);
if (abort) {
return bestValue;
}
// Pruning
if (value > bestValue) {
bestValue = value;
// Do we have a better value?
if (value > alpha) {
alpha = value;
savePV(move, pv[ply + 1], pv[ply]);
// Is the value higher than beta?
if (value >= beta) {
// Cut-off
break;
}
}
}
}
// If we cannot move, check for checkmate.
if (searchedMoves == 0 && isCheck) {
// We have a check mate. This is bad for us, so return a -CHECKMATE.
return -Evaluation.CHECKMATE + ply;
}
return bestValue;
}
private void savePV(int move, MoveVariation src, MoveVariation dest) {
dest.moves[0] = move;
System.arraycopy(src.moves, 0, dest.moves, 1, src.size);
dest.size = src.size + 1;
}
private void sendStatus() {
if (System.currentTimeMillis() - statusStartTime >= 1000) {
sendStatus(false);
}
}
private void sendStatus(boolean force) {
long timeDelta = System.currentTimeMillis() - startTime;
if (force || timeDelta >= 1000) {
ProtocolInformationCommand command = new ProtocolInformationCommand();
command.setDepth(currentDepth);
command.setMaxDepth(currentMaxDepth);
command.setNodes(totalNodes);
command.setTime(timeDelta);
command.setNps(timeDelta >= 1000 ? (totalNodes * 1000) / timeDelta : 0);
if (currentMove != Move.NOMOVE) {
command.setCurrentMove(Move.toGenericMove(currentMove));
command.setCurrentMoveNumber(currentMoveNumber);
}
protocol.send(command);
statusStartTime = System.currentTimeMillis();
}
}
private void sendMove(MoveList.Entry entry) {
long timeDelta = System.currentTimeMillis() - startTime;
ProtocolInformationCommand command = new ProtocolInformationCommand();
command.setDepth(currentDepth);
command.setMaxDepth(currentMaxDepth);
command.setNodes(totalNodes);
command.setTime(timeDelta);
command.setNps(timeDelta >= 1000 ? (totalNodes * 1000) / timeDelta : 0);
if (Math.abs(entry.value) >= Evaluation.CHECKMATE_THRESHOLD) {
// Calculate mate distance
int mateDepth = Evaluation.CHECKMATE - Math.abs(entry.value);
command.setMate(Integer.signum(entry.value) * (mateDepth + 1) / 2);
} else {
command.setCentipawns(entry.value);
}
List<GenericMove> pv = new ArrayList<>();
for (int i = 0; i < entry.pv.size; ++i) {
pv.add(Move.toGenericMove(entry.pv.moves[i]));
}
command.setMoveList(pv);
protocol.send(command);
statusStartTime = System.currentTimeMillis();
}
}
| src/main/java/com/fluxchess/pulse/Search.java | /*
* Copyright 2013-2014 the original author or authors.
*
* This file is part of Pulse Chess.
*
* Pulse Chess is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pulse Chess 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Pulse Chess. If not, see <http://www.gnu.org/licenses/>.
*/
package com.fluxchess.pulse;
import com.fluxchess.jcpi.commands.IProtocol;
import com.fluxchess.jcpi.commands.ProtocolBestMoveCommand;
import com.fluxchess.jcpi.commands.ProtocolInformationCommand;
import com.fluxchess.jcpi.models.GenericMove;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Semaphore;
import static com.fluxchess.pulse.Color.WHITE;
import static com.fluxchess.pulse.MoveList.MoveVariation;
/**
* This class implements our search in a separate thread to keep the main
* thread available for more commands.
*/
public final class Search implements Runnable {
static final int MAX_PLY = 256;
static final int MAX_DEPTH = 64;
private final Thread thread = new Thread(this);
private final Semaphore semaphore = new Semaphore(0);
private final IProtocol protocol;
private final Board board;
private final Evaluation evaluation = new Evaluation();
// Depth search
private int searchDepth = MAX_DEPTH;
// Nodes search
private long searchNodes = Long.MAX_VALUE;
// Time & Clock & Ponder search
private long searchTime = 0;
private Timer timer = null;
private boolean timerStopped = false;
private boolean doTimeManagement = false;
// Moves search
private final MoveList searchMoves = new MoveList();
// Search parameters
private final MoveList rootMoves = new MoveList();
private boolean abort = false;
private long startTime = 0;
private long statusStartTime = 0;
private long totalNodes = 0;
private int initialDepth = 1;
private int currentDepth = initialDepth;
private int currentMaxDepth = initialDepth;
private int currentMove = Move.NOMOVE;
private int currentMoveNumber = 0;
private final MoveVariation[] pv = new MoveVariation[MAX_PLY + 1];
/**
* This is our search timer for time & clock & ponder searches.
*/
private final class SearchTimer extends TimerTask {
@Override
public void run() {
timerStopped = true;
// If we finished the first iteration, we should have a result.
// In this case abort the search.
if (!doTimeManagement || currentDepth > initialDepth) {
abort = true;
}
}
}
static Search newDepthSearch(IProtocol protocol, Board board, int searchDepth) {
if (protocol == null) throw new IllegalArgumentException();
if (board == null) throw new IllegalArgumentException();
if (searchDepth < 1 || searchDepth > MAX_DEPTH) throw new IllegalArgumentException();
Search search = new Search(protocol, board);
search.searchDepth = searchDepth;
return search;
}
static Search newNodesSearch(IProtocol protocol, Board board, long searchNodes) {
if (protocol == null) throw new IllegalArgumentException();
if (board == null) throw new IllegalArgumentException();
if (searchNodes < 1) throw new IllegalArgumentException();
Search search = new Search(protocol, board);
search.searchNodes = searchNodes;
return search;
}
static Search newTimeSearch(IProtocol protocol, Board board, long searchTime) {
if (protocol == null) throw new IllegalArgumentException();
if (board == null) throw new IllegalArgumentException();
if (searchTime < 1) throw new IllegalArgumentException();
Search search = new Search(protocol, board);
search.searchTime = searchTime;
search.timer = new Timer(true);
return search;
}
static Search newMovesSearch(IProtocol protocol, Board board, List<GenericMove> searchMoves) {
if (protocol == null) throw new IllegalArgumentException();
if (board == null) throw new IllegalArgumentException();
if (searchMoves == null) throw new IllegalArgumentException();
Search search = new Search(protocol, board);
for (GenericMove move : searchMoves) {
search.searchMoves.entries[search.searchMoves.size++].move = Move.valueOf(move, board);
}
return search;
}
static Search newInfiniteSearch(IProtocol protocol, Board board) {
if (protocol == null) throw new IllegalArgumentException();
if (board == null) throw new IllegalArgumentException();
return new Search(protocol, board);
}
static Search newClockSearch(
IProtocol protocol, Board board,
long whiteTimeLeft, long whiteTimeIncrement, long blackTimeLeft, long blackTimeIncrement, int movesToGo) {
Search search = newPonderSearch(
protocol, board,
whiteTimeLeft, whiteTimeIncrement, blackTimeLeft, blackTimeIncrement, movesToGo
);
search.timer = new Timer(true);
return search;
}
static Search newPonderSearch(
IProtocol protocol, Board board,
long whiteTimeLeft, long whiteTimeIncrement, long blackTimeLeft, long blackTimeIncrement, int movesToGo) {
if (protocol == null) throw new IllegalArgumentException();
if (board == null) throw new IllegalArgumentException();
if (whiteTimeLeft < 1) throw new IllegalArgumentException();
if (whiteTimeIncrement < 0) throw new IllegalArgumentException();
if (blackTimeLeft < 1) throw new IllegalArgumentException();
if (blackTimeIncrement < 0) throw new IllegalArgumentException();
if (movesToGo < 0) throw new IllegalArgumentException();
Search search = new Search(protocol, board);
long timeLeft;
long timeIncrement;
if (board.activeColor == WHITE) {
timeLeft = whiteTimeLeft;
timeIncrement = whiteTimeIncrement;
} else {
timeLeft = blackTimeLeft;
timeIncrement = blackTimeIncrement;
}
// Don't use all of our time. Search only for 95%. Always leave 1 second as
// buffer time.
long maxSearchTime = (long) (timeLeft * 0.95) - 1000L;
if (maxSearchTime < 1) {
// We don't have enough time left. Search only for 1 millisecond, meaning
// get a result as fast as we can.
maxSearchTime = 1;
}
// Assume that we still have to do movesToGo number of moves. For every next
// move (movesToGo - 1) we will receive a time increment.
search.searchTime = (maxSearchTime + (movesToGo - 1) * timeIncrement) / movesToGo;
if (search.searchTime > maxSearchTime) {
search.searchTime = maxSearchTime;
}
search.doTimeManagement = true;
return search;
}
private Search(IProtocol protocol, Board board) {
assert protocol != null;
assert board != null;
this.protocol = protocol;
this.board = board;
for (int i = 0; i < pv.length; ++i) {
pv[i] = new MoveVariation();
}
}
void start() {
if (!thread.isAlive()) {
thread.setDaemon(true);
thread.start();
try {
// Wait for initialization
semaphore.acquire();
} catch (InterruptedException e) {
// Do nothing
}
}
}
void stop() {
if (thread.isAlive()) {
// Signal the search thread that we want to stop it
abort = true;
try {
// Wait for the thread to die
thread.join(5000);
} catch (InterruptedException e) {
// Do nothing
}
}
}
void ponderhit() {
if (thread.isAlive()) {
// Enable time management
timer = new Timer(true);
timer.schedule(new SearchTimer(), searchTime);
// If we finished the first iteration, we should have a result.
// In this case check the stop conditions.
if (currentDepth > initialDepth) {
checkStopConditions();
}
}
}
public void run() {
// Do all initialization before releasing the main thread to JCPI
startTime = System.currentTimeMillis();
statusStartTime = startTime;
if (timer != null) {
timer.schedule(new SearchTimer(), searchTime);
}
// Populate root move list
boolean isCheck = board.isCheck();
MoveGenerator moveGenerator = MoveGenerator.getMoveGenerator(board, 1, 0, isCheck);
int move;
while ((move = moveGenerator.next()) != Move.NOMOVE) {
rootMoves.entries[rootMoves.size].move = move;
rootMoves.entries[rootMoves.size].pv.moves[0] = move;
rootMoves.entries[rootMoves.size].pv.size = 1;
++rootMoves.size;
}
// Go...
semaphore.release();
//### BEGIN Iterative Deepening
for (currentDepth = initialDepth; currentDepth <= searchDepth; ++currentDepth) {
currentMaxDepth = 0;
sendStatus(true);
searchRoot(currentDepth, -Evaluation.INFINITY, Evaluation.INFINITY);
// Sort the root move list, so that the next iteration begins with the
// best move first.
rootMoves.sort();
checkStopConditions();
if (abort) {
break;
}
}
//### ENDOF Iterative Deepening
if (timer != null) {
timer.cancel();
}
// Update all stats
sendStatus(true);
// Get the best move and convert it to a GenericMove
GenericMove bestMove = null;
GenericMove ponderMove = null;
if (rootMoves.size > 0) {
bestMove = Move.toGenericMove(rootMoves.entries[0].move);
if (rootMoves.entries[0].pv.size >= 2) {
ponderMove = Move.toGenericMove(rootMoves.entries[0].pv.moves[1]);
}
}
// Send the best move to the GUI
protocol.send(new ProtocolBestMoveCommand(bestMove, ponderMove));
}
private void checkStopConditions() {
// We will check the stop conditions only if we are using time management,
// that is if our timer != null.
if (timer != null && doTimeManagement) {
if (timerStopped) {
abort = true;
} else {
// Check if we have only one move to make
if (rootMoves.size == 1) {
abort = true;
} else
// Check if we have a checkmate
if (Math.abs(rootMoves.entries[0].value) >= Evaluation.CHECKMATE_THRESHOLD
&& currentDepth >= (Evaluation.CHECKMATE - Math.abs(rootMoves.entries[0].value))) {
abort = true;
}
}
}
}
private void updateSearch(int ply) {
++totalNodes;
if (ply > currentMaxDepth) {
currentMaxDepth = ply;
}
if (searchNodes <= totalNodes) {
// Hard stop on number of nodes
abort = true;
}
pv[ply].size = 0;
sendStatus(false);
}
private void searchRoot(int depth, int alpha, int beta) {
int ply = 0;
updateSearch(ply);
// Abort conditions
if (abort) {
return;
}
for (int i = 0; i < rootMoves.size; ++i) {
rootMoves.entries[i].value = -Evaluation.INFINITY;
}
for (int i = 0; i < rootMoves.size; ++i) {
int move = rootMoves.entries[i].move;
// Search only moves specified in searchedMoves
if (searchMoves.size > 0) {
boolean found = false;
for (int j = 0; j < searchMoves.size; ++j) {
if (move == searchMoves.entries[j].move) {
found = true;
break;
}
}
if (!found) {
continue;
}
}
currentMove = move;
currentMoveNumber = i + 1;
sendStatus(true);
board.makeMove(move);
int value = -search(depth - 1, -beta, -alpha, ply + 1);
board.undoMove(move);
if (abort) {
return;
}
// Do we have a better value?
if (value > alpha) {
alpha = value;
rootMoves.entries[i].value = value;
savePV(move, pv[ply + 1], rootMoves.entries[i].pv);
sendMove(rootMoves.entries[i]);
}
}
if (rootMoves.size == 0) {
// The root position is a checkmate or stalemate. We cannot search
// further. Abort!
abort = true;
}
}
private int search(int depth, int alpha, int beta, int ply) {
// We are at a leaf/horizon. So calculate that value.
if (depth <= 0) {
// Descend into quiescent
return quiescent(0, alpha, beta, ply);
}
updateSearch(ply);
// Abort conditions
if (abort || ply == MAX_PLY) {
return evaluation.evaluate(board);
}
// Check the repetition table and fifty move rule
if (board.isRepetition() || board.halfMoveClock >= 100) {
return Evaluation.DRAW;
}
// Initialize
int bestValue = -Evaluation.INFINITY;
int searchedMoves = 0;
boolean isCheck = board.isCheck();
MoveGenerator moveGenerator = MoveGenerator.getMoveGenerator(board, depth, ply, isCheck);
int move;
while ((move = moveGenerator.next()) != Move.NOMOVE) {
++searchedMoves;
board.makeMove(move);
int value = -search(depth - 1, -beta, -alpha, ply + 1);
board.undoMove(move);
if (abort) {
return bestValue;
}
// Pruning
if (value > bestValue) {
bestValue = value;
// Do we have a better value?
if (value > alpha) {
alpha = value;
savePV(move, pv[ply + 1], pv[ply]);
// Is the value higher than beta?
if (value >= beta) {
// Cut-off
break;
}
}
}
}
// If we cannot move, check for checkmate and stalemate.
if (searchedMoves == 0) {
if (isCheck) {
// We have a check mate. This is bad for us, so return a -CHECKMATE.
return -Evaluation.CHECKMATE + ply;
} else {
// We have a stale mate. Return the draw value.
return Evaluation.DRAW;
}
}
return bestValue;
}
private int quiescent(int depth, int alpha, int beta, int ply) {
updateSearch(ply);
// Abort conditions
if (abort || ply == MAX_PLY) {
return evaluation.evaluate(board);
}
// Check the repetition table and fifty move rule
if (board.isRepetition() || board.halfMoveClock >= 100) {
return Evaluation.DRAW;
}
// Initialize
int bestValue = -Evaluation.INFINITY;
int searchedMoves = 0;
boolean isCheck = board.isCheck();
//### BEGIN Stand pat
if (!isCheck) {
bestValue = evaluation.evaluate(board);
// Do we have a better value?
if (bestValue > alpha) {
alpha = bestValue;
// Is the value higher than beta?
if (bestValue >= beta) {
// Cut-off
return bestValue;
}
}
}
//### ENDOF Stand pat
// Only generate capturing moves or evasion moves, in case we are in check.
MoveGenerator moveGenerator = MoveGenerator.getMoveGenerator(board, depth, ply, isCheck);
int move;
while ((move = moveGenerator.next()) != Move.NOMOVE) {
++searchedMoves;
board.makeMove(move);
int value = -quiescent(depth - 1, -beta, -alpha, ply + 1);
board.undoMove(move);
if (abort) {
return bestValue;
}
// Pruning
if (value > bestValue) {
bestValue = value;
// Do we have a better value?
if (value > alpha) {
alpha = value;
savePV(move, pv[ply + 1], pv[ply]);
// Is the value higher than beta?
if (value >= beta) {
// Cut-off
break;
}
}
}
}
// If we cannot move, check for checkmate.
if (searchedMoves == 0 && isCheck) {
// We have a check mate. This is bad for us, so return a -CHECKMATE.
return -Evaluation.CHECKMATE + ply;
}
return bestValue;
}
private void savePV(int move, MoveVariation src, MoveVariation dest) {
dest.moves[0] = move;
System.arraycopy(src.moves, 0, dest.moves, 1, src.size);
dest.size = src.size + 1;
}
private void sendStatus(boolean force) {
long currentTime = System.currentTimeMillis();
if ((currentTime - startTime >= 1000)
&& (force || (currentTime - statusStartTime) >= 1000)) {
ProtocolInformationCommand command = new ProtocolInformationCommand();
command.setDepth(currentDepth);
command.setMaxDepth(currentMaxDepth);
command.setNodes(totalNodes);
command.setTime(currentTime - startTime);
command.setNps(totalNodes * 1000 / (currentTime - startTime));
if (currentMove != Move.NOMOVE) {
command.setCurrentMove(Move.toGenericMove(currentMove));
command.setCurrentMoveNumber(currentMoveNumber);
}
protocol.send(command);
statusStartTime = System.currentTimeMillis();
}
}
private void sendMove(MoveList.Entry entry) {
long timeDelta = System.currentTimeMillis() - startTime;
ProtocolInformationCommand command = new ProtocolInformationCommand();
command.setDepth(currentDepth);
command.setMaxDepth(currentMaxDepth);
command.setNodes(totalNodes);
command.setTime(timeDelta);
command.setNps(timeDelta >= 1000 ? (totalNodes * 1000) / timeDelta : 0);
if (Math.abs(entry.value) >= Evaluation.CHECKMATE_THRESHOLD) {
// Calculate mate distance
int mateDepth = Evaluation.CHECKMATE - Math.abs(entry.value);
command.setMate(Integer.signum(entry.value) * (mateDepth + 1) / 2);
} else {
command.setCentipawns(entry.value);
}
List<GenericMove> pv = new ArrayList<>();
for (int i = 0; i < entry.pv.size; ++i) {
pv.add(Move.toGenericMove(entry.pv.moves[i]));
}
command.setMoveList(pv);
protocol.send(command);
statusStartTime = System.currentTimeMillis();
}
}
| Fix status output
| src/main/java/com/fluxchess/pulse/Search.java | Fix status output | |
Java | lgpl-2.1 | db8badf09baf1022ed77b3257f989d41fa155bb1 | 0 | jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,ACS-Community/ACS,csrg-utfsm/acscb,ACS-Community/ACS,ACS-Community/ACS,csrg-utfsm/acscb,jbarriosc/ACSUFRO,ACS-Community/ACS,jbarriosc/ACSUFRO,csrg-utfsm/acscb,csrg-utfsm/acscb,csrg-utfsm/acscb,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,csrg-utfsm/acscb,jbarriosc/ACSUFRO,ACS-Community/ACS,csrg-utfsm/acscb,ACS-Community/ACS,jbarriosc/ACSUFRO,csrg-utfsm/acscb,ACS-Community/ACS,ACS-Community/ACS | /*
* Created on Oct 26, 2005 by mschilli
*/
package alma.acs.commandcenter.app;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.ValidationException;
import alma.acs.commandcenter.CommandCenter;
import alma.entity.xmlbinding.acscommandcenterproject.AcsCommandCenterProject;
import alma.entity.xmlbinding.acscommandcenterproject.ContainerT;
import alma.entity.xmlbinding.acscommandcenterproject.ContainersT;
import alma.entity.xmlbinding.acscommandcenterproject.types.ModeType;
/**
*
* @author mschilli
*/
public class ProjectMaker {
protected CommandCenterLogic ctrl;
public ProjectMaker(CommandCenterLogic ctrl) {
this.ctrl = ctrl;
}
public AcsCommandCenterProject createProject () {
AcsCommandCenterProject ret = new AcsCommandCenterProject();
/* 3 env.variables are of interest: ACS_CDB, ACSROOT, ACSDATA.
* The first two transformed to Java system properties by
* the acscommandcenter script, not acsStartJava.
* We try to locate the cdb root directory and provide a fallback if
* we can't.
* We want to find additional schemas stored under ACSROOT of the
* acs installation. The additional schema path is stored in the sysprop
* "ACS.cdbpath" which we do not want to touch if it has been set by the
* user. Otherwise, we'll infer it from ACSROOT.
*/
String cdbroot = null;
{
// 1. $ACS_CDB
cdbroot = System.getProperty("ACS.cdbroot");
// 2. $ACSDATA/config/defaultCDB
if (cdbroot == null || cdbroot.equals("")) {
String acsdata = System.getProperty("ACS.data");
if (acsdata != null) {
acsdata += (acsdata.endsWith("/")) ? "" : "/";
cdbroot = acsdata + "config/defaultCDB";
}
}
// 3. fallback
if (cdbroot == null || cdbroot.equals("")) {
cdbroot = "/alma/ACS-4.0/acsdata/config/defaultCDB";
}
}
String cdbpath = null;
{
// 1. ACS.cdbpath
cdbpath = System.getProperty("ACS.cdbpath");
// 2. $ACSROOT/config/CDB/schemas
if (cdbpath == null || cdbpath.equals("")) {
String acsroot = System.getProperty("ACS.root");
if (acsroot != null) {
acsroot += (acsroot.endsWith("/")) ? "" : "/";
cdbpath = acsroot + "config/CDB/schemas";
// store, so cdb-jDAL can find it
if (cdbpath != null)
System.setProperty("ACS.cdbpath", cdbpath);
// TODO(msc): instead setting sysprop ACS.cdbpath: store in project, add field to gui
}
}
// 3. fallback to what?
}
ret.setMode(ModeType.LOCAL);
ret.setScriptBase(System.getProperty("ACS.baseport", "9"));
ret.setServicesLocalJavaRoot(cdbroot);
ret.setRemoteHost("");
ret.setToolAgainstManagerHost("");
ret.setToolAgainstManagerPort("");
ret.setToolAgainstNameService("");
ret.setToolAgainstInterfaceRepository("");
ret.setContainers(new ContainersT());
ret.getContainers().setAgainstManagerHost("");
ret.getContainers().setAgainstManagerPort("");
ret.getContainers().setAgainstCDB("");
ret.getContainers().setAgainstInterfaceRepository("");
ret.getContainers().addContainer(createContainer());
ret.setCreator(ctrl.projectCreatorId());
return ret;
}
public AcsCommandCenterProject loadProject (File f) throws MarshalException, ValidationException, FileNotFoundException, IOException {
AcsCommandCenterProject project = readProject(f);
if (isFromAnOutdatedVersion(project)) {
// could ask here whether upgrade is wanted
}
// checks and upgrades the project
sanitizeProject(project);
return project;
}
/**
* Purges passwords from the project, sets the version/creator info,
* then writes the project to disk.
*/
public void writeProject (AcsCommandCenterProject p, File f) throws IOException, MarshalException, ValidationException {
// --- clear all passwords from the model
p.setRemotePassword("");
for (int i = 0; i < p.getContainers().getContainerCount(); i++) {
p.getContainers().getContainer(i).setRemotePassword("");
}
// --- write to disk
BufferedWriter w = new BufferedWriter(new FileWriter(f));
p.marshal(w);
w.flush();
w.close();
}
protected ContainerT createContainer () {
ContainerT ret = new ContainerT();
ret.setType("java");
return ret;
}
/**
* Used to upgrade a project after it was read in.
*/
protected void sanitizeProject(AcsCommandCenterProject p) {
// --- upgrading projects to 4.1
if (p.getMode() == null) {
p.setMode(ModeType.LOCAL);
}
if (! p.hasToolRunAgainstDedicatedSettings()) {
p.setToolRunAgainstDedicatedSettings(false);
}
// --- upgrading projects to xyz
// --- store the fact that the project was sanitized
// by this current command center version
p.setCreator(ctrl.projectCreatorId());
}
protected AcsCommandCenterProject readProject (File f) throws FileNotFoundException, MarshalException, ValidationException, IOException {
BufferedReader r = new BufferedReader(new FileReader(f));
AcsCommandCenterProject p = AcsCommandCenterProject.unmarshalAcsCommandCenterProject(r);
r.close();
return p;
}
/**
* @since v4.1
*/
protected boolean isFromAnOutdatedVersion(AcsCommandCenterProject p) {
String v = p.getCreator();
if (v == null) {
return true;
}
// PENDING(msc): more sophisticated version checking
boolean a = v.equals("acc-v4.1");
boolean b = v.startsWith("acc-v4.1");
return !a; // sufficient in current version
}
}
// ================================================
// API
// ================================================
// ================================================
// Internal
// ================================================
// ================================================
// Inner Types
// ================================================
| LGPL/CommonSoftware/acscommandcenter/src/alma/acs/commandcenter/app/ProjectMaker.java | /*
* Created on Oct 26, 2005 by mschilli
*/
package alma.acs.commandcenter.app;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.ValidationException;
import alma.acs.commandcenter.CommandCenter;
import alma.entity.xmlbinding.acscommandcenterproject.AcsCommandCenterProject;
import alma.entity.xmlbinding.acscommandcenterproject.ContainerT;
import alma.entity.xmlbinding.acscommandcenterproject.ContainersT;
import alma.entity.xmlbinding.acscommandcenterproject.types.ModeType;
/**
*
* @author mschilli
*/
public class ProjectMaker {
protected CommandCenterLogic ctrl;
public ProjectMaker(CommandCenterLogic ctrl) {
this.ctrl = ctrl;
}
public AcsCommandCenterProject createProject () {
AcsCommandCenterProject ret = new AcsCommandCenterProject();
/* 3 env.variables are of interest: ACS_CDB, ACSROOT, ACSDATA.
* The first two transformed to Java system properties by
* the acscommandcenter script, not acsStartJava.
* We try to locate the cdb root directory and provide a fallback if
* we can't.
* We want to find additional schemas stored under ACSROOT of the
* acs installation. The additional schema path is stored in the sysprop
* "ACS.cdbpath" which we do not want to touch if it has been set by the
* user. Otherwise, we'll infer it from ACSROOT.
*/
String cdbroot = null;
{
// 1. $ACS_CDB
cdbroot = System.getProperty("ACS.cdbroot");
// 2. $ACSDATA/config/defaultCDB
if (cdbroot == null || cdbroot.equals("")) {
String acsdata = System.getProperty("ACS.data");
if (acsdata != null) {
acsdata += (acsdata.endsWith("/")) ? "" : "/";
cdbroot = acsdata + "config/defaultCDB";
}
}
// 3. fallback
if (cdbroot == null || cdbroot.equals("")) {
cdbroot = "/alma/ACS-4.0/acsdata/config/defaultCDB";
}
}
String cdbpath = null;
{
// 1. ACS.cdbpath
cdbpath = System.getProperty("ACS.cdbpath");
// 2. $ACSROOT/config/CDB/schemas
if (cdbpath == null || cdbpath.equals("")) {
String acsroot = System.getProperty("ACS.root");
if (acsroot != null) {
acsroot += (acsroot.endsWith("/")) ? "" : "/";
cdbpath = acsroot + "config/CDB/schemas";
// store, so cdb-jDAL can find it
if (cdbpath != null)
System.setProperty("ACS.cdbpath", cdbpath);
// TODO(msc): instead setting sysprop ACS.cdbpath: store in project, add field to gui
}
}
// 3. fallback to what?
}
ret.setMode(ModeType.LOCAL);
ret.setScriptBase(System.getProperty("ACS.baseport", "9"));
ret.setServicesLocalJavaRoot(cdbroot);
ret.setRemoteHost("");
ret.setToolAgainstManagerHost("");
ret.setToolAgainstManagerPort("");
ret.setToolAgainstNameService("");
ret.setToolAgainstInterfaceRepository("");
ret.setContainers(new ContainersT());
ret.getContainers().setAgainstManagerHost("");
ret.getContainers().setAgainstManagerPort("");
ret.getContainers().setAgainstCDB("");
ret.getContainers().setAgainstInterfaceRepository("");
ret.getContainers().addContainer(createContainer());
ret.setCreator(ctrl.projectCreatorId());
return ret;
}
public AcsCommandCenterProject loadProject (File f) throws MarshalException, ValidationException, FileNotFoundException {
AcsCommandCenterProject project = readProject(f);
if (isFromAnOutdatedVersion(project)) {
// could ask here whether upgrade is wanted
}
// checks and upgrades the project
sanitizeProject(project);
return project;
}
/**
* Purges passwords from the project, sets the version/creator info,
* then writes the project to disk.
*/
public void writeProject (AcsCommandCenterProject p, File f) throws IOException, MarshalException, ValidationException {
// --- clear all passwords from the model
p.setRemotePassword("");
for (int i = 0; i < p.getContainers().getContainerCount(); i++) {
p.getContainers().getContainer(i).setRemotePassword("");
}
// --- write to disk
BufferedWriter w = new BufferedWriter(new FileWriter(f));
p.marshal(w);
}
protected ContainerT createContainer () {
ContainerT ret = new ContainerT();
ret.setType("java");
return ret;
}
/**
* Used to upgrade a project after it was read in.
*/
protected void sanitizeProject(AcsCommandCenterProject p) {
// --- upgrading projects to 4.1
if (p.getMode() == null) {
p.setMode(ModeType.LOCAL);
}
if (! p.hasToolRunAgainstDedicatedSettings()) {
p.setToolRunAgainstDedicatedSettings(false);
}
// --- upgrading projects to xyz
// --- store the fact that the project was sanitized
// by this current command center version
p.setCreator(ctrl.projectCreatorId());
}
protected AcsCommandCenterProject readProject (File f) throws FileNotFoundException, MarshalException, ValidationException {
BufferedReader r = new BufferedReader(new FileReader(f));
AcsCommandCenterProject p = AcsCommandCenterProject.unmarshalAcsCommandCenterProject(r);
return p;
}
/**
* @since v4.1
*/
protected boolean isFromAnOutdatedVersion(AcsCommandCenterProject p) {
String v = p.getCreator();
if (v == null) {
return true;
}
// PENDING(msc): more sophisticated version checking
boolean a = v.equals("acc-v4.1");
boolean b = v.startsWith("acc-v4.1");
return !a; // sufficient in current version
}
}
// ================================================
// API
// ================================================
// ================================================
// Internal
// ================================================
// ================================================
// Inner Types
// ================================================
| now flushes the writer when saving a project
git-svn-id: afcf11d89342f630bd950d18a70234a9e277d909@63350 523d945c-050c-4681-91ec-863ad3bb968a
| LGPL/CommonSoftware/acscommandcenter/src/alma/acs/commandcenter/app/ProjectMaker.java | now flushes the writer when saving a project | |
Java | lgpl-2.1 | f92188d40e92cc48b7e359160fc7dc31dec8ed27 | 0 | deegree/deegree3,deegree/deegree3,deegree/deegree3,deegree/deegree3,deegree/deegree3 | //$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 by:
Department of Geography, University of Bonn
and
lat/lon GmbH
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library 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 Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: info@deegree.org
----------------------------------------------------------------------------*/
package org.deegree.services.wfs;
import static org.deegree.commons.xml.CommonNamespaces.FES_20_NS;
import static org.deegree.commons.xml.CommonNamespaces.FES_PREFIX;
import static org.deegree.commons.xml.CommonNamespaces.GMLNS;
import static org.deegree.commons.xml.CommonNamespaces.GML_PREFIX;
import static org.deegree.commons.xml.CommonNamespaces.OGCNS;
import static org.deegree.commons.xml.CommonNamespaces.OGC_PREFIX;
import static org.deegree.commons.xml.CommonNamespaces.XLINK_PREFIX;
import static org.deegree.commons.xml.CommonNamespaces.XLNNS;
import static org.deegree.commons.xml.CommonNamespaces.XSINS;
import static org.deegree.commons.xml.CommonNamespaces.XSI_PREFIX;
import static org.deegree.protocol.wfs.WFSConstants.VERSION_100;
import static org.deegree.protocol.wfs.WFSConstants.VERSION_110;
import static org.deegree.protocol.wfs.WFSConstants.VERSION_200;
import static org.deegree.protocol.wfs.WFSConstants.WFS_100_CAPABILITIES_SCHEMA_URL;
import static org.deegree.protocol.wfs.WFSConstants.WFS_110_SCHEMA_URL;
import static org.deegree.protocol.wfs.WFSConstants.WFS_200_NS;
import static org.deegree.protocol.wfs.WFSConstants.WFS_200_SCHEMA_URL;
import static org.deegree.protocol.wfs.WFSConstants.WFS_NS;
import static org.deegree.protocol.wfs.WFSConstants.WFS_PREFIX;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import org.deegree.commons.tom.ows.Version;
import org.deegree.commons.utils.Pair;
import org.deegree.commons.utils.StringUtils;
import org.deegree.commons.xml.CommonNamespaces;
import org.deegree.cs.coordinatesystems.ICRS;
import org.deegree.cs.persistence.CRSManager;
import org.deegree.feature.persistence.FeatureStore;
import org.deegree.feature.persistence.FeatureStoreException;
import org.deegree.feature.types.FeatureType;
import org.deegree.filter.xml.FilterCapabilitiesExporter;
import org.deegree.geometry.Envelope;
import org.deegree.geometry.GeometryTransformer;
import org.deegree.geometry.SimpleGeometryFactory;
import org.deegree.geometry.io.CoordinateFormatter;
import org.deegree.geometry.io.DecimalCoordinateFormatter;
import org.deegree.geometry.primitive.Point;
import org.deegree.protocol.ows.capabilities.GetCapabilities;
import org.deegree.protocol.wfs.WFSRequestType;
import org.deegree.services.controller.OGCFrontController;
import org.deegree.services.controller.ows.capabilities.OWSCapabilitiesXMLAdapter;
import org.deegree.services.controller.ows.capabilities.OWSOperation;
import org.deegree.services.jaxb.controller.DCPType;
import org.deegree.services.jaxb.metadata.ServiceIdentificationType;
import org.deegree.services.jaxb.metadata.ServiceProviderType;
import org.deegree.services.jaxb.wfs.FeatureTypeMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
/**
* Handles a single {@link GetCapabilities} requests for the {@link WebFeatureService}.
*
* @author <a href="mailto:schneider@lat-lon.de">Markus Schneider </a>
* @author last edited by: $Author:$
*
* @version $Revision:$, $Date:$
*/
class GetCapabilitiesHandler extends OWSCapabilitiesXMLAdapter {
private static Logger LOG = LoggerFactory.getLogger( GetCapabilitiesHandler.class );
private static GeometryTransformer transformer;
// used for formatting WGS84 bounding box coordinates
private static CoordinateFormatter formatter = new DecimalCoordinateFormatter();
static {
try {
transformer = new GeometryTransformer( "EPSG:4326" );
} catch ( Exception e ) {
LOG.error( "Could not initialize GeometryTransformer." );
}
}
private final Version version;
private final XMLStreamWriter writer;
private final ServiceIdentificationType serviceId;
private final ServiceProviderType serviceProvider;
private final Collection<FeatureType> servedFts;
private final Map<QName, FeatureTypeMetadata> ftNameToFtMetadata;
private final Set<String> sections;
private final boolean enableTransactions;
private final List<ICRS> querySRS;
private final WFSFeatureStoreManager service;
private final WebFeatureService master;
private final Element extendedCapabilities;
private final String metadataUrlTemplate;
GetCapabilitiesHandler( WebFeatureService master, WFSFeatureStoreManager service, Version version,
XMLStreamWriter xmlWriter, ServiceIdentificationType serviceId,
ServiceProviderType serviceProvider, Collection<FeatureType> servedFts,
String metadataUrlTemplate, Map<QName, FeatureTypeMetadata> ftNameToFtMetadata,
Set<String> sections, boolean enableTransactions, List<ICRS> querySRS,
Element extendedCapabilities ) {
this.master = master;
this.service = service;
this.version = version;
this.writer = xmlWriter;
this.serviceId = serviceId;
this.serviceProvider = serviceProvider;
this.servedFts = servedFts;
this.metadataUrlTemplate = metadataUrlTemplate;
this.ftNameToFtMetadata = ftNameToFtMetadata;
this.sections = sections;
this.enableTransactions = enableTransactions;
this.querySRS = querySRS;
this.extendedCapabilities = extendedCapabilities;
}
/**
* Produces a <code>WFS_Capabilities</code> document compliant to the specified WFS version.
*
* @throws XMLStreamException
* @throws IllegalArgumentException
* if the specified version is not 1.0.0, 1.1.0 or 2.0.0
*/
void export()
throws XMLStreamException {
if ( VERSION_100.equals( version ) ) {
export100();
} else if ( VERSION_110.equals( version ) ) {
export110();
} else if ( VERSION_200.equals( version ) ) {
export200();
} else {
throw new IllegalArgumentException( "Version '" + version + "' is not supported." );
}
}
/**
* Produces a <code>WFS_Capabilities</code> document that complies to the WFS 1.0.0 specification.
*
* @throws XMLStreamException
*/
void export100()
throws XMLStreamException {
writer.setDefaultNamespace( WFS_NS );
writer.writeStartElement( WFS_NS, "WFS_Capabilities" );
writer.writeAttribute( "version", "1.0.0" );
writer.writeDefaultNamespace( WFS_NS );
writer.writeNamespace( OWS_PREFIX, OWS_NS );
writer.writeNamespace( OGC_PREFIX, OGCNS );
writer.writeNamespace( GML_PREFIX, GMLNS );
writer.writeNamespace( XLINK_PREFIX, XLN_NS );
writer.writeAttribute( "xsi", XSINS, "schemaLocation", WFS_NS + " " + WFS_100_CAPABILITIES_SCHEMA_URL );
// wfs:Service (type="wfs:ServiceType")
exportService100();
// wfs:Capability (type="wfs:CapabilityType")
exportCapability100();
// wfs:FeatureTypeList (type="wfs:FeatureTypeListType")
writer.writeStartElement( WFS_NS, "FeatureTypeList" );
exportOperations100();
for ( FeatureType ft : servedFts ) {
// wfs:FeatureType
writer.writeStartElement( WFS_NS, "FeatureType" );
// wfs:Name
writer.writeStartElement( WFS_NS, "Name" );
QName ftName = ft.getName();
FeatureTypeMetadata ftMd = ftNameToFtMetadata.get( ftName );
String prefix = null;
if ( ftName.getNamespaceURI() != XMLConstants.NULL_NS_URI ) {
prefix = ftName.getPrefix();
if ( ftName.getPrefix() == null || ftName.getPrefix().equals( "" ) ) {
LOG.warn( "Feature type '" + ftName + "' has no prefix!? This should not happen." );
prefix = "app";
}
writer.writeNamespace( prefix, ftName.getNamespaceURI() );
writer.writeCharacters( prefix + ":" + ftName.getLocalPart() );
} else {
writer.writeCharacters( ftName.getLocalPart() );
}
writer.writeEndElement();
// wfs:Title (minOccurs=0, maxOccurs=1)
writer.writeStartElement( WFS_NS, "Title" );
if ( ftMd != null && ftMd.getTitle() != null ) {
writer.writeCharacters( ftMd.getTitle() );
} else {
if ( prefix != null ) {
writer.writeCharacters( prefix + ":" + ftName.getLocalPart() );
} else {
writer.writeCharacters( ftName.getLocalPart() );
}
}
writer.writeEndElement();
// wfs:Abstract (minOccurs=0, maxOccurs=1)
if ( ftMd != null && ftMd.getAbstract() != null ) {
writer.writeStartElement( WFS_NS, "Abstract" );
writer.writeCharacters( ftMd.getAbstract() );
writer.writeEndElement();
}
// wfs:Keywords (minOccurs=0, maxOccurs=1)
// if ( ft.getKeywords() != null ) {
// writer.writeStartElement( WFS_NS, "Keywords" );
// writer.writeCharacters( ft.getKeywords() );
// writer.writeEndElement();
// }
// wfs:SRS (minOccurs=1, maxOccurs=1)
writer.writeStartElement( WFS_NS, "SRS" );
writer.writeCharacters( querySRS.get( 0 ).getAlias() );
writer.writeEndElement();
// wfs:Operations (minOccurs=0, maxOccurs=1)
exportOperations100();
// wfs:LatLongBoundingBox (minOccurs=0, maxOccurs=unbounded)
Envelope env = null;
try {
FeatureStore fs = service.getStore( ftName );
env = fs.getEnvelope( ftName );
} catch ( FeatureStoreException e ) {
LOG.error( "Error retrieving envelope from FeatureStore: " + e.getMessage(), e );
}
if ( env != null ) {
try {
env = transformer.transform( env );
Point min = env.getMin();
Point max = env.getMax();
double minX = min.get0();
double minY = min.get1();
double maxX = max.get0();
double maxY = max.get1();
writer.writeStartElement( WFS_NS, "LatLongBoundingBox" );
writer.writeAttribute( "minx", "" + formatter.format( minX ) );
writer.writeAttribute( "miny", "" + formatter.format( minY ) );
writer.writeAttribute( "maxx", "" + formatter.format( maxX ) );
writer.writeAttribute( "maxy", "" + formatter.format( maxY ) );
writer.writeEndElement();
} catch ( Exception e ) {
LOG.error( "Cannot generate WGS84 envelope for feature type '" + ftName + "'.", e );
}
}
// wfs:MetadataURL (minOccurs=0, maxOccurs=unbounded)
String metadataUrl = getMetadataURL( ftMd );
if ( metadataUrl != null ) {
writer.writeStartElement( WFS_NS, "MetadataURL" );
writer.writeAttribute( "type", "TC211" );
writer.writeAttribute( "format", "XML" );
writer.writeCharacters( metadataUrl );
writer.writeEndElement();
}
writer.writeEndElement();
}
writer.writeEndElement();
// ogc:Filter_Capabilities
FilterCapabilitiesExporter.export100( writer );
writer.writeEndElement();
writer.writeEndDocument();
}
private String getMetadataURL( FeatureTypeMetadata ftMd ) {
if ( metadataUrlTemplate == null || ftMd == null || ftMd.getMetadataSetId() == null ) {
return null;
}
return StringUtils.replaceAll( metadataUrlTemplate, "${metadataSetId}", ftMd.getMetadataSetId() );
}
private void exportCapability100()
throws XMLStreamException {
writer.writeStartElement( WFS_NS, "Capability" );
writer.writeStartElement( WFS_NS, "Request" );
String getURL = OGCFrontController.getHttpGetURL();
String postURL = OGCFrontController.getHttpPostURL();
// wfs:GetCapabilities
writer.writeStartElement( WFS_NS, WFSRequestType.GetCapabilities.name() );
exportGetDCPType100( getURL );
exportPostDCPType100( postURL );
writer.writeEndElement();
// wfs:DescribeFeatureType
writer.writeStartElement( WFS_NS, WFSRequestType.DescribeFeatureType.name() );
writer.writeStartElement( WFS_NS, "SchemaDescriptionLanguage" );
writer.writeStartElement( WFS_NS, "XMLSCHEMA" );
writer.writeEndElement();
writer.writeEndElement();
exportGetDCPType100( getURL );
exportPostDCPType100( postURL );
writer.writeEndElement();
if ( enableTransactions ) {
// wfs:Transaction
writer.writeStartElement( WFS_NS, WFSRequestType.Transaction.name() );
exportGetDCPType100( getURL );
exportPostDCPType100( postURL );
writer.writeEndElement();
}
// wfs:GetFeature
writer.writeStartElement( WFS_NS, WFSRequestType.GetFeature.name() );
writer.writeStartElement( WFS_NS, "ResultFormat" );
writer.writeEmptyElement( WFS_NS, "GML2" );
writer.writeEndElement();
exportGetDCPType100( getURL );
exportPostDCPType100( postURL );
writer.writeEndElement();
if ( enableTransactions ) {
// wfs:GetFeatureWithLock
writer.writeStartElement( WFS_NS, WFSRequestType.GetFeatureWithLock.name() );
writer.writeStartElement( WFS_NS, "ResultFormat" );
writer.writeEmptyElement( WFS_NS, "GML2" );
writer.writeEndElement();
exportGetDCPType100( getURL );
exportPostDCPType100( postURL );
writer.writeEndElement();
// wfs:LockFeature
writer.writeStartElement( WFS_NS, WFSRequestType.LockFeature.name() );
exportGetDCPType100( getURL );
exportPostDCPType100( postURL );
writer.writeEndElement();
}
writer.writeEndElement();
writer.writeEndElement();
}
private void exportService100()
throws XMLStreamException {
writer.writeStartElement( WFS_NS, "Service" );
if ( serviceId != null && serviceId.getTitle() != null && !serviceId.getTitle().isEmpty() ) {
// wfs:Name (type="string")
writeElement( writer, WFS_NS, "Name", serviceId.getTitle().get( 0 ) );
// wfs:Title (type="string)
writeElement( writer, WFS_NS, "Title", serviceId.getTitle().get( 0 ) );
} else {
writeElement( writer, WFS_NS, "Name", "" );
writeElement( writer, WFS_NS, "Title", "" );
}
if ( serviceId != null && serviceId.getAbstract() != null && !serviceId.getAbstract().isEmpty() ) {
// wfs:Abstract
writeElement( writer, WFS_NS, "Abstract", serviceId.getAbstract().get( 0 ) );
}
// wfs:Keywords
// wfs:OnlineResource (type=???)
writeElement( writer, WFS_NS, "OnlineResource", serviceProvider.getServiceContact().getOnlineResource() );
// wfs:Fees
if ( serviceId != null && serviceId.getFees() != null ) {
writeElement( writer, WFS_NS, "Fees", serviceId.getFees() );
}
// wfs:AccessConstraints
writer.writeEndElement();
}
private void exportOperations100()
throws XMLStreamException {
writer.writeStartElement( WFS_NS, "Operations" );
writer.writeEmptyElement( WFS_NS, "Query" );
if ( enableTransactions ) {
writer.writeEmptyElement( WFS_NS, "Insert" );
writer.writeEmptyElement( WFS_NS, "Update" );
writer.writeEmptyElement( WFS_NS, "Delete" );
}
if ( enableTransactions ) {
writer.writeEmptyElement( WFS_NS, "Lock" );
}
writer.writeEndElement();
}
private void exportGetDCPType100( String getURL )
throws XMLStreamException {
if ( getURL != null ) {
writer.writeStartElement( WFS_NS, "DCPType" );
writer.writeStartElement( WFS_NS, "HTTP" );
// ows:Get (type="ows:GetType")
writer.writeStartElement( WFS_NS, "Get" );
writer.writeAttribute( "onlineResource", getURL );
writer.writeEndElement();
writer.writeEndElement();
writer.writeEndElement();
}
}
private void exportPostDCPType100( String postURL )
throws XMLStreamException {
if ( postURL != null ) {
writer.writeStartElement( WFS_NS, "DCPType" );
writer.writeStartElement( WFS_NS, "HTTP" );
// ows:Post (type="ows:PostType")
writer.writeStartElement( WFS_NS, "Post" );
writer.writeAttribute( "onlineResource", postURL );
writer.writeEndElement();
writer.writeEndElement();
writer.writeEndElement();
}
}
/**
* Produces a <code>WFS_Capabilities</code> document that complies to the WFS 1.1.0 specification.
*
* @throws XMLStreamException
*/
void export110()
throws XMLStreamException {
writer.setDefaultNamespace( WFS_NS );
writer.writeStartElement( WFS_NS, "WFS_Capabilities" );
writer.writeAttribute( "version", "1.1.0" );
writer.writeDefaultNamespace( WFS_NS );
writer.writeNamespace( OWS_PREFIX, OWS_NS );
writer.writeNamespace( OGC_PREFIX, OGCNS );
writer.writeNamespace( GML_PREFIX, GMLNS );
writer.writeNamespace( XLINK_PREFIX, XLNNS );
writer.writeAttribute( XSI_PREFIX, XSINS, "schemaLocation", WFS_NS + " " + WFS_110_SCHEMA_URL );
// ows:ServiceIdentification
if ( sections == null || sections.contains( "SERVICEIDENTIFICATION" ) ) {
List<Version> serviceVersions = new ArrayList<Version>();
serviceVersions.add( Version.parseVersion( "1.1.0" ) );
exportServiceIdentification100( writer, serviceId, "WFS", serviceVersions );
}
// ows:ServiceProvider
if ( sections == null || sections.contains( "SERVICEPROVIDER" ) ) {
exportServiceProvider100( writer, serviceProvider );
}
// ows:OperationsMetadata
if ( sections == null || sections.contains( "OPERATIONSMETADATA" ) ) {
List<OWSOperation> operations = new ArrayList<OWSOperation>();
DCPType dcp = new DCPType();
dcp.setHTTPGet( OGCFrontController.getHttpGetURL() );
dcp.setHTTPPost( OGCFrontController.getHttpPostURL() );
// DescribeFeatureType
List<Pair<String, List<String>>> params = new ArrayList<Pair<String, List<String>>>();
List<String> outputFormats = new ArrayList<String>( master.getOutputFormats() );
params.add( new Pair<String, List<String>>( "outputFormat", outputFormats ) );
List<Pair<String, List<String>>> constraints = new ArrayList<Pair<String, List<String>>>();
operations.add( new OWSOperation( WFSRequestType.DescribeFeatureType.name(), dcp, params, constraints ) );
// GetCapabilities
params = new ArrayList<Pair<String, List<String>>>();
params.add( new Pair<String, List<String>>( "AcceptVersions", master.getOfferedVersions() ) );
params.add( new Pair<String, List<String>>( "AcceptFormats", Collections.singletonList( "text/xml" ) ) );
// List<String> sections = new ArrayList<String>();
// sections.add( "ServiceIdentification" );
// sections.add( "ServiceProvider" );
// sections.add( "OperationsMetadata" );
// sections.add( "FeatureTypeList" );
// sections.add( "Filter_Capabilities" );
// params.add( new Pair<String, List<String>>( "Sections", sections ) );
constraints = new ArrayList<Pair<String, List<String>>>();
operations.add( new OWSOperation( WFSRequestType.GetCapabilities.name(), dcp, params, constraints ) );
// GetFeature
params = new ArrayList<Pair<String, List<String>>>();
params.add( new Pair<String, List<String>>( "resultType",
Arrays.asList( new String[] { "results", "hits" } ) ) );
params.add( new Pair<String, List<String>>( "outputFormat", outputFormats ) );
operations.add( new OWSOperation( WFSRequestType.GetFeature.name(), dcp, params, constraints ) );
// GetFeatureWithLock
if ( enableTransactions ) {
params = new ArrayList<Pair<String, List<String>>>();
params.add( new Pair<String, List<String>>( "resultType", Arrays.asList( new String[] { "results",
"hits" } ) ) );
params.add( new Pair<String, List<String>>( "outputFormat", outputFormats ) );
operations.add( new OWSOperation( WFSRequestType.GetFeatureWithLock.name(), dcp, params, constraints ) );
}
// GetGmlObject
params = new ArrayList<Pair<String, List<String>>>();
params = new ArrayList<Pair<String, List<String>>>();
params.add( new Pair<String, List<String>>( "outputFormat", outputFormats ) );
constraints = new ArrayList<Pair<String, List<String>>>();
operations.add( new OWSOperation( WFSRequestType.GetGmlObject.name(), dcp, params, constraints ) );
if ( enableTransactions ) {
// LockFeature
params = new ArrayList<Pair<String, List<String>>>();
params.add( new Pair<String, List<String>>( "lockAction",
Arrays.asList( new String[] { "ALL", "SOME" } ) ) );
operations.add( new OWSOperation( WFSRequestType.LockFeature.name(), dcp, params, constraints ) );
// Transaction
params = new ArrayList<Pair<String, List<String>>>();
params.add( new Pair<String, List<String>>( "inputFormat", outputFormats ) );
params.add( new Pair<String, List<String>>( "idgen", Arrays.asList( new String[] { "GenerateNew",
"UseExisting",
"ReplaceDuplicate" } ) ) );
params.add( new Pair<String, List<String>>( "releaseAction", Arrays.asList( new String[] { "ALL",
"SOME" } ) ) );
operations.add( new OWSOperation( WFSRequestType.Transaction.name(), dcp, params, constraints ) );
}
// TODO
exportOperationsMetadata100( writer, operations, extendedCapabilities );
}
// wfs:FeatureTypeList
if ( sections == null || sections.contains( "FEATURETYPELIST" ) ) {
writer.writeStartElement( WFS_NS, "FeatureTypeList" );
for ( FeatureType ft : servedFts ) {
QName ftName = ft.getName();
FeatureTypeMetadata ftMd = ftNameToFtMetadata.get( ftName );
writer.writeStartElement( WFS_NS, "FeatureType" );
// wfs:Name
writer.writeStartElement( WFS_NS, "Name" );
String prefix = ftName.getPrefix();
if ( prefix == null || prefix.equals( "" ) ) {
LOG.warn( "Feature type '" + ftName + "' has no prefix!? This should not happen." );
prefix = "app";
}
if ( ftName.getNamespaceURI() != XMLConstants.NULL_NS_URI ) {
// TODO what about the namespace prefix?
writer.writeNamespace( prefix, ftName.getNamespaceURI() );
writer.writeCharacters( prefix + ":" + ftName.getLocalPart() );
} else {
writer.writeCharacters( ftName.getLocalPart() );
}
writer.writeEndElement();
// wfs:Title
writer.writeStartElement( WFS_NS, "Title" );
if ( ftMd != null && ftMd.getTitle() != null ) {
writer.writeCharacters( ftMd.getTitle() );
} else {
writer.writeCharacters( prefix + ":" + ftName.getLocalPart() );
}
writer.writeEndElement();
// wfs:Abstract (minOccurs=0, maxOccurs=1)
if ( ftMd != null && ftMd.getAbstract() != null ) {
writer.writeStartElement( WFS_NS, "Abstract" );
writer.writeCharacters( ftMd.getAbstract() );
writer.writeEndElement();
}
// ows:Keywords (minOccurs=0, maxOccurs=unbounded)
// writer.writeStartElement( OWS_NS, "Keywords" );
// writer.writeCharacters( "keywords" );
// writer.writeEndElement();
// wfs:DefaultSRS / wfs:NoSRS
FeatureStore fs = service.getStore( ftName );
writeElement( writer, WFS_NS, "DefaultSRS", querySRS.get( 0 ).getAlias() );
// wfs:OtherSRS
for ( int i = 1; i < querySRS.size(); i++ ) {
writeElement( writer, WFS_NS, "OtherSRS", querySRS.get( i ).getAlias() );
}
writeOutputFormats110( writer );
// ows:WGS84BoundingBox (minOccurs=0, maxOccurs=unbounded)
Envelope env = null;
try {
env = fs.getEnvelope( ftName );
} catch ( FeatureStoreException e ) {
LOG.error( "Error retrieving envelope from FeatureStore: " + e.getMessage(), e );
}
if ( env != null ) {
try {
env = transformer.transform( env );
} catch ( Exception e ) {
LOG.error( "Cannot transform feature type envelope to WGS84." );
}
} else {
env = new SimpleGeometryFactory().createEnvelope( -180, -90, 180, 90,
CRSManager.getCRSRef( "EPSG:4326" ) );
}
writer.writeStartElement( OWS_NS, "WGS84BoundingBox" );
Point min = env.getMin();
Point max = env.getMax();
double minX = -180.0;
double minY = -90.0;
double maxX = 180.0;
double maxY = 90.0;
try {
minX = min.get0();
minY = min.get1();
maxX = max.get0();
maxY = max.get1();
} catch ( ArrayIndexOutOfBoundsException e ) {
LOG.error( "Cannot generate WGS84 envelope for feature type '" + ftName + "'. Using full extent.",
e );
minX = -180.0;
minY = -90.0;
maxX = 180.0;
maxY = 90.0;
}
writer.writeStartElement( OWS_NS, "LowerCorner" );
writer.writeCharacters( formatter.format( minX ) + " " + formatter.format( minY ) );
writer.writeEndElement();
writer.writeStartElement( OWS_NS, "UpperCorner" );
writer.writeCharacters( formatter.format( maxX ) + " " + formatter.format( maxY ) );
writer.writeEndElement();
writer.writeEndElement();
// TODO Operations
// wfs:MetadataURL (minOccurs=0, maxOccurs=unbounded)
String metadataUrl = getMetadataURL( ftMd );
if ( metadataUrl != null ) {
writer.writeStartElement( WFS_NS, "MetadataURL" );
writer.writeAttribute( "type", "19139" );
writer.writeAttribute( "format", "text/xml" );
writer.writeCharacters( metadataUrl );
writer.writeEndElement();
}
writer.writeEndElement();
}
writer.writeEndElement();
}
// wfs:ServesGMLObjectTypeList
if ( sections == null || sections.contains( "SERVESGMLOBJECTTYPELIST" ) ) {
// TODO
}
// wfs:SupportsGMLObjectTypeList
if ( sections == null || sections.contains( "SUPPORTSGMLOBJECTTYPELIST" ) ) {
// TODO
}
// 'ogc:Filter_Capabilities' (mandatory)
FilterCapabilitiesExporter.export110( writer );
writer.writeEndElement();
writer.writeEndDocument();
}
private void writeOutputFormats110( XMLStreamWriter writer )
throws XMLStreamException {
writer.writeStartElement( WFS_PREFIX, "OutputFormats", WFS_NS );
for ( String format : master.getOutputFormats() ) {
writer.writeStartElement( WFS_PREFIX, "Format", WFS_NS );
writer.writeCharacters( format );
writer.writeEndElement();
}
writer.writeEndElement();
}
/**
* Produces a <code>WFS_Capabilities</code> document that complies to the WFS 2.0.0 specification.
*
* @throws XMLStreamException
*/
void export200()
throws XMLStreamException {
writer.setDefaultNamespace( WFS_200_NS );
writer.writeStartElement( WFS_200_NS, "WFS_Capabilities" );
writer.writeAttribute( "version", "2.0.0" );
writer.writeDefaultNamespace( WFS_200_NS );
writer.writeNamespace( OWS_PREFIX, OWS110_NS );
writer.writeNamespace( OGC_PREFIX, OGCNS );
writer.writeNamespace( FES_PREFIX, FES_20_NS );
writer.writeNamespace( GML_PREFIX, GMLNS );
writer.writeNamespace( XLINK_PREFIX, XLN_NS );
writer.writeAttribute( "xsi", CommonNamespaces.XSINS, "schemaLocation", WFS_200_NS + " " + WFS_200_SCHEMA_URL );
// ows:ServiceIdentification
if ( sections == null || sections.contains( "ServiceIdentification" ) ) {
List<Version> serviceVersions = new ArrayList<Version>();
serviceVersions.add( Version.parseVersion( "2.0.0" ) );
exportServiceIdentification110( writer, serviceId, "WFS", serviceVersions );
}
// ows:ServiceProvider
if ( sections == null || sections.contains( "ServiceProvider" ) ) {
exportServiceProvider110( writer, serviceProvider );
}
// ows:OperationsMetadata
if ( sections == null || sections.contains( "OPERATIONSMETADATA" ) ) {
List<OWSOperation> operations = new ArrayList<OWSOperation>();
DCPType dcp = new DCPType();
dcp.setHTTPGet( OGCFrontController.getHttpGetURL() );
dcp.setHTTPPost( OGCFrontController.getHttpPostURL() );
// DescribeFeatureType
List<Pair<String, List<String>>> params = new ArrayList<Pair<String, List<String>>>();
List<String> outputFormats = new ArrayList<String>( master.getOutputFormats() );
params.add( new Pair<String, List<String>>( "outputFormat", outputFormats ) );
List<Pair<String, List<String>>> constraints = new ArrayList<Pair<String, List<String>>>();
operations.add( new OWSOperation( WFSRequestType.DescribeFeatureType.name(), dcp, params, constraints ) );
// GetCapabilities
params = new ArrayList<Pair<String, List<String>>>();
params.add( new Pair<String, List<String>>( "AcceptVersions", master.getOfferedVersions() ) );
params.add( new Pair<String, List<String>>( "AcceptFormats", Collections.singletonList( "text/xml" ) ) );
List<String> sections = new ArrayList<String>();
sections.add( "ServiceIdentification" );
sections.add( "ServiceProvider" );
sections.add( "OperationsMetadata" );
sections.add( "FeatureTypeList" );
sections.add( "Filter_Capabilities" );
params.add( new Pair<String, List<String>>( "Sections", sections ) );
constraints = new ArrayList<Pair<String, List<String>>>();
operations.add( new OWSOperation( WFSRequestType.GetCapabilities.name(), dcp, params, constraints ) );
// GetFeature
params = new ArrayList<Pair<String, List<String>>>();
params.add( new Pair<String, List<String>>( "outputFormat", outputFormats ) );
List<String> resolve = new ArrayList<String>();
resolve.add( "none" );
resolve.add( "local" );
resolve.add( "remote" );
resolve.add( "all" );
params.add( new Pair<String, List<String>>( "resolve", resolve ) );
operations.add( new OWSOperation( WFSRequestType.GetFeature.name(), dcp, params, constraints ) );
// GetPropertyValue
params = new ArrayList<Pair<String, List<String>>>();
params.add( new Pair<String, List<String>>( "outputFormat", outputFormats ) );
params.add( new Pair<String, List<String>>( "resolve", resolve ) );
operations.add( new OWSOperation( WFSRequestType.GetPropertyValue.name(), dcp, params, constraints ) );
// global parameter domains
List<Pair<String, List<String>>> globalParams = new ArrayList<Pair<String, List<String>>>();
// globalParams.add( new Pair<String, List<String>>( "version", master.getOfferedVersions() ) );
// Service constraints
List<Pair<String, String>> profileConstraints = new ArrayList<Pair<String, String>>();
profileConstraints.add( new Pair<String, String>( "ImplementsBasicWFS", "TRUE" ) );
profileConstraints.add( new Pair<String, String>( "ImplementsTransactionalWFS", "FALSE" ) );
profileConstraints.add( new Pair<String, String>( "ImplementsLockingWFS", "FALSE" ) );
profileConstraints.add( new Pair<String, String>( "KVPEncoding", "TRUE" ) );
profileConstraints.add( new Pair<String, String>( "XMLEncoding", "TRUE" ) );
profileConstraints.add( new Pair<String, String>( "SOAPEncoding", "FALSE" ) );
profileConstraints.add( new Pair<String, String>( "ImplementsInheritance", "TRUE" ) );
profileConstraints.add( new Pair<String, String>( "ImplementsRemoteResolve", "FALSE" ) );
profileConstraints.add( new Pair<String, String>( "ImplementsResultPaging", "FALSE" ) );
profileConstraints.add( new Pair<String, String>( "ImplementsStandardJoins", "FALSE" ) );
profileConstraints.add( new Pair<String, String>( "ImplementsSpatialJoins", "FALSE" ) );
profileConstraints.add( new Pair<String, String>( "ImplementsTemporalJoins", "FALSE" ) );
profileConstraints.add( new Pair<String, String>( "ImplementsFeatureVersioning", "FALSE" ) );
profileConstraints.add( new Pair<String, String>( "ManageStoredQueries", "FALSE" ) );
exportOperationsMetadata110( writer, operations, globalParams, profileConstraints, extendedCapabilities );
}
// wfs:WSDL
if ( sections == null || sections.contains( "WSDL" ) ) {
// TODO
}
// wfs:FeatureTypeList
if ( sections == null || sections.contains( "FeatureTypeList" ) ) {
writer.writeStartElement( WFS_200_NS, "FeatureTypeList" );
for ( FeatureType ft : servedFts ) {
QName ftName = ft.getName();
FeatureTypeMetadata ftMd = ftNameToFtMetadata.get( ftName );
writer.writeStartElement( WFS_200_NS, "FeatureType" );
// wfs:Name
writer.writeStartElement( WFS_200_NS, "Name" );
String prefix = ftName.getPrefix();
if ( prefix == null || prefix.equals( "" ) ) {
LOG.warn( "Feature type '" + ftName + "' has no prefix!? This should not happen." );
prefix = "app";
}
if ( ftName.getNamespaceURI() != XMLConstants.NULL_NS_URI ) {
// TODO what about the namespace prefix?
writer.writeNamespace( prefix, ftName.getNamespaceURI() );
writer.writeCharacters( prefix + ":" + ftName.getLocalPart() );
} else {
writer.writeCharacters( ftName.getLocalPart() );
}
writer.writeEndElement();
// wfs:Title
writer.writeStartElement( WFS_200_NS, "Title" );
if ( ftMd != null && ftMd.getTitle() != null ) {
writer.writeCharacters( ftMd.getTitle() );
} else {
writer.writeCharacters( prefix + ":" + ftName.getLocalPart() );
}
writer.writeEndElement();
// wfs:Abstract (minOccurs=0, maxOccurs=1)
if ( ftMd != null && ftMd.getAbstract() != null ) {
writer.writeStartElement( WFS_200_NS, "Abstract" );
writer.writeCharacters( ftMd.getAbstract() );
writer.writeEndElement();
}
// ows:Keywords (minOccurs=0, maxOccurs=unbounded)
// writer.writeStartElement( OWS_NS, "Keywords" );
// writer.writeCharacters( "keywords" );
// writer.writeEndElement();
// wfs:DefaultCRS / wfs:NoCRS
FeatureStore fs = service.getStore( ftName );
writeElement( writer, WFS_200_NS, "DefaultCRS", querySRS.get( 0 ).getAlias() );
// wfs:OtherCRS
for ( int i = 1; i < querySRS.size(); i++ ) {
writeElement( writer, WFS_200_NS, "OtherCRS", querySRS.get( i ).getAlias() );
}
writeOutputFormats200( writer );
// ows:WGS84BoundingBox (minOccurs=0, maxOccurs=unbounded)
Envelope env = null;
try {
env = fs.getEnvelope( ftName );
} catch ( FeatureStoreException e ) {
LOG.error( "Error retrieving envelope from FeatureStore: " + e.getMessage(), e );
}
if ( env != null ) {
try {
env = transformer.transform( env );
} catch ( Exception e ) {
LOG.error( "Cannot transform feature type envelope to WGS84." );
}
} else {
env = new SimpleGeometryFactory().createEnvelope( -180, -90, 180, 90,
CRSManager.getCRSRef( "EPSG:4326" ) );
}
writer.writeStartElement( OWS110_NS, "WGS84BoundingBox" );
Point min = env.getMin();
Point max = env.getMax();
double minX = -180.0;
double minY = -90.0;
double maxX = 180.0;
double maxY = 90.0;
try {
minX = min.get0();
minY = min.get1();
maxX = max.get0();
maxY = max.get1();
} catch ( ArrayIndexOutOfBoundsException e ) {
LOG.error( "Cannot generate WGS84 envelope for feature type '" + ftName + "'. Using full extent.",
e );
minX = -180.0;
minY = -90.0;
maxX = 180.0;
maxY = 90.0;
}
writer.writeStartElement( OWS110_NS, "LowerCorner" );
writer.writeCharacters( formatter.format( minX ) + " " + formatter.format( minY ) );
writer.writeEndElement();
writer.writeStartElement( OWS110_NS, "UpperCorner" );
writer.writeCharacters( formatter.format( maxX ) + " " + formatter.format( maxY ) );
writer.writeEndElement();
writer.writeEndElement();
// wfs:MetadataURL (minOccurs=0, maxOccurs=unbounded)
String metadataUrl = getMetadataURL( ftMd );
if ( metadataUrl != null ) {
writer.writeEmptyElement( WFS_200_NS, "MetadataURL" );
writer.writeAttribute( XLN_NS, "href", metadataUrl );
}
writer.writeEndElement();
}
writer.writeEndElement();
}
// fes:Filter_Capabilities
if ( sections == null || sections.contains( "Filter_Capabilities" ) ) {
FilterCapabilitiesExporter.export200( writer );
}
writer.writeEndElement();
writer.writeEndDocument();
}
private void writeOutputFormats200( XMLStreamWriter writer )
throws XMLStreamException {
writer.writeStartElement( WFS_200_NS, "OutputFormats" );
for ( String format : master.getOutputFormats() ) {
writer.writeStartElement( WFS_200_NS, "Format" );
writer.writeCharacters( format );
writer.writeEndElement();
}
writer.writeEndElement();
}
} | deegree-services/deegree-services-wfs/src/main/java/org/deegree/services/wfs/GetCapabilitiesHandler.java | //$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 by:
Department of Geography, University of Bonn
and
lat/lon GmbH
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library 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 Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: info@deegree.org
----------------------------------------------------------------------------*/
package org.deegree.services.wfs;
import static org.deegree.commons.xml.CommonNamespaces.FES_20_NS;
import static org.deegree.commons.xml.CommonNamespaces.FES_PREFIX;
import static org.deegree.commons.xml.CommonNamespaces.GMLNS;
import static org.deegree.commons.xml.CommonNamespaces.GML_PREFIX;
import static org.deegree.commons.xml.CommonNamespaces.OGCNS;
import static org.deegree.commons.xml.CommonNamespaces.OGC_PREFIX;
import static org.deegree.commons.xml.CommonNamespaces.XLINK_PREFIX;
import static org.deegree.commons.xml.CommonNamespaces.XLNNS;
import static org.deegree.commons.xml.CommonNamespaces.XSINS;
import static org.deegree.commons.xml.CommonNamespaces.XSI_PREFIX;
import static org.deegree.protocol.wfs.WFSConstants.VERSION_100;
import static org.deegree.protocol.wfs.WFSConstants.VERSION_110;
import static org.deegree.protocol.wfs.WFSConstants.VERSION_200;
import static org.deegree.protocol.wfs.WFSConstants.WFS_100_CAPABILITIES_SCHEMA_URL;
import static org.deegree.protocol.wfs.WFSConstants.WFS_110_SCHEMA_URL;
import static org.deegree.protocol.wfs.WFSConstants.WFS_200_NS;
import static org.deegree.protocol.wfs.WFSConstants.WFS_200_SCHEMA_URL;
import static org.deegree.protocol.wfs.WFSConstants.WFS_NS;
import static org.deegree.protocol.wfs.WFSConstants.WFS_PREFIX;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import org.deegree.commons.tom.ows.Version;
import org.deegree.commons.utils.Pair;
import org.deegree.commons.utils.StringUtils;
import org.deegree.commons.xml.CommonNamespaces;
import org.deegree.cs.coordinatesystems.ICRS;
import org.deegree.cs.persistence.CRSManager;
import org.deegree.feature.persistence.FeatureStore;
import org.deegree.feature.persistence.FeatureStoreException;
import org.deegree.feature.types.FeatureType;
import org.deegree.filter.xml.FilterCapabilitiesExporter;
import org.deegree.geometry.Envelope;
import org.deegree.geometry.GeometryTransformer;
import org.deegree.geometry.SimpleGeometryFactory;
import org.deegree.geometry.io.CoordinateFormatter;
import org.deegree.geometry.io.DecimalCoordinateFormatter;
import org.deegree.geometry.primitive.Point;
import org.deegree.protocol.ows.capabilities.GetCapabilities;
import org.deegree.protocol.wfs.WFSRequestType;
import org.deegree.services.controller.OGCFrontController;
import org.deegree.services.controller.ows.capabilities.OWSCapabilitiesXMLAdapter;
import org.deegree.services.controller.ows.capabilities.OWSOperation;
import org.deegree.services.jaxb.controller.DCPType;
import org.deegree.services.jaxb.metadata.ServiceIdentificationType;
import org.deegree.services.jaxb.metadata.ServiceProviderType;
import org.deegree.services.jaxb.wfs.FeatureTypeMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
/**
* Handles a single {@link GetCapabilities} requests for the {@link WebFeatureService}.
*
* @author <a href="mailto:schneider@lat-lon.de">Markus Schneider </a>
* @author last edited by: $Author:$
*
* @version $Revision:$, $Date:$
*/
class GetCapabilitiesHandler extends OWSCapabilitiesXMLAdapter {
private static Logger LOG = LoggerFactory.getLogger( GetCapabilitiesHandler.class );
private static GeometryTransformer transformer;
// used for formatting WGS84 bounding box coordinates
private static CoordinateFormatter formatter = new DecimalCoordinateFormatter();
static {
try {
transformer = new GeometryTransformer( "EPSG:4326" );
} catch ( Exception e ) {
LOG.error( "Could not initialize GeometryTransformer." );
}
}
private final Version version;
private final XMLStreamWriter writer;
private final ServiceIdentificationType serviceId;
private final ServiceProviderType serviceProvider;
private final Collection<FeatureType> servedFts;
private final Map<QName, FeatureTypeMetadata> ftNameToFtMetadata;
private final Set<String> sections;
private final boolean enableTransactions;
private final List<ICRS> querySRS;
private final WFSFeatureStoreManager service;
private final WebFeatureService master;
private final Element extendedCapabilities;
private final String metadataUrlTemplate;
GetCapabilitiesHandler( WebFeatureService master, WFSFeatureStoreManager service, Version version,
XMLStreamWriter xmlWriter, ServiceIdentificationType serviceId,
ServiceProviderType serviceProvider, Collection<FeatureType> servedFts,
String metadataUrlTemplate, Map<QName, FeatureTypeMetadata> ftNameToFtMetadata,
Set<String> sections, boolean enableTransactions, List<ICRS> querySRS,
Element extendedCapabilities ) {
this.master = master;
this.service = service;
this.version = version;
this.writer = xmlWriter;
this.serviceId = serviceId;
this.serviceProvider = serviceProvider;
this.servedFts = servedFts;
this.metadataUrlTemplate = metadataUrlTemplate;
this.ftNameToFtMetadata = ftNameToFtMetadata;
this.sections = sections;
this.enableTransactions = enableTransactions;
this.querySRS = querySRS;
this.extendedCapabilities = extendedCapabilities;
}
/**
* Produces a <code>WFS_Capabilities</code> document compliant to the specified WFS version.
*
* @throws XMLStreamException
* @throws IllegalArgumentException
* if the specified version is not 1.0.0, 1.1.0 or 2.0.0
*/
void export()
throws XMLStreamException {
if ( VERSION_100.equals( version ) ) {
export100();
} else if ( VERSION_110.equals( version ) ) {
export110();
} else if ( VERSION_200.equals( version ) ) {
export200();
} else {
throw new IllegalArgumentException( "Version '" + version + "' is not supported." );
}
}
/**
* Produces a <code>WFS_Capabilities</code> document that complies to the WFS 1.0.0 specification.
*
* @throws XMLStreamException
*/
void export100()
throws XMLStreamException {
writer.setDefaultNamespace( WFS_NS );
writer.writeStartElement( WFS_NS, "WFS_Capabilities" );
writer.writeAttribute( "version", "1.0.0" );
writer.writeDefaultNamespace( WFS_NS );
writer.writeNamespace( OWS_PREFIX, OWS_NS );
writer.writeNamespace( OGC_PREFIX, OGCNS );
writer.writeNamespace( GML_PREFIX, GMLNS );
writer.writeNamespace( XLINK_PREFIX, XLN_NS );
writer.writeAttribute( "xsi", XSINS, "schemaLocation", WFS_NS + " " + WFS_100_CAPABILITIES_SCHEMA_URL );
// wfs:Service (type="wfs:ServiceType")
exportService100();
// wfs:Capability (type="wfs:CapabilityType")
exportCapability100();
// wfs:FeatureTypeList (type="wfs:FeatureTypeListType")
writer.writeStartElement( WFS_NS, "FeatureTypeList" );
exportOperations100();
for ( FeatureType ft : servedFts ) {
// wfs:FeatureType
writer.writeStartElement( WFS_NS, "FeatureType" );
// wfs:Name
writer.writeStartElement( WFS_NS, "Name" );
QName ftName = ft.getName();
FeatureTypeMetadata ftMd = ftNameToFtMetadata.get( ftName );
String prefix = null;
if ( ftName.getNamespaceURI() != XMLConstants.NULL_NS_URI ) {
prefix = ftName.getPrefix();
if ( ftName.getPrefix() == null || ftName.getPrefix().equals( "" ) ) {
LOG.warn( "Feature type '" + ftName + "' has no prefix!? This should not happen." );
prefix = "app";
}
writer.writeNamespace( prefix, ftName.getNamespaceURI() );
writer.writeCharacters( prefix + ":" + ftName.getLocalPart() );
} else {
writer.writeCharacters( ftName.getLocalPart() );
}
writer.writeEndElement();
// wfs:Title (minOccurs=0, maxOccurs=1)
writer.writeStartElement( WFS_NS, "Title" );
if ( ftMd != null && ftMd.getTitle() != null ) {
writer.writeCharacters( ftMd.getTitle() );
} else {
if ( prefix != null ) {
writer.writeCharacters( prefix + ":" + ftName.getLocalPart() );
} else {
writer.writeCharacters( ftName.getLocalPart() );
}
}
writer.writeEndElement();
// wfs:Abstract (minOccurs=0, maxOccurs=1)
if ( ftMd != null && ftMd.getAbstract() != null ) {
writer.writeStartElement( WFS_NS, "Abstract" );
writer.writeCharacters( ftMd.getAbstract() );
writer.writeEndElement();
}
// wfs:Keywords (minOccurs=0, maxOccurs=1)
// if ( ft.getKeywords() != null ) {
// writer.writeStartElement( WFS_NS, "Keywords" );
// writer.writeCharacters( ft.getKeywords() );
// writer.writeEndElement();
// }
// wfs:SRS (minOccurs=1, maxOccurs=1)
writer.writeStartElement( WFS_NS, "SRS" );
writer.writeCharacters( querySRS.get( 0 ).getAlias() );
writer.writeEndElement();
// wfs:Operations (minOccurs=0, maxOccurs=1)
exportOperations100();
// wfs:LatLongBoundingBox (minOccurs=0, maxOccurs=unbounded)
Envelope env = null;
try {
FeatureStore fs = service.getStore( ftName );
env = fs.getEnvelope( ftName );
} catch ( FeatureStoreException e ) {
LOG.error( "Error retrieving envelope from FeatureStore: " + e.getMessage(), e );
}
if ( env != null ) {
try {
env = transformer.transform( env );
Point min = env.getMin();
Point max = env.getMax();
double minX = min.get0();
double minY = min.get1();
double maxX = max.get0();
double maxY = max.get1();
writer.writeStartElement( WFS_NS, "LatLongBoundingBox" );
writer.writeAttribute( "minx", "" + formatter.format( minX ) );
writer.writeAttribute( "miny", "" + formatter.format( minY ) );
writer.writeAttribute( "maxx", "" + formatter.format( maxX ) );
writer.writeAttribute( "maxy", "" + formatter.format( maxY ) );
writer.writeEndElement();
} catch ( Exception e ) {
LOG.error( "Cannot generate WGS84 envelope for feature type '" + ftName + "'.", e );
}
}
// wfs:MetadataURL (minOccurs=0, maxOccurs=unbounded)
String metadataUrl = getMetadataURL( ftMd );
if ( metadataUrl != null ) {
writer.writeStartElement( WFS_NS, "MetadataURL" );
writer.writeAttribute( "type", "TC211" );
writer.writeAttribute( "format", "XML" );
writer.writeCharacters( metadataUrl );
writer.writeEndElement();
}
writer.writeEndElement();
}
writer.writeEndElement();
// ogc:Filter_Capabilities
FilterCapabilitiesExporter.export100( writer );
writer.writeEndElement();
writer.writeEndDocument();
}
private String getMetadataURL( FeatureTypeMetadata ftMd ) {
if ( metadataUrlTemplate == null || ftMd == null || ftMd.getMetadataSetId() == null ) {
return null;
}
return StringUtils.replaceAll( metadataUrlTemplate, "${metadataSetId}", ftMd.getMetadataSetId() );
}
private void exportCapability100()
throws XMLStreamException {
writer.writeStartElement( WFS_NS, "Capability" );
writer.writeStartElement( WFS_NS, "Request" );
String getURL = OGCFrontController.getHttpGetURL();
String postURL = OGCFrontController.getHttpPostURL();
// wfs:GetCapabilities
writer.writeStartElement( WFS_NS, WFSRequestType.GetCapabilities.name() );
exportGetDCPType100( getURL );
exportPostDCPType100( postURL );
writer.writeEndElement();
// wfs:DescribeFeatureType
writer.writeStartElement( WFS_NS, WFSRequestType.DescribeFeatureType.name() );
writer.writeStartElement( WFS_NS, "SchemaDescriptionLanguage" );
writer.writeStartElement( WFS_NS, "XMLSCHEMA" );
writer.writeEndElement();
writer.writeEndElement();
exportGetDCPType100( getURL );
exportPostDCPType100( postURL );
writer.writeEndElement();
if ( enableTransactions ) {
// wfs:Transaction
writer.writeStartElement( WFS_NS, WFSRequestType.Transaction.name() );
exportGetDCPType100( getURL );
exportPostDCPType100( postURL );
writer.writeEndElement();
}
// wfs:GetFeature
writer.writeStartElement( WFS_NS, WFSRequestType.GetFeature.name() );
writer.writeStartElement( WFS_NS, "ResultFormat" );
writer.writeEmptyElement( WFS_NS, "GML2" );
writer.writeEndElement();
exportGetDCPType100( getURL );
exportPostDCPType100( postURL );
writer.writeEndElement();
if ( enableTransactions ) {
// wfs:GetFeatureWithLock
writer.writeStartElement( WFS_NS, WFSRequestType.GetFeatureWithLock.name() );
writer.writeStartElement( WFS_NS, "ResultFormat" );
writer.writeEmptyElement( WFS_NS, "GML2" );
writer.writeEndElement();
exportGetDCPType100( getURL );
exportPostDCPType100( postURL );
writer.writeEndElement();
// wfs:LockFeature
writer.writeStartElement( WFS_NS, WFSRequestType.LockFeature.name() );
exportGetDCPType100( getURL );
exportPostDCPType100( postURL );
writer.writeEndElement();
}
writer.writeEndElement();
writer.writeEndElement();
}
private void exportService100()
throws XMLStreamException {
writer.writeStartElement( WFS_NS, "Service" );
if ( serviceId != null && serviceId.getTitle() != null && !serviceId.getTitle().isEmpty() ) {
// wfs:Name (type="string")
writeElement( writer, WFS_NS, "Name", serviceId.getTitle().get( 0 ) );
// wfs:Title (type="string)
writeElement( writer, WFS_NS, "Title", serviceId.getTitle().get( 0 ) );
} else {
writeElement( writer, WFS_NS, "Name", "" );
writeElement( writer, WFS_NS, "Title", "" );
}
if ( serviceId != null && serviceId.getAbstract() != null && !serviceId.getAbstract().isEmpty() ) {
// wfs:Abstract
writeElement( writer, WFS_NS, "Abstract", serviceId.getAbstract().get( 0 ) );
}
// wfs:Keywords
// wfs:OnlineResource (type=???)
writeElement( writer, WFS_NS, "OnlineResource", serviceProvider.getServiceContact().getOnlineResource() );
// wfs:Fees
if ( serviceId != null && serviceId.getFees() != null ) {
writeElement( writer, WFS_NS, "Fees", serviceId.getFees() );
}
// wfs:AccessConstraints
writer.writeEndElement();
}
private void exportOperations100()
throws XMLStreamException {
writer.writeStartElement( WFS_NS, "Operations" );
writer.writeEmptyElement( WFS_NS, "Query" );
if ( enableTransactions ) {
writer.writeEmptyElement( WFS_NS, "Insert" );
writer.writeEmptyElement( WFS_NS, "Update" );
writer.writeEmptyElement( WFS_NS, "Delete" );
}
if ( enableTransactions ) {
writer.writeEmptyElement( WFS_NS, "Lock" );
}
writer.writeEndElement();
}
private void exportGetDCPType100( String getURL )
throws XMLStreamException {
if ( getURL != null ) {
writer.writeStartElement( WFS_NS, "DCPType" );
writer.writeStartElement( WFS_NS, "HTTP" );
// ows:Get (type="ows:GetType")
writer.writeStartElement( WFS_NS, "Get" );
writer.writeAttribute( "onlineResource", getURL );
writer.writeEndElement();
writer.writeEndElement();
writer.writeEndElement();
}
}
private void exportPostDCPType100( String postURL )
throws XMLStreamException {
if ( postURL != null ) {
writer.writeStartElement( WFS_NS, "DCPType" );
writer.writeStartElement( WFS_NS, "HTTP" );
// ows:Post (type="ows:PostType")
writer.writeStartElement( WFS_NS, "Post" );
writer.writeAttribute( "onlineResource", postURL );
writer.writeEndElement();
writer.writeEndElement();
writer.writeEndElement();
}
}
/**
* Produces a <code>WFS_Capabilities</code> document that complies to the WFS 1.1.0 specification.
*
* @throws XMLStreamException
*/
void export110()
throws XMLStreamException {
writer.setDefaultNamespace( WFS_NS );
writer.writeStartElement( WFS_NS, "WFS_Capabilities" );
writer.writeAttribute( "version", "1.1.0" );
writer.writeDefaultNamespace( WFS_NS );
writer.writeNamespace( OWS_PREFIX, OWS_NS );
writer.writeNamespace( OGC_PREFIX, OGCNS );
writer.writeNamespace( GML_PREFIX, GMLNS );
writer.writeNamespace( XLINK_PREFIX, XLNNS );
writer.writeAttribute( XSI_PREFIX, XSINS, "schemaLocation", WFS_NS + " " + WFS_110_SCHEMA_URL );
// ows:ServiceIdentification
if ( sections == null || sections.contains( "SERVICEIDENTIFICATION" ) ) {
List<Version> serviceVersions = new ArrayList<Version>();
serviceVersions.add( Version.parseVersion( "1.1.0" ) );
exportServiceIdentification100( writer, serviceId, "WFS", serviceVersions );
}
// ows:ServiceProvider
if ( sections == null || sections.contains( "SERVICEPROVIDER" ) ) {
exportServiceProvider100( writer, serviceProvider );
}
// ows:OperationsMetadata
if ( sections == null || sections.contains( "OPERATIONSMETADATA" ) ) {
List<OWSOperation> operations = new ArrayList<OWSOperation>();
DCPType dcp = new DCPType();
dcp.setHTTPGet( OGCFrontController.getHttpGetURL() );
dcp.setHTTPPost( OGCFrontController.getHttpPostURL() );
// DescribeFeatureType
List<Pair<String, List<String>>> params = new ArrayList<Pair<String, List<String>>>();
List<String> outputFormats = new ArrayList<String>( master.getOutputFormats() );
params.add( new Pair<String, List<String>>( "outputFormat", outputFormats ) );
List<Pair<String, List<String>>> constraints = new ArrayList<Pair<String, List<String>>>();
operations.add( new OWSOperation( WFSRequestType.DescribeFeatureType.name(), dcp, params, constraints ) );
// GetCapabilities
params = new ArrayList<Pair<String, List<String>>>();
params.add( new Pair<String, List<String>>( "AcceptVersions", master.getOfferedVersions() ) );
params.add( new Pair<String, List<String>>( "AcceptFormats", Collections.singletonList( "text/xml" ) ) );
// List<String> sections = new ArrayList<String>();
// sections.add( "ServiceIdentification" );
// sections.add( "ServiceProvider" );
// sections.add( "OperationsMetadata" );
// sections.add( "FeatureTypeList" );
// sections.add( "Filter_Capabilities" );
// params.add( new Pair<String, List<String>>( "Sections", sections ) );
constraints = new ArrayList<Pair<String, List<String>>>();
operations.add( new OWSOperation( WFSRequestType.GetCapabilities.name(), dcp, params, constraints ) );
// GetFeature
params = new ArrayList<Pair<String, List<String>>>();
params.add( new Pair<String, List<String>>( "resultType",
Arrays.asList( new String[] { "results", "hits" } ) ) );
params.add( new Pair<String, List<String>>( "outputFormat", outputFormats ) );
operations.add( new OWSOperation( WFSRequestType.GetFeature.name(), dcp, params, constraints ) );
// GetFeatureWithLock
if ( enableTransactions ) {
params = new ArrayList<Pair<String, List<String>>>();
params.add( new Pair<String, List<String>>( "resultType", Arrays.asList( new String[] { "results",
"hits" } ) ) );
params.add( new Pair<String, List<String>>( "outputFormat", outputFormats ) );
operations.add( new OWSOperation( WFSRequestType.GetFeatureWithLock.name(), dcp, params, constraints ) );
}
// GetGmlObject
params = new ArrayList<Pair<String, List<String>>>();
params = new ArrayList<Pair<String, List<String>>>();
params.add( new Pair<String, List<String>>( "outputFormat", outputFormats ) );
constraints = new ArrayList<Pair<String, List<String>>>();
operations.add( new OWSOperation( WFSRequestType.GetGmlObject.name(), dcp, params, constraints ) );
if ( enableTransactions ) {
// LockFeature
params = new ArrayList<Pair<String, List<String>>>();
params.add( new Pair<String, List<String>>( "lockAction",
Arrays.asList( new String[] { "ALL", "SOME" } ) ) );
operations.add( new OWSOperation( WFSRequestType.LockFeature.name(), dcp, params, constraints ) );
// Transaction
params = new ArrayList<Pair<String, List<String>>>();
params.add( new Pair<String, List<String>>( "inputFormat", outputFormats ) );
params.add( new Pair<String, List<String>>( "idgen", Arrays.asList( new String[] { "GenerateNew",
"UseExisting",
"ReplaceDuplicate" } ) ) );
params.add( new Pair<String, List<String>>( "releaseAction", Arrays.asList( new String[] { "ALL",
"SOME" } ) ) );
operations.add( new OWSOperation( WFSRequestType.Transaction.name(), dcp, params, constraints ) );
}
// TODO
exportOperationsMetadata100( writer, operations, extendedCapabilities );
}
// wfs:FeatureTypeList
if ( sections == null || sections.contains( "FEATURETYPELIST" ) ) {
writer.writeStartElement( WFS_NS, "FeatureTypeList" );
for ( FeatureType ft : servedFts ) {
QName ftName = ft.getName();
FeatureTypeMetadata ftMd = ftNameToFtMetadata.get( ftName );
writer.writeStartElement( WFS_NS, "FeatureType" );
// wfs:Name
writer.writeStartElement( WFS_NS, "Name" );
String prefix = ftName.getPrefix();
if ( prefix == null || prefix.equals( "" ) ) {
LOG.warn( "Feature type '" + ftName + "' has no prefix!? This should not happen." );
prefix = "app";
}
if ( ftName.getNamespaceURI() != XMLConstants.NULL_NS_URI ) {
// TODO what about the namespace prefix?
writer.writeNamespace( prefix, ftName.getNamespaceURI() );
writer.writeCharacters( prefix + ":" + ftName.getLocalPart() );
} else {
writer.writeCharacters( ftName.getLocalPart() );
}
writer.writeEndElement();
// wfs:Title
writer.writeStartElement( WFS_NS, "Title" );
if ( ftMd != null && ftMd.getTitle() != null ) {
writer.writeCharacters( ftMd.getTitle() );
} else {
writer.writeCharacters( prefix + ":" + ftName.getLocalPart() );
}
writer.writeEndElement();
// wfs:Abstract (minOccurs=0, maxOccurs=1)
if ( ftMd != null && ftMd.getAbstract() != null ) {
writer.writeStartElement( WFS_NS, "Abstract" );
writer.writeCharacters( ftMd.getAbstract() );
writer.writeEndElement();
}
// ows:Keywords (minOccurs=0, maxOccurs=unbounded)
// writer.writeStartElement( OWS_NS, "Keywords" );
// writer.writeCharacters( "keywords" );
// writer.writeEndElement();
// wfs:DefaultSRS / wfs:NoSRS
FeatureStore fs = service.getStore( ftName );
writeElement( writer, WFS_NS, "DefaultSRS", querySRS.get( 0 ).getAlias() );
// wfs:OtherSRS
for ( int i = 1; i < querySRS.size(); i++ ) {
writeElement( writer, WFS_NS, "OtherSRS", querySRS.get( i ).getAlias() );
}
writeOutputFormats110( writer );
// ows:WGS84BoundingBox (minOccurs=0, maxOccurs=unbounded)
Envelope env = null;
try {
env = fs.getEnvelope( ftName );
} catch ( FeatureStoreException e ) {
LOG.error( "Error retrieving envelope from FeatureStore: " + e.getMessage(), e );
}
if ( env != null ) {
try {
env = transformer.transform( env );
} catch ( Exception e ) {
LOG.error( "Cannot transform feature type envelope to WGS84." );
}
} else {
env = new SimpleGeometryFactory().createEnvelope( -180, -90, 180, 90,
CRSManager.getCRSRef( "EPSG:4326" ) );
}
writer.writeStartElement( OWS_NS, "WGS84BoundingBox" );
Point min = env.getMin();
Point max = env.getMax();
double minX = -180.0;
double minY = -90.0;
double maxX = 180.0;
double maxY = 90.0;
try {
minX = min.get0();
minY = min.get1();
maxX = max.get0();
maxY = max.get1();
} catch ( ArrayIndexOutOfBoundsException e ) {
LOG.error( "Cannot generate WGS84 envelope for feature type '" + ftName + "'. Using full extent.",
e );
minX = -180.0;
minY = -90.0;
maxX = 180.0;
maxY = 90.0;
}
writer.writeStartElement( OWS_NS, "LowerCorner" );
writer.writeCharacters( formatter.format( minX ) + " " + formatter.format( minY ) );
writer.writeEndElement();
writer.writeStartElement( OWS_NS, "UpperCorner" );
writer.writeCharacters( formatter.format( maxX ) + " " + formatter.format( maxY ) );
writer.writeEndElement();
writer.writeEndElement();
// TODO Operations
// wfs:MetadataURL (minOccurs=0, maxOccurs=unbounded)
String metadataUrl = getMetadataURL( ftMd );
if ( metadataUrl != null ) {
writer.writeStartElement( WFS_NS, "MetadataURL" );
writer.writeAttribute( "type", "19139" );
writer.writeAttribute( "format", "text/xml" );
writer.writeCharacters( metadataUrl );
writer.writeEndElement();
}
writer.writeEndElement();
}
writer.writeEndElement();
}
// wfs:ServesGMLObjectTypeList
if ( sections == null || sections.contains( "SERVESGMLOBJECTTYPELIST" ) ) {
// TODO
}
// wfs:SupportsGMLObjectTypeList
if ( sections == null || sections.contains( "SUPPORTSGMLOBJECTTYPELIST" ) ) {
// TODO
}
// 'ogc:Filter_Capabilities' (mandatory)
FilterCapabilitiesExporter.export110( writer );
writer.writeEndElement();
writer.writeEndDocument();
}
private void writeOutputFormats110( XMLStreamWriter writer )
throws XMLStreamException {
writer.writeStartElement( WFS_PREFIX, "OutputFormats", WFS_NS );
for ( String format : master.getOutputFormats() ) {
writer.writeStartElement( WFS_PREFIX, "Format", WFS_NS );
writer.writeCharacters( format );
writer.writeEndElement();
}
writer.writeEndElement();
}
/**
* Produces a <code>WFS_Capabilities</code> document that complies to the WFS 2.0.0 specification.
*
* @throws XMLStreamException
*/
void export200()
throws XMLStreamException {
writer.setDefaultNamespace( WFS_200_NS );
writer.writeStartElement( WFS_200_NS, "WFS_Capabilities" );
writer.writeAttribute( "version", "2.0.0" );
writer.writeDefaultNamespace( WFS_200_NS );
writer.writeNamespace( OWS_PREFIX, OWS110_NS );
writer.writeNamespace( OGC_PREFIX, OGCNS );
writer.writeNamespace( FES_PREFIX, FES_20_NS );
writer.writeNamespace( GML_PREFIX, GMLNS );
writer.writeNamespace( XLINK_PREFIX, XLN_NS );
writer.writeAttribute( "xsi", CommonNamespaces.XSINS, "schemaLocation", WFS_200_NS + " " + WFS_200_SCHEMA_URL );
// ows:ServiceIdentification
if ( sections == null || sections.contains( "ServiceIdentification" ) ) {
List<Version> serviceVersions = new ArrayList<Version>();
serviceVersions.add( Version.parseVersion( "2.0.0" ) );
exportServiceIdentification110( writer, serviceId, "WFS", serviceVersions );
}
// ows:ServiceProvider
if ( sections == null || sections.contains( "ServiceProvider" ) ) {
exportServiceProvider110( writer, serviceProvider );
}
// ows:OperationsMetadata
if ( sections == null || sections.contains( "OPERATIONSMETADATA" ) ) {
List<OWSOperation> operations = new ArrayList<OWSOperation>();
DCPType dcp = new DCPType();
dcp.setHTTPGet( OGCFrontController.getHttpGetURL() );
dcp.setHTTPPost( OGCFrontController.getHttpPostURL() );
// DescribeFeatureType
List<Pair<String, List<String>>> params = new ArrayList<Pair<String, List<String>>>();
List<String> outputFormats = new ArrayList<String>( master.getOutputFormats() );
params.add( new Pair<String, List<String>>( "outputFormat", outputFormats ) );
List<Pair<String, List<String>>> constraints = new ArrayList<Pair<String, List<String>>>();
operations.add( new OWSOperation( WFSRequestType.DescribeFeatureType.name(), dcp, params, constraints ) );
// GetCapabilities
params = new ArrayList<Pair<String, List<String>>>();
params.add( new Pair<String, List<String>>( "AcceptVersions", master.getOfferedVersions() ) );
params.add( new Pair<String, List<String>>( "AcceptFormats", Collections.singletonList( "text/xml" ) ) );
List<String> sections = new ArrayList<String>();
sections.add( "ServiceIdentification" );
sections.add( "ServiceProvider" );
sections.add( "OperationsMetadata" );
sections.add( "FeatureTypeList" );
sections.add( "Filter_Capabilities" );
params.add( new Pair<String, List<String>>( "Sections", sections ) );
constraints = new ArrayList<Pair<String, List<String>>>();
operations.add( new OWSOperation( WFSRequestType.GetCapabilities.name(), dcp, params, constraints ) );
// GetFeature
params = new ArrayList<Pair<String, List<String>>>();
params.add( new Pair<String, List<String>>( "outputFormat", outputFormats ) );
List<String> resolve = new ArrayList<String>();
resolve.add( "none" );
resolve.add( "local" );
resolve.add( "remote" );
resolve.add( "all" );
params.add( new Pair<String, List<String>>( "resolve", resolve ) );
operations.add( new OWSOperation( WFSRequestType.GetFeature.name(), dcp, params, constraints ) );
// GetPropertyValue
params = new ArrayList<Pair<String, List<String>>>();
params.add( new Pair<String, List<String>>( "outputFormat", outputFormats ) );
params.add( new Pair<String, List<String>>( "resolve", resolve ) );
operations.add( new OWSOperation( WFSRequestType.GetPropertyValue.name(), dcp, params, constraints ) );
// global parameter domains
List<Pair<String, List<String>>> globalParams = new ArrayList<Pair<String, List<String>>>();
// globalParams.add( new Pair<String, List<String>>( "version", master.getOfferedVersions() ) );
// Service constraints
List<Pair<String, String>> profileConstraints = new ArrayList<Pair<String, String>>();
profileConstraints.add( new Pair<String, String>( "ImplementsBasicWFS", "TRUE" ) );
profileConstraints.add( new Pair<String, String>( "ImplementsTransactionalWFS", "FALSE" ) );
profileConstraints.add( new Pair<String, String>( "ImplementsLockingWFS", "FALSE" ) );
profileConstraints.add( new Pair<String, String>( "KVPEncoding", "TRUE" ) );
profileConstraints.add( new Pair<String, String>( "XMLEncoding", "TRUE" ) );
profileConstraints.add( new Pair<String, String>( "SOAPEncoding", "FALSE" ) );
profileConstraints.add( new Pair<String, String>( "ImplementsInheritance", "TRUE" ) );
profileConstraints.add( new Pair<String, String>( "ImplementsRemoteResolve", "FALSE" ) );
profileConstraints.add( new Pair<String, String>( "ImplementsResultPaging", "FALSE" ) );
profileConstraints.add( new Pair<String, String>( "ImplementsStandardJoins", "FALSE" ) );
profileConstraints.add( new Pair<String, String>( "ImplementsSpatialJoins", "FALSE" ) );
profileConstraints.add( new Pair<String, String>( "ImplementsTemporalJoins", "FALSE" ) );
profileConstraints.add( new Pair<String, String>( "ImplementsFeatureVersioning", "FALSE" ) );
profileConstraints.add( new Pair<String, String>( "ManageStoredQueries", "FALSE" ) );
exportOperationsMetadata110( writer, operations, globalParams, profileConstraints, extendedCapabilities );
}
// wfs:WSDL
if ( sections == null || sections.contains( "WSDL" ) ) {
// TODO
}
// wfs:FeatureTypeList
if ( sections == null || sections.contains( "FeatureTypeList" ) ) {
writer.writeStartElement( WFS_200_NS, "FeatureTypeList" );
for ( FeatureType ft : servedFts ) {
QName ftName = ft.getName();
FeatureTypeMetadata ftMd = ftNameToFtMetadata.get( ftName );
writer.writeStartElement( WFS_200_NS, "FeatureType" );
// wfs:Name
writer.writeStartElement( WFS_200_NS, "Name" );
String prefix = ftName.getPrefix();
if ( prefix == null || prefix.equals( "" ) ) {
LOG.warn( "Feature type '" + ftName + "' has no prefix!? This should not happen." );
prefix = "app";
}
if ( ftName.getNamespaceURI() != XMLConstants.NULL_NS_URI ) {
// TODO what about the namespace prefix?
writer.writeNamespace( prefix, ftName.getNamespaceURI() );
writer.writeCharacters( prefix + ":" + ftName.getLocalPart() );
} else {
writer.writeCharacters( ftName.getLocalPart() );
}
writer.writeEndElement();
// wfs:Title
writer.writeStartElement( WFS_200_NS, "Title" );
if ( ftMd != null && ftMd.getTitle() != null ) {
writer.writeCharacters( ftMd.getTitle() );
} else {
writer.writeCharacters( prefix + ":" + ftName.getLocalPart() );
}
writer.writeEndElement();
// wfs:Abstract (minOccurs=0, maxOccurs=1)
if ( ftMd != null && ftMd.getAbstract() != null ) {
writer.writeStartElement( WFS_200_NS, "Abstract" );
writer.writeCharacters( ftMd.getAbstract() );
writer.writeEndElement();
}
// ows:Keywords (minOccurs=0, maxOccurs=unbounded)
// writer.writeStartElement( OWS_NS, "Keywords" );
// writer.writeCharacters( "keywords" );
// writer.writeEndElement();
// wfs:DefaultCRS / wfs:NoCRS
FeatureStore fs = service.getStore( ftName );
writeElement( writer, WFS_200_NS, "DefaultCRS", querySRS.get( 0 ).getAlias() );
// wfs:OtherCRS
for ( int i = 1; i < querySRS.size(); i++ ) {
writeElement( writer, WFS_200_NS, "OtherCRS", querySRS.get( i ).getAlias() );
}
writeOutputFormats200( writer );
// ows:WGS84BoundingBox (minOccurs=0, maxOccurs=unbounded)
Envelope env = null;
try {
env = fs.getEnvelope( ftName );
} catch ( FeatureStoreException e ) {
LOG.error( "Error retrieving envelope from FeatureStore: " + e.getMessage(), e );
}
if ( env != null ) {
try {
env = transformer.transform( env );
} catch ( Exception e ) {
LOG.error( "Cannot transform feature type envelope to WGS84." );
}
} else {
env = new SimpleGeometryFactory().createEnvelope( -180, -90, 180, 90,
CRSManager.getCRSRef( "EPSG:4326" ) );
}
writer.writeStartElement( OWS110_NS, "WGS84BoundingBox" );
Point min = env.getMin();
Point max = env.getMax();
double minX = -180.0;
double minY = -90.0;
double maxX = 180.0;
double maxY = 90.0;
try {
minX = min.get0();
minY = min.get1();
maxX = max.get0();
maxY = max.get1();
} catch ( ArrayIndexOutOfBoundsException e ) {
LOG.error( "Cannot generate WGS84 envelope for feature type '" + ftName + "'. Using full extent.",
e );
minX = -180.0;
minY = -90.0;
maxX = 180.0;
maxY = 90.0;
}
writer.writeStartElement( OWS110_NS, "LowerCorner" );
writer.writeCharacters( formatter.format( minX ) + " " + formatter.format( minY ) );
writer.writeEndElement();
writer.writeStartElement( OWS110_NS, "UpperCorner" );
writer.writeCharacters( formatter.format( maxX ) + " " + formatter.format( maxY ) );
writer.writeEndElement();
writer.writeEndElement();
// wfs:MetadataURL (minOccurs=0, maxOccurs=unbounded)
String metadataUrl = getMetadataURL( ftMd );
if ( metadataUrl != null ) {
writer.writeStartElement( WFS_200_NS, "MetadataURL" );
writer.writeCharacters( metadataUrl );
writer.writeEndElement();
}
writer.writeEndElement();
}
writer.writeEndElement();
}
// fes:Filter_Capabilities
if ( sections == null || sections.contains( "Filter_Capabilities" ) ) {
FilterCapabilitiesExporter.export200( writer );
}
writer.writeEndElement();
writer.writeEndDocument();
}
private void writeOutputFormats200( XMLStreamWriter writer )
throws XMLStreamException {
writer.writeStartElement( WFS_200_NS, "OutputFormats" );
for ( String format : master.getOutputFormats() ) {
writer.writeStartElement( WFS_200_NS, "Format" );
writer.writeCharacters( format );
writer.writeEndElement();
}
writer.writeEndElement();
}
} | Fixed WFS 2.0.0 export of MetadataURL
| deegree-services/deegree-services-wfs/src/main/java/org/deegree/services/wfs/GetCapabilitiesHandler.java | Fixed WFS 2.0.0 export of MetadataURL | |
Java | apache-2.0 | 4bf09b2be2b226c94e50c9d6e96315678db0f490 | 0 | desp0916/LearnStorm,desp0916/LearnStorm,desp0916/LearnStorm | /**
* storm jar target/LearnStorm-0.0.1-SNAPSHOT.jar com.pic.ala.ApLogAnalysisTopology
*
* storm jar target\LearnStorm-0.0.1-SNAPSHOT.jar com.pic.ala.ApLogAnalysisTopology -c nimbus.host=192.168.20.150 -c nimbus.thrift.port=49627
*
* https://github.com/apache/storm/tree/master/external/storm-kafka
*/
package com.pic.ala;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.apache.log4j.Logger;
import org.apache.storm.hbase.bolt.HBaseBolt;
import org.apache.storm.hbase.bolt.mapper.SimpleHBaseMapper;
import backtype.storm.Config;
import backtype.storm.StormSubmitter;
import backtype.storm.generated.AlreadyAliveException;
import backtype.storm.generated.AuthorizationException;
import backtype.storm.generated.InvalidTopologyException;
import backtype.storm.spout.SchemeAsMultiScheme;
import backtype.storm.topology.TopologyBuilder;
import backtype.storm.tuple.Fields;
import storm.kafka.BrokerHosts;
import storm.kafka.KafkaSpout;
import storm.kafka.SpoutConfig;
import storm.kafka.ZkHosts;
public class ApLogAnalysisTopology extends BaseApLogAnalysisTopology {
private static final Logger LOG = Logger.getLogger(ApLogAnalysisTopology.class);
private static final String KAFKA_SPOUT_ID = "kafkaSpout";
private static final String HBASE_BOLT_ID = "hbaseBolt";
public ApLogAnalysisTopology(String configFileLocation) throws Exception {
super(configFileLocation);
}
private SpoutConfig constructKafkaSpoutConf() {
BrokerHosts hosts = new ZkHosts(topologyConfig.getProperty("kafka.zookeeper.host.port"));
String topic = topologyConfig.getProperty("kafka.topic");
String zkRoot = topologyConfig.getProperty("kafka.zkRoot");
// String consumerGroupId = "ApLogAnalysisSpout";
String consumerGroupId = UUID.randomUUID().toString();
// String clientId = "ApLogAnalysisClient";
// KafkaConfig kafkaConfig = new KafkaConfig(hosts, topic, clientId);
SpoutConfig spoutConfig = new SpoutConfig(hosts, topic, zkRoot, consumerGroupId);
spoutConfig.startOffsetTime = System.currentTimeMillis();
// spoutConfig.startOffsetTime = kafka.api.OffsetRequest.EarliestTime()
spoutConfig.scheme = new SchemeAsMultiScheme(new ApLogScheme());
return spoutConfig;
}
public void configureKafkaSpout(TopologyBuilder builder) {
KafkaSpout kafkaSpout = new KafkaSpout(constructKafkaSpoutConf());
int spoutCount = Integer.valueOf(topologyConfig.getProperty("spout.thread.count"));
builder.setSpout(KAFKA_SPOUT_ID, kafkaSpout, spoutCount);
}
public void configureHBaseBolt(TopologyBuilder builder) {
SimpleHBaseMapper mapper = new SimpleHBaseMapper().withRowKeyField(ApLogScheme.FIELD_LOG_ID)
.withColumnFields(new Fields(ApLogScheme.FIELD_HOSTNAME, ApLogScheme.FIELD_EXEC_TIME,
ApLogScheme.FIELD_ERROR_LEVEL, ApLogScheme.FIELD_EXEC_METHOD, ApLogScheme.FIELD_KEYWORD1,
ApLogScheme.FIELD_KEYWORD2, ApLogScheme.FIELD_KEYWORD3, ApLogScheme.FIELD_MESSAGE))
// .withCounterFields(new Fields("count"))
.withColumnFamily("cf");
HBaseBolt hbase = new HBaseBolt(ApLogScheme.SYSTEM_ID, mapper).withConfigKey("hbase.conf");
builder.setBolt(HBASE_BOLT_ID, hbase, 1).fieldsGrouping(KAFKA_SPOUT_ID, new Fields(ApLogScheme.FIELD_LOG_ID));
}
private void buildAndSubmit() throws AlreadyAliveException, InvalidTopologyException, AuthorizationException {
TopologyBuilder builder = new TopologyBuilder();
configureKafkaSpout(builder);
configureHBaseBolt(builder);
Config conf = new Config();
Map<String, Object> hbConf = new HashMap<String, Object>();
hbConf.put("hbase.rootdir", "hdfs://hdpha/apps/hbase/data");
// conf.put("topology.auto-credentials",
// "org.apache.storm.hbase.security.AutoHBase");
conf.put("hbase.conf", hbConf);
conf.setDebug(true);
// LocalCluster cluster = new LocalCluster();
StormSubmitter.submitTopology("ApLogAnalyzer", conf, builder.createTopology());
}
public static void main(String args[]) throws Exception {
// ClassLoader cl = ClassLoader.getSystemClassLoader();
// URL[] urls = ((URLClassLoader)cl).getURLs();
// for(URL url: urls){
// System.out.println(url.getFile());
// }
String configFileLocation = "ap_log_analysis_topology.properties";
ApLogAnalysisTopology apLogAnalysisTopology = new ApLogAnalysisTopology(configFileLocation);
apLogAnalysisTopology.buildAndSubmit();
}
} | src/main/java/com/pic/ala/ApLogAnalysisTopology.java | Updated. | src/main/java/com/pic/ala/ApLogAnalysisTopology.java | Updated. | ||
Java | apache-2.0 | e23acca8761a3cbdcab44a0ca864be4cde1b67e4 | 0 | aseldawy/spatialhadoop,aseldawy/spatialhadoop,hn5092/hadoop-common,hn5092/hadoop-common,ShortMap/ShortMap,squidsolutions/hadoop-common,squidsolutions/hadoop-common,dongjiaqiang/hadoop-common,hn5092/hadoop-common,hn5092/hadoop-common,dhootha/hadoop-common,hn5092/hadoop-common,ShortMap/ShortMap,sztanko/hadoop-common,dhootha/hadoop-common,toddlipcon/hadoop,dhootha/hadoop-common,dhootha/hadoop-common,ShortMap/ShortMap,aseldawy/spatialhadoop,ShortMap/ShortMap,hn5092/hadoop-common,coderplay/hadoop-common,ShortMap/ShortMap,hn5092/hadoop-common,hn5092/hadoop-common,dongjiaqiang/hadoop-common,squidsolutions/hadoop-common,squidsolutions/hadoop-common,dhootha/hadoop-common,sztanko/hadoop-common,coderplay/hadoop-common,sztanko/hadoop-common,toddlipcon/hadoop,hn5092/hadoop-common,dongjiaqiang/hadoop-common,toddlipcon/hadoop,squidsolutions/hadoop-common,toddlipcon/hadoop,dongjiaqiang/hadoop-common,dongjiaqiang/hadoop-common,aseldawy/spatialhadoop,ShortMap/ShortMap,dongjiaqiang/hadoop-common,sztanko/hadoop-common,dhootha/hadoop-common,squidsolutions/hadoop-common,sztanko/hadoop-common,hn5092/hadoop-common,aseldawy/spatialhadoop,sztanko/hadoop-common,coderplay/hadoop-common,toddlipcon/hadoop,dongjiaqiang/hadoop-common,squidsolutions/hadoop-common,toddlipcon/hadoop,sztanko/hadoop-common,coderplay/hadoop-common,coderplay/hadoop-common,toddlipcon/hadoop,squidsolutions/hadoop-common,sztanko/hadoop-common,dongjiaqiang/hadoop-common,dhootha/hadoop-common,sztanko/hadoop-common,dhootha/hadoop-common,coderplay/hadoop-common,dongjiaqiang/hadoop-common,ShortMap/ShortMap,coderplay/hadoop-common,aseldawy/spatialhadoop,squidsolutions/hadoop-common,ShortMap/ShortMap,dhootha/hadoop-common,toddlipcon/hadoop,ShortMap/ShortMap,toddlipcon/hadoop,squidsolutions/hadoop-common,aseldawy/spatialhadoop,coderplay/hadoop-common,coderplay/hadoop-common,aseldawy/spatialhadoop,dhootha/hadoop-common,dongjiaqiang/hadoop-common,sztanko/hadoop-common,aseldawy/spatialhadoop | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.hadoop.ipc;
import java.io.IOException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.net.BindException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Iterator;
import java.util.Random;
import javax.security.auth.login.LoginException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.ObjectWritable;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableUtils;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.ipc.metrics.RpcMetrics;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.UnixUserGroupInformation;
/** An abstract IPC service. IPC calls take a single {@link Writable} as a
* parameter, and return a {@link Writable} as their value. A service runs on
* a port and is defined by a parameter class and a value class.
*
* @see Client
*/
public abstract class Server {
/**
* The first four bytes of Hadoop RPC connections
*/
public static final ByteBuffer HEADER = ByteBuffer.wrap("hrpc".getBytes());
// 1 : Ticket is added to connection header
public static final byte CURRENT_VERSION = 1;
/**
* How much time should be allocated for actually running the handler?
* Calls that are older than ipc.timeout * MAX_CALL_QUEUE_TIME
* are ignored when the handler takes them off the queue.
*/
private static final float MAX_CALL_QUEUE_TIME = 0.6f;
/**
* How many calls/handler are allowed in the queue.
*/
private static final int MAX_QUEUE_SIZE_PER_HANDLER = 100;
public static final Log LOG =
LogFactory.getLog("org.apache.hadoop.ipc.Server");
private static final ThreadLocal<Server> SERVER = new ThreadLocal<Server>();
/** Returns the server instance called under or null. May be called under
* {@link #call(Writable, long)} implementations, and under {@link Writable}
* methods of paramters and return values. Permits applications to access
* the server context.*/
public static Server get() {
return SERVER.get();
}
/** This is set to Call object before Handler invokes an RPC and reset
* after the call returns.
*/
private static final ThreadLocal<Call> CurCall = new ThreadLocal<Call>();
/** Returns the remote side ip address when invoked inside an RPC
* Returns null incase of an error.
*/
public static InetAddress getRemoteIp() {
Call call = CurCall.get();
if (call != null) {
return call.connection.socket.getInetAddress();
}
return null;
}
/** Returns remote address as a string when invoked inside an RPC.
* Returns null in case of an error.
*/
public static String getRemoteAddress() {
InetAddress addr = getRemoteIp();
return (addr == null) ? null : addr.getHostAddress();
}
/** Returns {@link UserGroupInformation} associated with current RPC.
* returns null if user information is not available.
*/
public static UserGroupInformation getUserInfo() {
Call call = CurCall.get();
if (call != null)
return call.connection.ticket;
// This is to support local calls (as opposed to rpc ones) to the name-node.
// Currently it is name-node specific and should be placed somewhere else.
try {
return UnixUserGroupInformation.login();
} catch(LoginException le) {
LOG.info(StringUtils.stringifyException(le));
return null;
}
}
private String bindAddress;
private int port; // port we listen on
private int handlerCount; // number of handler threads
private Class paramClass; // class of call parameters
private int maxIdleTime; // the maximum idle time after
// which a client may be disconnected
private int thresholdIdleConnections; // the number of idle connections
// after which we will start
// cleaning up idle
// connections
int maxConnectionsToNuke; // the max number of
// connections to nuke
//during a cleanup
protected RpcMetrics rpcMetrics;
private Configuration conf;
private int timeout;
private long maxCallStartAge;
private int maxQueueSize;
private int socketSendBufferSize;
private boolean tcpNoDelay; // if T then disable Nagle's Algorithm
volatile private boolean running = true; // true while server runs
private LinkedList<Call> callQueue = new LinkedList<Call>(); // queued calls
private List<Connection> connectionList =
Collections.synchronizedList(new LinkedList<Connection>());
//maintain a list
//of client connections
private Listener listener = null;
private Responder responder = null;
private int numConnections = 0;
private Handler[] handlers = null;
/**
* A convience method to bind to a given address and report
* better exceptions if the address is not a valid host.
* @param socket the socket to bind
* @param address the address to bind to
* @param backlog the number of connections allowed in the queue
* @throws BindException if the address can't be bound
* @throws UnknownHostException if the address isn't a valid host name
* @throws IOException other random errors from bind
*/
static void bind(ServerSocket socket, InetSocketAddress address,
int backlog) throws IOException {
try {
socket.bind(address, backlog);
} catch (BindException e) {
throw new BindException("Problem binding to " + address);
} catch (SocketException e) {
// If they try to bind to a different host's address, give a better
// error message.
if ("Unresolved address".equals(e.getMessage())) {
throw new UnknownHostException("Invalid hostname for server: " +
address.getHostName());
} else {
throw e;
}
}
}
/** A call queued for handling. */
private static class Call {
private int id; // the client's call id
private Writable param; // the parameter passed
private Connection connection; // connection to client
private long receivedTime; // the time received
private ByteBuffer response; // the response for this call
public Call(int id, Writable param, Connection connection) {
this.id = id;
this.param = param;
this.connection = connection;
this.receivedTime = System.currentTimeMillis();
this.response = null;
}
@Override
public String toString() {
return param.toString() + " from " + connection.toString();
}
public void setResponse(ByteBuffer response) {
this.response = response;
}
}
/** Listens on the socket. Creates jobs for the handler threads*/
private class Listener extends Thread {
private ServerSocketChannel acceptChannel = null; //the accept channel
private Selector selector = null; //the selector that we use for the server
private InetSocketAddress address; //the address we bind at
private Random rand = new Random();
private long lastCleanupRunTime = 0; //the last time when a cleanup connec-
//-tion (for idle connections) ran
private long cleanupInterval = 10000; //the minimum interval between
//two cleanup runs
private int backlogLength = conf.getInt("ipc.server.listen.queue.size", 128);
public Listener() throws IOException {
address = new InetSocketAddress(bindAddress, port);
// Create a new server socket and set to non blocking mode
acceptChannel = ServerSocketChannel.open();
acceptChannel.configureBlocking(false);
// Bind the server socket to the local host and port
bind(acceptChannel.socket(), address, backlogLength);
port = acceptChannel.socket().getLocalPort(); //Could be an ephemeral port
// create a selector;
selector= Selector.open();
// Register accepts on the server socket with the selector.
acceptChannel.register(selector, SelectionKey.OP_ACCEPT);
this.setName("IPC Server listener on " + port);
this.setDaemon(true);
}
/** cleanup connections from connectionList. Choose a random range
* to scan and also have a limit on the number of the connections
* that will be cleanedup per run. The criteria for cleanup is the time
* for which the connection was idle. If 'force' is true then all
* connections will be looked at for the cleanup.
*/
private void cleanupConnections(boolean force) {
if (force || numConnections > thresholdIdleConnections) {
long currentTime = System.currentTimeMillis();
if (!force && (currentTime - lastCleanupRunTime) < cleanupInterval) {
return;
}
int start = 0;
int end = numConnections - 1;
if (!force) {
start = rand.nextInt() % numConnections;
end = rand.nextInt() % numConnections;
int temp;
if (end < start) {
temp = start;
start = end;
end = temp;
}
}
int i = start;
int numNuked = 0;
while (i <= end) {
Connection c;
synchronized (connectionList) {
try {
c = connectionList.get(i);
} catch (Exception e) {return;}
}
if (c.timedOut(currentTime)) {
if (LOG.isDebugEnabled())
LOG.debug(getName() + ": disconnecting client " + c.getHostAddress());
closeConnection(c);
numNuked++;
end--;
c = null;
if (!force && numNuked == maxConnectionsToNuke) break;
}
else i++;
}
lastCleanupRunTime = System.currentTimeMillis();
}
}
@Override
public void run() {
LOG.info(getName() + ": starting");
SERVER.set(Server.this);
while (running) {
SelectionKey key = null;
try {
selector.select();
Iterator iter = selector.selectedKeys().iterator();
while (iter.hasNext()) {
key = (SelectionKey)iter.next();
iter.remove();
try {
if (key.isValid()) {
if (key.isAcceptable())
doAccept(key);
else if (key.isReadable())
doRead(key);
}
} catch (IOException e) {
}
key = null;
}
} catch (OutOfMemoryError e) {
// we can run out of memory if we have too many threads
// log the event and sleep for a minute and give
// some thread(s) a chance to finish
LOG.warn("Out of Memory in server select", e);
closeCurrentConnection(key, e);
cleanupConnections(true);
try { Thread.sleep(60000); } catch (Exception ie) {}
} catch (Exception e) {
closeCurrentConnection(key, e);
}
cleanupConnections(false);
}
LOG.info("Stopping " + this.getName());
synchronized (this) {
try {
acceptChannel.close();
selector.close();
} catch (IOException e) { }
selector= null;
acceptChannel= null;
connectionList = null;
}
}
private void closeCurrentConnection(SelectionKey key, Throwable e) {
if (key != null) {
Connection c = (Connection)key.attachment();
if (c != null) {
if (LOG.isDebugEnabled())
LOG.debug(getName() + ": disconnecting client " + c.getHostAddress());
closeConnection(c);
c = null;
}
}
}
InetSocketAddress getAddress() {
return (InetSocketAddress)acceptChannel.socket().getLocalSocketAddress();
}
void doAccept(SelectionKey key) throws IOException, OutOfMemoryError {
Connection c = null;
ServerSocketChannel server = (ServerSocketChannel) key.channel();
SocketChannel channel = server.accept();
channel.configureBlocking(false);
channel.socket().setTcpNoDelay(tcpNoDelay);
SelectionKey readKey = channel.register(selector, SelectionKey.OP_READ);
c = new Connection(readKey, channel, System.currentTimeMillis());
readKey.attach(c);
synchronized (connectionList) {
connectionList.add(numConnections, c);
numConnections++;
}
if (LOG.isDebugEnabled())
LOG.debug("Server connection from " + c.toString() +
"; # active connections: " + numConnections +
"; # queued calls: " + callQueue.size());
}
void doRead(SelectionKey key) {
int count = 0;
Connection c = (Connection)key.attachment();
if (c == null) {
return;
}
c.setLastContact(System.currentTimeMillis());
try {
count = c.readAndProcess();
} catch (Exception e) {
LOG.debug(getName() + ": readAndProcess threw exception " + e + ". Count of bytes read: " + count, e);
count = -1; //so that the (count < 0) block is executed
}
if (count < 0) {
if (LOG.isDebugEnabled())
LOG.debug(getName() + ": disconnecting client " +
c.getHostAddress() + ". Number of active connections: "+
numConnections);
closeConnection(c);
c = null;
}
else {
c.setLastContact(System.currentTimeMillis());
}
}
synchronized void doStop() {
if (selector != null) {
selector.wakeup();
Thread.yield();
}
if (acceptChannel != null) {
try {
acceptChannel.socket().close();
} catch (IOException e) {
LOG.info(getName() + ":Exception in closing listener socket. " + e);
}
}
}
}
// Sends responses of RPC back to clients.
private class Responder extends Thread {
private Selector writeSelector;
private int pending; // connections waiting to register
Responder() throws IOException {
this.setName("IPC Server Responder");
this.setDaemon(true);
writeSelector = Selector.open(); // create a selector
pending = 0;
}
@Override
public void run() {
LOG.info(getName() + ": starting");
SERVER.set(Server.this);
long lastPurgeTime = 0; // last check for old calls.
while (running) {
try {
waitPending(); // If a channel is being registered, wait.
writeSelector.select(maxCallStartAge);
Iterator<SelectionKey> iter = writeSelector.selectedKeys().iterator();
while (iter.hasNext()) {
SelectionKey key = iter.next();
iter.remove();
try {
if (key.isValid() && key.isWritable()) {
doAsyncWrite(key);
}
} catch (IOException e) {
LOG.info(getName() + ": doAsyncWrite threw exception " + e);
}
}
long now = System.currentTimeMillis();
if (now < lastPurgeTime + maxCallStartAge) {
continue;
}
lastPurgeTime = now;
//
// If there were some calls that have not been sent out for a
// long time, discard them.
//
LOG.debug("Checking for old call responses.");
iter = writeSelector.keys().iterator();
while (iter.hasNext()) {
SelectionKey key = iter.next();
try {
doPurge(key, now);
} catch (IOException e) {
LOG.warn("Error in purging old calls " + e);
}
}
} catch (OutOfMemoryError e) {
//
// we can run out of memory if we have too many threads
// log the event and sleep for a minute and give
// some thread(s) a chance to finish
//
LOG.warn("Out of Memory in server select", e);
try { Thread.sleep(60000); } catch (Exception ie) {}
} catch (Exception e) {
LOG.warn("Exception in Responder " +
StringUtils.stringifyException(e));
}
}
LOG.info("Stopping " + this.getName());
}
private void doAsyncWrite(SelectionKey key) throws IOException {
Call call = (Call)key.attachment();
if (call == null) {
return;
}
if (key.channel() != call.connection.channel) {
throw new IOException("doAsyncWrite: bad channel");
}
synchronized(call.connection.responseQueue) {
if (processResponse(call.connection.responseQueue, false)) {
try {
key.interestOps(0);
} catch (CancelledKeyException e) {
/* The Listener/reader might have closed the socket.
* We don't explicitly cancel the key, so not sure if this will
* ever fire.
* This warning could be removed.
*/
LOG.warn("Exception while changing ops : " + e);
}
}
}
}
//
// Remove calls that have been pending in the responseQueue
// for a long time.
//
private void doPurge(SelectionKey key, long now) throws IOException {
Call call = (Call)key.attachment();
if (call == null) {
return;
}
if (key.channel() != call.connection.channel) {
LOG.info("doPurge: bad channel");
return;
}
boolean close = false;
LinkedList<Call> responseQueue = call.connection.responseQueue;
synchronized (responseQueue) {
Iterator<Call> iter = responseQueue.listIterator(0);
while (iter.hasNext()) {
call = iter.next();
if (now > call.receivedTime + maxCallStartAge) {
LOG.info(getName() + ", call " + call +
": response discarded for being too old (" +
(now - call.receivedTime) + ")");
iter.remove();
if (call.response.position() > 0) {
/* We should probably use a different start time
* than receivedTime. receivedTime starts when the RPC
* was first read.
* We have written a partial response. will close the
* connection for now.
*/
close = true;
break;
}
}
}
}
if (close) {
closeConnection(call.connection);
}
}
// Processes one response. Returns true if there are no more pending
// data for this channel.
//
private boolean processResponse(LinkedList<Call> responseQueue,
boolean inHandler) throws IOException {
boolean error = true;
boolean done = false; // there is more data for this channel.
int numElements = 0;
Call call = null;
try {
synchronized (responseQueue) {
//
// If there are no items for this channel, then we are done
//
numElements = responseQueue.size();
if (numElements == 0) {
error = false;
return true; // no more data for this channel.
}
//
// Extract the first call
//
call = responseQueue.removeFirst();
SocketChannel channel = call.connection.channel;
if (LOG.isDebugEnabled()) {
LOG.debug(getName() + ": responding to #" + call.id + " from " +
call.connection);
}
//
// Send as much data as we can in the non-blocking fashion
//
int numBytes = channel.write(call.response);
if (numBytes < 0) {
return true;
}
if (!call.response.hasRemaining()) {
if (numElements == 1) { // last call fully processes.
done = true; // no more data for this channel.
} else {
done = false; // more calls pending to be sent.
}
if (LOG.isDebugEnabled()) {
LOG.debug(getName() + ": responding to #" + call.id + " from " +
call.connection + " Wrote " + numBytes + " bytes.");
}
} else {
//
// If we were unable to write the entire response out, then
// insert in Selector queue.
//
call.connection.responseQueue.addFirst(call);
if (inHandler) {
incPending();
try {
// Wakeup the thread blocked on select, only then can the call
// to channel.register() complete.
writeSelector.wakeup();
channel.register(writeSelector, SelectionKey.OP_WRITE, call);
} catch (ClosedChannelException e) {
//Its ok. channel might be closed else where.
done = true;
} finally {
decPending();
}
}
if (LOG.isDebugEnabled()) {
LOG.debug(getName() + ": responding to #" + call.id + " from " +
call.connection + " Wrote partial " + numBytes +
" bytes.");
}
}
error = false; // everything went off well
}
} finally {
if (error && call != null) {
LOG.warn(getName()+", call " + call + ": output error");
done = true; // error. no more data for this channel.
closeConnection(call.connection);
}
}
return done;
}
//
// Enqueue a response from the application.
//
void doRespond(Call call) throws IOException {
synchronized (call.connection.responseQueue) {
call.connection.responseQueue.addLast(call);
if (call.connection.responseQueue.size() == 1) {
processResponse(call.connection.responseQueue, true);
}
}
}
private synchronized void incPending() { // call waiting to be enqueued.
pending++;
}
private synchronized void decPending() { // call done enqueueing.
pending--;
notify();
}
private synchronized void waitPending() throws InterruptedException {
while (pending > 0) {
wait();
}
}
}
/** Reads calls from a connection and queues them for handling. */
private class Connection {
private boolean versionRead = false; //if initial signature and
//version are read
private boolean headerRead = false; //if the connection header that
//follows version is read.
private SocketChannel channel;
private ByteBuffer data;
private ByteBuffer dataLengthBuffer;
private LinkedList<Call> responseQueue;
private long lastContact;
private int dataLength;
private Socket socket;
// Cache the remote host & port info so that even if the socket is
// disconnected, we can say where it used to connect to.
private String hostAddress;
private int remotePort;
private UserGroupInformation ticket = null;
public Connection(SelectionKey key, SocketChannel channel,
long lastContact) {
this.channel = channel;
this.lastContact = lastContact;
this.data = null;
this.dataLengthBuffer = ByteBuffer.allocate(4);
this.socket = channel.socket();
InetAddress addr = socket.getInetAddress();
if (addr == null) {
this.hostAddress = "*Unknown*";
} else {
this.hostAddress = addr.getHostAddress();
}
this.remotePort = socket.getPort();
this.responseQueue = new LinkedList<Call>();
if (socketSendBufferSize != 0) {
try {
socket.setSendBufferSize(socketSendBufferSize);
} catch (IOException e) {
LOG.warn("Connection: unable to set socket send buffer size to " +
socketSendBufferSize);
}
}
}
@Override
public String toString() {
return getHostAddress() + ":" + remotePort;
}
public String getHostAddress() {
return hostAddress;
}
public void setLastContact(long lastContact) {
this.lastContact = lastContact;
}
public long getLastContact() {
return lastContact;
}
private boolean timedOut(long currentTime) {
if (currentTime - lastContact > maxIdleTime)
return true;
return false;
}
public int readAndProcess() throws IOException, InterruptedException {
while (true) {
/* Read at most one RPC. If the header is not read completely yet
* then iterate until we read first RPC or until there is no data left.
*/
int count = -1;
if (dataLengthBuffer.remaining() > 0) {
count = channel.read(dataLengthBuffer);
if (count < 0 || dataLengthBuffer.remaining() > 0)
return count;
}
if (!versionRead) {
//Every connection is expected to send the header.
ByteBuffer versionBuffer = ByteBuffer.allocate(1);
count = channel.read(versionBuffer);
if (count <= 0) {
return count;
}
int version = versionBuffer.get(0);
dataLengthBuffer.flip();
if (!HEADER.equals(dataLengthBuffer) || version != CURRENT_VERSION) {
//Warning is ok since this is not supposed to happen.
LOG.warn("Incorrect header or version mismatch from " +
hostAddress + ":" + remotePort +
" got version " + version +
" expected version " + CURRENT_VERSION);
return -1;
}
dataLengthBuffer.clear();
versionRead = true;
continue;
}
if (data == null) {
dataLengthBuffer.flip();
dataLength = dataLengthBuffer.getInt();
data = ByteBuffer.allocate(dataLength);
}
count = channel.read(data);
if (data.remaining() == 0) {
dataLengthBuffer.clear();
data.flip();
if (headerRead) {
processData();
data = null;
return count;
} else {
processHeader();
headerRead = true;
data = null;
continue;
}
}
return count;
}
}
/// Reads the header following version
private void processHeader() throws IOException {
/* In the current version, it is just a ticket.
* Later we could introduce a "ConnectionHeader" class.
*/
DataInputStream in =
new DataInputStream(new ByteArrayInputStream(data.array()));
ticket = (UserGroupInformation) ObjectWritable.readObject(in, conf);
}
private void processData() throws IOException, InterruptedException {
DataInputStream dis =
new DataInputStream(new ByteArrayInputStream(data.array()));
int id = dis.readInt(); // try to read an id
if (LOG.isDebugEnabled())
LOG.debug(" got #" + id);
Writable param = (Writable)ReflectionUtils.newInstance(paramClass, conf); // read param
param.readFields(dis);
Call call = new Call(id, param, this);
synchronized (callQueue) {
if (callQueue.size() >= maxQueueSize) {
Call oldCall = callQueue.removeFirst();
LOG.warn("Call queue overflow discarding oldest call " + oldCall);
}
callQueue.addLast(call); // queue the call
callQueue.notify(); // wake up a waiting handler
}
}
private synchronized void close() throws IOException {
data = null;
dataLengthBuffer = null;
if (!channel.isOpen())
return;
try {socket.shutdownOutput();} catch(Exception e) {}
if (channel.isOpen()) {
try {channel.close();} catch(Exception e) {}
}
try {socket.close();} catch(Exception e) {}
}
}
/** Handles queued calls . */
private class Handler extends Thread {
public Handler(int instanceNumber) {
this.setDaemon(true);
this.setName("IPC Server handler "+ instanceNumber + " on " + port);
}
@Override
public void run() {
LOG.info(getName() + ": starting");
SERVER.set(Server.this);
ByteArrayOutputStream buf = new ByteArrayOutputStream(10240);
while (running) {
try {
Call call;
synchronized (callQueue) {
while (running && callQueue.size()==0) { // wait for a call
callQueue.wait(timeout);
}
if (!running) break;
call = callQueue.removeFirst(); // pop the queue
}
// throw the message away if it is too old
if (System.currentTimeMillis() - call.receivedTime >
maxCallStartAge) {
ReflectionUtils.logThreadInfo(LOG, "Discarding call " + call, 30);
int timeInQ = (int) (System.currentTimeMillis() - call.receivedTime);
LOG.warn(getName()+", call "+call
+": discarded for being too old (" +
timeInQ + ")");
rpcMetrics.rpcDiscardedOps.inc(timeInQ);
continue;
}
if (LOG.isDebugEnabled())
LOG.debug(getName() + ": has #" + call.id + " from " +
call.connection);
String errorClass = null;
String error = null;
Writable value = null;
CurCall.set(call);
try {
value = call(call.param, call.receivedTime); // make the call
} catch (Throwable e) {
LOG.info(getName()+", call "+call+": error: " + e, e);
errorClass = e.getClass().getName();
error = StringUtils.stringifyException(e);
}
CurCall.set(null);
buf.reset();
DataOutputStream out = new DataOutputStream(buf);
out.writeInt(call.id); // write call id
out.writeBoolean(error != null); // write error flag
if (error == null) {
value.write(out);
} else {
WritableUtils.writeString(out, errorClass);
WritableUtils.writeString(out, error);
}
call.setResponse(ByteBuffer.wrap(buf.toByteArray()));
responder.doRespond(call);
} catch (InterruptedException e) {
if (running) { // unexpected -- log it
LOG.info(getName() + " caught: " +
StringUtils.stringifyException(e));
}
} catch (Exception e) {
LOG.info(getName() + " caught: " +
StringUtils.stringifyException(e));
}
}
LOG.info(getName() + ": exiting");
}
}
protected Server(String bindAddress, int port, Class paramClass, int handlerCount, Configuration conf)
throws IOException
{
this(bindAddress, port, paramClass, handlerCount, conf, Integer.toString(port));
}
/** Constructs a server listening on the named port and address. Parameters passed must
* be of the named class. The <code>handlerCount</handlerCount> determines
* the number of handler threads that will be used to process calls.
*
*/
protected Server(String bindAddress, int port, Class paramClass, int handlerCount, Configuration conf,
String serverName)
throws IOException {
this.bindAddress = bindAddress;
this.conf = conf;
this.port = port;
this.paramClass = paramClass;
this.handlerCount = handlerCount;
this.timeout = conf.getInt("ipc.client.timeout", 10000);
this.socketSendBufferSize = 0;
maxCallStartAge = (long) (timeout * MAX_CALL_QUEUE_TIME);
maxQueueSize = handlerCount * MAX_QUEUE_SIZE_PER_HANDLER;
this.maxIdleTime = conf.getInt("ipc.client.maxidletime", 120000);
this.maxConnectionsToNuke = conf.getInt("ipc.client.kill.max", 10);
this.thresholdIdleConnections = conf.getInt("ipc.client.idlethreshold", 4000);
// Start the listener here and let it bind to the port
listener = new Listener();
this.port = listener.getAddress().getPort();
this.rpcMetrics = new RpcMetrics(serverName,
Integer.toString(this.port), this);
// Create the responder here
responder = new Responder();
}
private void closeConnection(Connection connection) {
synchronized (connectionList) {
if (connectionList.remove(connection))
numConnections--;
}
try {
connection.close();
} catch (IOException e) {
}
}
/** Sets the timeout used for network i/o. */
public void setTimeout(int timeout) { this.timeout = timeout; }
/** Sets the socket buffer size used for responding to RPCs */
public void setSocketSendBufSize(int size) { this.socketSendBufferSize = size; }
/** Starts the service. Must be called before any calls will be handled. */
public synchronized void start() throws IOException {
responder.start();
listener.start();
handlers = new Handler[handlerCount];
for (int i = 0; i < handlerCount; i++) {
handlers[i] = new Handler(i);
handlers[i].start();
}
}
/** Stops the service. No new calls will be handled after this is called. */
public synchronized void stop() {
LOG.info("Stopping server on " + port);
running = false;
if (handlers != null) {
for (int i = 0; i < handlerCount; i++) {
if (handlers[i] != null) {
handlers[i].interrupt();
}
}
}
listener.interrupt();
listener.doStop();
responder.interrupt();
notifyAll();
if (this.rpcMetrics != null) {
this.rpcMetrics.shutdown();
}
}
/** Wait for the server to be stopped.
* Does not wait for all subthreads to finish.
* See {@link #stop()}.
*/
public synchronized void join() throws InterruptedException {
while (running) {
wait();
}
}
/**
* Return the socket (ip+port) on which the RPC server is listening to.
* @return the socket (ip+port) on which the RPC server is listening to.
*/
public synchronized InetSocketAddress getListenerAddress() {
return listener.getAddress();
}
/** Called for each call. */
public abstract Writable call(Writable param, long receiveTime)
throws IOException;
/**
* The number of open RPC conections
* @return the number of open rpc connections
*/
public int getNumOpenConnections() {
return numConnections;
}
/**
* The number of rpc calls in the queue.
* @return The number of rpc calls in the queue.
*/
public int getCallQueueLen() {
return callQueue.size();
}
}
| src/java/org/apache/hadoop/ipc/Server.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.hadoop.ipc;
import java.io.IOException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.net.BindException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Iterator;
import java.util.Random;
import javax.security.auth.login.LoginException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.ObjectWritable;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableUtils;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.ipc.metrics.RpcMetrics;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.UnixUserGroupInformation;
/** An abstract IPC service. IPC calls take a single {@link Writable} as a
* parameter, and return a {@link Writable} as their value. A service runs on
* a port and is defined by a parameter class and a value class.
*
* @see Client
*/
public abstract class Server {
/**
* The first four bytes of Hadoop RPC connections
*/
public static final ByteBuffer HEADER = ByteBuffer.wrap("hrpc".getBytes());
// 1 : Ticket is added to connection header
public static final byte CURRENT_VERSION = 1;
/**
* How much time should be allocated for actually running the handler?
* Calls that are older than ipc.timeout * MAX_CALL_QUEUE_TIME
* are ignored when the handler takes them off the queue.
*/
private static final float MAX_CALL_QUEUE_TIME = 0.6f;
/**
* How many calls/handler are allowed in the queue.
*/
private static final int MAX_QUEUE_SIZE_PER_HANDLER = 100;
public static final Log LOG =
LogFactory.getLog("org.apache.hadoop.ipc.Server");
private static final ThreadLocal<Server> SERVER = new ThreadLocal<Server>();
/** Returns the server instance called under or null. May be called under
* {@link #call(Writable, long)} implementations, and under {@link Writable}
* methods of paramters and return values. Permits applications to access
* the server context.*/
public static Server get() {
return SERVER.get();
}
/** This is set to Call object before Handler invokes an RPC and reset
* after the call returns.
*/
private static final ThreadLocal<Call> CurCall = new ThreadLocal<Call>();
/** Returns the remote side ip address when invoked inside an RPC
* Returns null incase of an error.
*/
public static InetAddress getRemoteIp() {
Call call = CurCall.get();
if (call != null) {
return call.connection.socket.getInetAddress();
}
return null;
}
/** Returns remote address as a string when invoked inside an RPC.
* Returns null in case of an error.
*/
public static String getRemoteAddress() {
InetAddress addr = getRemoteIp();
return (addr == null) ? null : addr.getHostAddress();
}
/** Returns {@link UserGroupInformation} associated with current RPC.
* returns null if user information is not available.
*/
public static UserGroupInformation getUserInfo() {
Call call = CurCall.get();
if (call != null)
return call.connection.ticket;
// This is to support local calls (as opposed to rpc ones) to the name-node.
// Currently it is name-node specific and should be placed somewhere else.
try {
return UnixUserGroupInformation.login();
} catch(LoginException le) {
LOG.info(StringUtils.stringifyException(le));
return null;
}
}
private String bindAddress;
private int port; // port we listen on
private int handlerCount; // number of handler threads
private Class paramClass; // class of call parameters
private int maxIdleTime; // the maximum idle time after
// which a client may be disconnected
private int thresholdIdleConnections; // the number of idle connections
// after which we will start
// cleaning up idle
// connections
int maxConnectionsToNuke; // the max number of
// connections to nuke
//during a cleanup
protected RpcMetrics rpcMetrics;
private Configuration conf;
private int timeout;
private long maxCallStartAge;
private int maxQueueSize;
private int socketSendBufferSize;
private boolean tcpNoDelay; // if T then disable Nagle's Algorithm
volatile private boolean running = true; // true while server runs
private LinkedList<Call> callQueue = new LinkedList<Call>(); // queued calls
private List<Connection> connectionList =
Collections.synchronizedList(new LinkedList<Connection>());
//maintain a list
//of client connections
private Listener listener = null;
private Responder responder = null;
private int numConnections = 0;
private Handler[] handlers = null;
/**
* A convience method to bind to a given address and report
* better exceptions if the address is not a valid host.
* @param socket the socket to bind
* @param address the address to bind to
* @param backlog the number of connections allowed in the queue
* @throws BindException if the address can't be bound
* @throws UnknownHostException if the address isn't a valid host name
* @throws IOException other random errors from bind
*/
static void bind(ServerSocket socket, InetSocketAddress address,
int backlog) throws IOException {
try {
socket.bind(address, backlog);
} catch (BindException e) {
throw new BindException("Problem binding to " + address);
} catch (SocketException e) {
// If they try to bind to a different host's address, give a better
// error message.
if ("Unresolved address".equals(e.getMessage())) {
throw new UnknownHostException("Invalid hostname for server: " +
address.getHostName());
} else {
throw e;
}
}
}
/** A call queued for handling. */
private static class Call {
private int id; // the client's call id
private Writable param; // the parameter passed
private Connection connection; // connection to client
private long receivedTime; // the time received
private ByteBuffer response; // the response for this call
public Call(int id, Writable param, Connection connection) {
this.id = id;
this.param = param;
this.connection = connection;
this.receivedTime = System.currentTimeMillis();
this.response = null;
}
@Override
public String toString() {
return param.toString() + " from " + connection.toString();
}
public void setResponse(ByteBuffer response) {
this.response = response;
}
}
/** Listens on the socket. Creates jobs for the handler threads*/
private class Listener extends Thread {
private ServerSocketChannel acceptChannel = null; //the accept channel
private Selector selector = null; //the selector that we use for the server
private InetSocketAddress address; //the address we bind at
private Random rand = new Random();
private long lastCleanupRunTime = 0; //the last time when a cleanup connec-
//-tion (for idle connections) ran
private long cleanupInterval = 10000; //the minimum interval between
//two cleanup runs
private int backlogLength = conf.getInt("ipc.server.listen.queue.size", 128);
public Listener() throws IOException {
address = new InetSocketAddress(bindAddress, port);
// Create a new server socket and set to non blocking mode
acceptChannel = ServerSocketChannel.open();
acceptChannel.configureBlocking(false);
// Bind the server socket to the local host and port
bind(acceptChannel.socket(), address, backlogLength);
port = acceptChannel.socket().getLocalPort(); //Could be an ephemeral port
// create a selector;
selector= Selector.open();
// Register accepts on the server socket with the selector.
acceptChannel.register(selector, SelectionKey.OP_ACCEPT);
this.setName("IPC Server listener on " + port);
this.setDaemon(true);
}
/** cleanup connections from connectionList. Choose a random range
* to scan and also have a limit on the number of the connections
* that will be cleanedup per run. The criteria for cleanup is the time
* for which the connection was idle. If 'force' is true then all
* connections will be looked at for the cleanup.
*/
private void cleanupConnections(boolean force) {
if (force || numConnections > thresholdIdleConnections) {
long currentTime = System.currentTimeMillis();
if (!force && (currentTime - lastCleanupRunTime) < cleanupInterval) {
return;
}
int start = 0;
int end = numConnections - 1;
if (!force) {
start = rand.nextInt() % numConnections;
end = rand.nextInt() % numConnections;
int temp;
if (end < start) {
temp = start;
start = end;
end = temp;
}
}
int i = start;
int numNuked = 0;
while (i <= end) {
Connection c;
synchronized (connectionList) {
try {
c = connectionList.get(i);
} catch (Exception e) {return;}
}
if (c.timedOut(currentTime)) {
if (LOG.isDebugEnabled())
LOG.debug(getName() + ": disconnecting client " + c.getHostAddress());
closeConnection(c);
numNuked++;
end--;
c = null;
if (!force && numNuked == maxConnectionsToNuke) break;
}
else i++;
}
lastCleanupRunTime = System.currentTimeMillis();
}
}
@Override
public void run() {
LOG.info(getName() + ": starting");
SERVER.set(Server.this);
while (running) {
SelectionKey key = null;
try {
selector.select();
Iterator iter = selector.selectedKeys().iterator();
while (iter.hasNext()) {
key = (SelectionKey)iter.next();
iter.remove();
try {
if (key.isValid()) {
if (key.isAcceptable())
doAccept(key);
else if (key.isReadable())
doRead(key);
}
} catch (IOException e) {
}
key = null;
}
} catch (OutOfMemoryError e) {
// we can run out of memory if we have too many threads
// log the event and sleep for a minute and give
// some thread(s) a chance to finish
LOG.warn("Out of Memory in server select", e);
closeCurrentConnection(key, e);
cleanupConnections(true);
try { Thread.sleep(60000); } catch (Exception ie) {}
} catch (Exception e) {
closeCurrentConnection(key, e);
}
cleanupConnections(false);
}
LOG.info("Stopping " + this.getName());
synchronized (this) {
try {
acceptChannel.close();
selector.close();
} catch (IOException e) { }
selector= null;
acceptChannel= null;
connectionList = null;
}
}
private void closeCurrentConnection(SelectionKey key, Throwable e) {
if (key != null) {
Connection c = (Connection)key.attachment();
if (c != null) {
if (LOG.isDebugEnabled())
LOG.debug(getName() + ": disconnecting client " + c.getHostAddress());
closeConnection(c);
c = null;
}
}
}
InetSocketAddress getAddress() {
return (InetSocketAddress)acceptChannel.socket().getLocalSocketAddress();
}
void doAccept(SelectionKey key) throws IOException, OutOfMemoryError {
Connection c = null;
ServerSocketChannel server = (ServerSocketChannel) key.channel();
SocketChannel channel = server.accept();
channel.configureBlocking(false);
channel.socket().setTcpNoDelay(tcpNoDelay);
SelectionKey readKey = channel.register(selector, SelectionKey.OP_READ);
c = new Connection(readKey, channel, System.currentTimeMillis());
readKey.attach(c);
synchronized (connectionList) {
connectionList.add(numConnections, c);
numConnections++;
}
if (LOG.isDebugEnabled())
LOG.debug("Server connection from " + c.toString() +
"; # active connections: " + numConnections +
"; # queued calls: " + callQueue.size());
}
void doRead(SelectionKey key) {
int count = 0;
Connection c = (Connection)key.attachment();
if (c == null) {
return;
}
c.setLastContact(System.currentTimeMillis());
try {
count = c.readAndProcess();
} catch (Exception e) {
LOG.debug(getName() + ": readAndProcess threw exception " + e + ". Count of bytes read: " + count, e);
count = -1; //so that the (count < 0) block is executed
}
if (count < 0) {
if (LOG.isDebugEnabled())
LOG.debug(getName() + ": disconnecting client " +
c.getHostAddress() + ". Number of active connections: "+
numConnections);
closeConnection(c);
c = null;
}
else {
c.setLastContact(System.currentTimeMillis());
}
}
synchronized void doStop() {
if (selector != null) {
selector.wakeup();
Thread.yield();
}
if (acceptChannel != null) {
try {
acceptChannel.socket().close();
} catch (IOException e) {
LOG.info(getName() + ":Exception in closing listener socket. " + e);
}
}
}
}
// Sends responses of RPC back to clients.
private class Responder extends Thread {
private Selector writeSelector;
private int pending; // connections waiting to register
Responder() throws IOException {
this.setName("IPC Server Responder");
this.setDaemon(true);
writeSelector = Selector.open(); // create a selector
pending = 0;
}
@Override
public void run() {
LOG.info(getName() + ": starting");
SERVER.set(Server.this);
long lastPurgeTime = 0; // last check for old calls.
while (running) {
try {
waitPending(); // If a channel is being registered, wait.
writeSelector.select(maxCallStartAge);
Iterator<SelectionKey> iter = writeSelector.selectedKeys().iterator();
while (iter.hasNext()) {
SelectionKey key = iter.next();
iter.remove();
try {
if (key.isValid() && key.isWritable()) {
doAsyncWrite(key);
}
} catch (IOException e) {
LOG.info(getName() + ": doAsyncWrite threw exception " + e);
}
}
long now = System.currentTimeMillis();
if (now < lastPurgeTime + maxCallStartAge) {
continue;
}
lastPurgeTime = now;
//
// If there were some calls that have not been sent out for a
// long time, discard them.
//
LOG.debug("Checking for old call responses.");
iter = writeSelector.keys().iterator();
while (iter.hasNext()) {
SelectionKey key = iter.next();
try {
doPurge(key, now);
} catch (IOException e) {
LOG.warn("Error in purging old calls " + e);
}
}
} catch (OutOfMemoryError e) {
//
// we can run out of memory if we have too many threads
// log the event and sleep for a minute and give
// some thread(s) a chance to finish
//
LOG.warn("Out of Memory in server select", e);
try { Thread.sleep(60000); } catch (Exception ie) {}
} catch (Exception e) {
LOG.warn("Exception in Responder " +
StringUtils.stringifyException(e));
}
}
LOG.info("Stopping " + this.getName());
}
private void doAsyncWrite(SelectionKey key) throws IOException {
Call call = (Call)key.attachment();
if (call == null) {
return;
}
if (key.channel() != call.connection.channel) {
throw new IOException("doAsyncWrite: bad channel");
}
synchronized(call.connection.responseQueue) {
if (processResponse(call.connection.responseQueue, false)) {
try {
key.interestOps(0);
} catch (CancelledKeyException e) {
/* The Listener/reader might have closed the socket.
* We don't explicitly cancel the key, so not sure if this will
* ever fire.
* This warning could be removed.
*/
LOG.warn("Exception while changing ops : " + e);
}
}
}
}
//
// Remove calls that have been pending in the responseQueue
// for a long time.
//
private void doPurge(SelectionKey key, long now) throws IOException {
Call call = (Call)key.attachment();
if (call == null) {
return;
}
if (key.channel() != call.connection.channel) {
LOG.info("doPurge: bad channel");
return;
}
boolean close = false;
LinkedList<Call> responseQueue = call.connection.responseQueue;
synchronized (responseQueue) {
Iterator<Call> iter = responseQueue.listIterator(0);
while (iter.hasNext()) {
call = iter.next();
if (call.response.position() > 0) {
/* We should probably use a different a different start time
* than receivedTime. receivedTime starts when the RPC
* was first read.
* We have written a partial response. will close the
* connection for now.
*/
close = true;
break;
}
if (now > call.receivedTime + maxCallStartAge) {
LOG.info(getName() + ", call " + call +
": response discarded for being too old (" +
(now - call.receivedTime) + ")");
iter.remove();
}
}
}
if (close) {
closeConnection(call.connection);
}
}
// Processes one response. Returns true if there are no more pending
// data for this channel.
//
private boolean processResponse(LinkedList<Call> responseQueue,
boolean inHandler) throws IOException {
boolean error = true;
boolean done = false; // there is more data for this channel.
int numElements = 0;
Call call = null;
try {
synchronized (responseQueue) {
//
// If there are no items for this channel, then we are done
//
numElements = responseQueue.size();
if (numElements == 0) {
error = false;
return true; // no more data for this channel.
}
//
// Extract the first call
//
call = responseQueue.removeFirst();
SocketChannel channel = call.connection.channel;
if (LOG.isDebugEnabled()) {
LOG.debug(getName() + ": responding to #" + call.id + " from " +
call.connection);
}
//
// Send as much data as we can in the non-blocking fashion
//
int numBytes = channel.write(call.response);
if (numBytes < 0) {
return true;
}
if (!call.response.hasRemaining()) {
if (numElements == 1) { // last call fully processes.
done = true; // no more data for this channel.
} else {
done = false; // more calls pending to be sent.
}
if (LOG.isDebugEnabled()) {
LOG.debug(getName() + ": responding to #" + call.id + " from " +
call.connection + " Wrote " + numBytes + " bytes.");
}
} else {
//
// If we were unable to write the entire response out, then
// insert in Selector queue.
//
call.connection.responseQueue.addFirst(call);
if (inHandler) {
incPending();
try {
// Wakeup the thread blocked on select, only then can the call
// to channel.register() complete.
writeSelector.wakeup();
channel.register(writeSelector, SelectionKey.OP_WRITE, call);
} catch (ClosedChannelException e) {
//Its ok. channel might be closed else where.
done = true;
} finally {
decPending();
}
}
if (LOG.isDebugEnabled()) {
LOG.debug(getName() + ": responding to #" + call.id + " from " +
call.connection + " Wrote partial " + numBytes +
" bytes.");
}
}
error = false; // everything went off well
}
} finally {
if (error && call != null) {
LOG.warn(getName()+", call " + call + ": output error");
done = true; // error. no more data for this channel.
closeConnection(call.connection);
}
}
return done;
}
//
// Enqueue a response from the application.
//
void doRespond(Call call) throws IOException {
synchronized (call.connection.responseQueue) {
call.connection.responseQueue.addLast(call);
if (call.connection.responseQueue.size() == 1) {
processResponse(call.connection.responseQueue, true);
}
}
}
private synchronized void incPending() { // call waiting to be enqueued.
pending++;
}
private synchronized void decPending() { // call done enqueueing.
pending--;
notify();
}
private synchronized void waitPending() throws InterruptedException {
while (pending > 0) {
wait();
}
}
}
/** Reads calls from a connection and queues them for handling. */
private class Connection {
private boolean versionRead = false; //if initial signature and
//version are read
private boolean headerRead = false; //if the connection header that
//follows version is read.
private SocketChannel channel;
private ByteBuffer data;
private ByteBuffer dataLengthBuffer;
private LinkedList<Call> responseQueue;
private long lastContact;
private int dataLength;
private Socket socket;
// Cache the remote host & port info so that even if the socket is
// disconnected, we can say where it used to connect to.
private String hostAddress;
private int remotePort;
private UserGroupInformation ticket = null;
public Connection(SelectionKey key, SocketChannel channel,
long lastContact) {
this.channel = channel;
this.lastContact = lastContact;
this.data = null;
this.dataLengthBuffer = ByteBuffer.allocate(4);
this.socket = channel.socket();
InetAddress addr = socket.getInetAddress();
if (addr == null) {
this.hostAddress = "*Unknown*";
} else {
this.hostAddress = addr.getHostAddress();
}
this.remotePort = socket.getPort();
this.responseQueue = new LinkedList<Call>();
if (socketSendBufferSize != 0) {
try {
socket.setSendBufferSize(socketSendBufferSize);
} catch (IOException e) {
LOG.warn("Connection: unable to set socket send buffer size to " +
socketSendBufferSize);
}
}
}
@Override
public String toString() {
return getHostAddress() + ":" + remotePort;
}
public String getHostAddress() {
return hostAddress;
}
public void setLastContact(long lastContact) {
this.lastContact = lastContact;
}
public long getLastContact() {
return lastContact;
}
private boolean timedOut(long currentTime) {
if (currentTime - lastContact > maxIdleTime)
return true;
return false;
}
public int readAndProcess() throws IOException, InterruptedException {
while (true) {
/* Read at most one RPC. If the header is not read completely yet
* then iterate until we read first RPC or until there is no data left.
*/
int count = -1;
if (dataLengthBuffer.remaining() > 0) {
count = channel.read(dataLengthBuffer);
if (count < 0 || dataLengthBuffer.remaining() > 0)
return count;
}
if (!versionRead) {
//Every connection is expected to send the header.
ByteBuffer versionBuffer = ByteBuffer.allocate(1);
count = channel.read(versionBuffer);
if (count <= 0) {
return count;
}
int version = versionBuffer.get(0);
dataLengthBuffer.flip();
if (!HEADER.equals(dataLengthBuffer) || version != CURRENT_VERSION) {
//Warning is ok since this is not supposed to happen.
LOG.warn("Incorrect header or version mismatch from " +
hostAddress + ":" + remotePort +
" got version " + version +
" expected version " + CURRENT_VERSION);
return -1;
}
dataLengthBuffer.clear();
versionRead = true;
continue;
}
if (data == null) {
dataLengthBuffer.flip();
dataLength = dataLengthBuffer.getInt();
data = ByteBuffer.allocate(dataLength);
}
count = channel.read(data);
if (data.remaining() == 0) {
dataLengthBuffer.clear();
data.flip();
if (headerRead) {
processData();
data = null;
return count;
} else {
processHeader();
headerRead = true;
data = null;
continue;
}
}
return count;
}
}
/// Reads the header following version
private void processHeader() throws IOException {
/* In the current version, it is just a ticket.
* Later we could introduce a "ConnectionHeader" class.
*/
DataInputStream in =
new DataInputStream(new ByteArrayInputStream(data.array()));
ticket = (UserGroupInformation) ObjectWritable.readObject(in, conf);
}
private void processData() throws IOException, InterruptedException {
DataInputStream dis =
new DataInputStream(new ByteArrayInputStream(data.array()));
int id = dis.readInt(); // try to read an id
if (LOG.isDebugEnabled())
LOG.debug(" got #" + id);
Writable param = (Writable)ReflectionUtils.newInstance(paramClass, conf); // read param
param.readFields(dis);
Call call = new Call(id, param, this);
synchronized (callQueue) {
if (callQueue.size() >= maxQueueSize) {
Call oldCall = callQueue.removeFirst();
LOG.warn("Call queue overflow discarding oldest call " + oldCall);
}
callQueue.addLast(call); // queue the call
callQueue.notify(); // wake up a waiting handler
}
}
private synchronized void close() throws IOException {
data = null;
dataLengthBuffer = null;
if (!channel.isOpen())
return;
try {socket.shutdownOutput();} catch(Exception e) {}
if (channel.isOpen()) {
try {channel.close();} catch(Exception e) {}
}
try {socket.close();} catch(Exception e) {}
}
}
/** Handles queued calls . */
private class Handler extends Thread {
public Handler(int instanceNumber) {
this.setDaemon(true);
this.setName("IPC Server handler "+ instanceNumber + " on " + port);
}
@Override
public void run() {
LOG.info(getName() + ": starting");
SERVER.set(Server.this);
ByteArrayOutputStream buf = new ByteArrayOutputStream(10240);
while (running) {
try {
Call call;
synchronized (callQueue) {
while (running && callQueue.size()==0) { // wait for a call
callQueue.wait(timeout);
}
if (!running) break;
call = callQueue.removeFirst(); // pop the queue
}
// throw the message away if it is too old
if (System.currentTimeMillis() - call.receivedTime >
maxCallStartAge) {
ReflectionUtils.logThreadInfo(LOG, "Discarding call " + call, 30);
int timeInQ = (int) (System.currentTimeMillis() - call.receivedTime);
LOG.warn(getName()+", call "+call
+": discarded for being too old (" +
timeInQ + ")");
rpcMetrics.rpcDiscardedOps.inc(timeInQ);
continue;
}
if (LOG.isDebugEnabled())
LOG.debug(getName() + ": has #" + call.id + " from " +
call.connection);
String errorClass = null;
String error = null;
Writable value = null;
CurCall.set(call);
try {
value = call(call.param, call.receivedTime); // make the call
} catch (Throwable e) {
LOG.info(getName()+", call "+call+": error: " + e, e);
errorClass = e.getClass().getName();
error = StringUtils.stringifyException(e);
}
CurCall.set(null);
buf.reset();
DataOutputStream out = new DataOutputStream(buf);
out.writeInt(call.id); // write call id
out.writeBoolean(error != null); // write error flag
if (error == null) {
value.write(out);
} else {
WritableUtils.writeString(out, errorClass);
WritableUtils.writeString(out, error);
}
call.setResponse(ByteBuffer.wrap(buf.toByteArray()));
responder.doRespond(call);
} catch (InterruptedException e) {
if (running) { // unexpected -- log it
LOG.info(getName() + " caught: " +
StringUtils.stringifyException(e));
}
} catch (Exception e) {
LOG.info(getName() + " caught: " +
StringUtils.stringifyException(e));
}
}
LOG.info(getName() + ": exiting");
}
}
protected Server(String bindAddress, int port, Class paramClass, int handlerCount, Configuration conf)
throws IOException
{
this(bindAddress, port, paramClass, handlerCount, conf, Integer.toString(port));
}
/** Constructs a server listening on the named port and address. Parameters passed must
* be of the named class. The <code>handlerCount</handlerCount> determines
* the number of handler threads that will be used to process calls.
*
*/
protected Server(String bindAddress, int port, Class paramClass, int handlerCount, Configuration conf,
String serverName)
throws IOException {
this.bindAddress = bindAddress;
this.conf = conf;
this.port = port;
this.paramClass = paramClass;
this.handlerCount = handlerCount;
this.timeout = conf.getInt("ipc.client.timeout", 10000);
this.socketSendBufferSize = 0;
maxCallStartAge = (long) (timeout * MAX_CALL_QUEUE_TIME);
maxQueueSize = handlerCount * MAX_QUEUE_SIZE_PER_HANDLER;
this.maxIdleTime = conf.getInt("ipc.client.maxidletime", 120000);
this.maxConnectionsToNuke = conf.getInt("ipc.client.kill.max", 10);
this.thresholdIdleConnections = conf.getInt("ipc.client.idlethreshold", 4000);
// Start the listener here and let it bind to the port
listener = new Listener();
this.port = listener.getAddress().getPort();
this.rpcMetrics = new RpcMetrics(serverName,
Integer.toString(this.port), this);
// Create the responder here
responder = new Responder();
}
private void closeConnection(Connection connection) {
synchronized (connectionList) {
if (connectionList.remove(connection))
numConnections--;
}
try {
connection.close();
} catch (IOException e) {
}
}
/** Sets the timeout used for network i/o. */
public void setTimeout(int timeout) { this.timeout = timeout; }
/** Sets the socket buffer size used for responding to RPCs */
public void setSocketSendBufSize(int size) { this.socketSendBufferSize = size; }
/** Starts the service. Must be called before any calls will be handled. */
public synchronized void start() throws IOException {
responder.start();
listener.start();
handlers = new Handler[handlerCount];
for (int i = 0; i < handlerCount; i++) {
handlers[i] = new Handler(i);
handlers[i].start();
}
}
/** Stops the service. No new calls will be handled after this is called. */
public synchronized void stop() {
LOG.info("Stopping server on " + port);
running = false;
if (handlers != null) {
for (int i = 0; i < handlerCount; i++) {
if (handlers[i] != null) {
handlers[i].interrupt();
}
}
}
listener.interrupt();
listener.doStop();
responder.interrupt();
notifyAll();
if (this.rpcMetrics != null) {
this.rpcMetrics.shutdown();
}
}
/** Wait for the server to be stopped.
* Does not wait for all subthreads to finish.
* See {@link #stop()}.
*/
public synchronized void join() throws InterruptedException {
while (running) {
wait();
}
}
/**
* Return the socket (ip+port) on which the RPC server is listening to.
* @return the socket (ip+port) on which the RPC server is listening to.
*/
public synchronized InetSocketAddress getListenerAddress() {
return listener.getAddress();
}
/** Called for each call. */
public abstract Writable call(Writable param, long receiveTime)
throws IOException;
/**
* The number of open RPC conections
* @return the number of open rpc connections
*/
public int getNumOpenConnections() {
return numConnections;
}
/**
* The number of rpc calls in the queue.
* @return The number of rpc calls in the queue.
*/
public int getCallQueueLen() {
return callQueue.size();
}
}
| Fix a bug in the IPC responder thread while cancelling keys from the
socket selector.
git-svn-id: 5be3658b1da2303116c04834c161daea58df9cc4@627254 13f79535-47bb-0310-9956-ffa450edef68
| src/java/org/apache/hadoop/ipc/Server.java | Fix a bug in the IPC responder thread while cancelling keys from the socket selector. | |
Java | apache-2.0 | bce5cb1d30c8aabc503cfc7468934ce143cd30d8 | 0 | Wisser/Jailer,Wisser/Jailer,Wisser/Jailer | /*
* Copyright 2007 - 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.jailer.ui.databrowser;
import java.awt.BasicStroke;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.math.BigDecimal;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.PriorityBlockingQueue;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.InputMap;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.ListCellRenderer;
import javax.swing.RowSorter;
import javax.swing.RowSorter.SortKey;
import javax.swing.SortOrder;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.event.RowSorterEvent;
import javax.swing.event.RowSorterListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import net.coderazzi.filters.gui.AutoChoices;
import net.coderazzi.filters.gui.TableFilterHeader;
import net.sf.jailer.ExecutionContext;
import net.sf.jailer.database.InlineViewStyle;
import net.sf.jailer.database.Session;
import net.sf.jailer.database.Session.AbstractResultSetReader;
import net.sf.jailer.database.SqlException;
import net.sf.jailer.datamodel.Association;
import net.sf.jailer.datamodel.Cardinality;
import net.sf.jailer.datamodel.Column;
import net.sf.jailer.datamodel.DataModel;
import net.sf.jailer.datamodel.PrimaryKey;
import net.sf.jailer.datamodel.RestrictionDefinition;
import net.sf.jailer.datamodel.RowIdSupport;
import net.sf.jailer.datamodel.Table;
import net.sf.jailer.extractionmodel.ExtractionModel;
import net.sf.jailer.modelbuilder.JDBCMetaDataBasedModelElementFinder;
import net.sf.jailer.modelbuilder.MemorizedResultSet.MemorizedResultSetMetaData;
import net.sf.jailer.subsetting.ScriptFormat;
import net.sf.jailer.ui.ConditionEditor;
import net.sf.jailer.ui.DataModelManager;
import net.sf.jailer.ui.DbConnectionDialog;
import net.sf.jailer.ui.Environment;
import net.sf.jailer.ui.ExtractionModelFrame;
import net.sf.jailer.ui.JComboBox;
import net.sf.jailer.ui.QueryBuilderDialog;
import net.sf.jailer.ui.QueryBuilderDialog.Relationship;
import net.sf.jailer.ui.UIUtil;
import net.sf.jailer.ui.databrowser.Desktop.RowBrowser;
import net.sf.jailer.ui.databrowser.RowCounter.RowCount;
import net.sf.jailer.ui.databrowser.metadata.MetaDataSource;
import net.sf.jailer.ui.databrowser.sqlconsole.SQLConsole;
import net.sf.jailer.ui.scrollmenu.JScrollC2Menu;
import net.sf.jailer.ui.scrollmenu.JScrollMenu;
import net.sf.jailer.ui.scrollmenu.JScrollPopupMenu;
import net.sf.jailer.util.CancellationException;
import net.sf.jailer.util.CancellationHandler;
import net.sf.jailer.util.CellContentConverter;
import net.sf.jailer.util.CellContentConverter.PObjectWrapper;
import net.sf.jailer.util.Pair;
import net.sf.jailer.util.Quoting;
import net.sf.jailer.util.SqlUtil;
/**
* Content UI of a row browser frame (as {@link JInternalFrame}s). Contains a
* table for rendering rows.
*
* @author Ralf Wisser
*/
@SuppressWarnings("serial")
public abstract class BrowserContentPane extends javax.swing.JPanel {
/**
* Concurrently loads rows.
*/
public class LoadJob implements RunnableWithPriority {
private List<Row> rows = Collections.synchronizedList(new ArrayList<Row>());
private Throwable exception;
private boolean isCanceled;
private final int limit;
private final String andCond;
private final boolean selectDistinct;
private boolean finished;
private final ResultSet inputResultSet;
private final RowBrowser parentBrowser;
public boolean closureLimitExceeded = false;
public LoadJob(int limit, String andCond, RowBrowser parentBrowser, boolean selectDistinct) {
this.andCond = andCond;
this.selectDistinct = selectDistinct;
this.inputResultSet = null;
synchronized (this) {
this.limit = limit;
finished = false;
isCanceled = false;
this.parentBrowser = parentBrowser;
}
}
public LoadJob(ResultSet inputResultSet, int limit) {
this.andCond = "";
this.selectDistinct = false;
this.inputResultSet = inputResultSet;
synchronized (this) {
this.limit = limit;
finished = false;
isCanceled = false;
parentBrowser = null;
}
}
@Override
public void run() {
int l;
synchronized (this) {
l = limit;
if (isCanceled) {
CancellationHandler.reset(this);
return;
}
}
rowCountCache.clear();
try {
reloadRows(inputResultSet, andCond, rows, this, l + 1, selectDistinct);
CancellationHandler.checkForCancellation(this);
synchronized (this) {
finished = true;
}
} catch (SQLException e) {
synchronized (rows) {
exception = e;
}
} catch (CancellationException e) {
Session._log.info("cancelled");
CancellationHandler.reset(this);
return;
} catch (Throwable e) {
synchronized (rows) {
exception = e;
}
}
CancellationHandler.reset(this);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Throwable e;
int l;
boolean limitExceeded = false;
synchronized (rows) {
e = exception;
l = limit;
while (rows.size() > limit) {
limitExceeded = true;
rows.remove(rows.size() - 1);
}
isCanceled = true; // done
sortRowsByParentViewIndex();
}
if (e != null) {
updateMode("error", null);
unhide();
UIUtil.showException(BrowserContentPane.this, "Error", e);
} else {
Set<String> prevIDs = new TreeSet<String>();
long prevHash = 0;
if (BrowserContentPane.this.rows != null) {
for (Row r: BrowserContentPane.this.rows) {
prevIDs.add(r.nonEmptyRowId);
try {
for (Object v: r.values) {
if (v != null) {
prevHash = 2 * prevHash + v.hashCode();
}
}
} catch (RuntimeException e1) {
// ignore
}
}
}
onContentChange(new ArrayList<Row>(), false);
BrowserContentPane.this.rows.clear();
BrowserContentPane.this.rows.addAll(rows);
updateTableModel(l, limitExceeded, closureLimitExceeded);
Set<String> currentIDs = new TreeSet<String>();
long currentHash = 0;
if (rows != null) {
for (Row r: rows) {
currentIDs.add(r.nonEmptyRowId);
try {
for (Object v: r.values) {
if (v != null) {
currentHash = 2 * currentHash + v.hashCode();
}
}
} catch (RuntimeException e1) {
// ignore
}
}
}
setPendingState(false, true);
onContentChange(rows, true); // rows.isEmpty() || currentHash != prevHash || rows.size() != prevSize || !prevIDs.equals(currentIDs) || rows.size() != currentIDs.size());
updateMode("table", null);
updateWhereField();
if (reloadAction != null) {
reloadAction.run();
}
}
}
});
}
protected void sortRowsByParentViewIndex() {
if (parentBrowser != null && parentBrowser.browserContentPane != null && parentBrowser.browserContentPane.rowsTable != null) {
final RowSorter<? extends TableModel> parentSorter = parentBrowser.browserContentPane.rowsTable.getRowSorter();
Collections.sort(rows, new Comparator<Row>() {
@Override
public int compare(Row a, Row b) {
int avi = a.getParentModelIndex();
if (avi >= 0 && avi < parentSorter.getModelRowCount()) {
avi = parentSorter.convertRowIndexToView(avi);
}
int bvi = b.getParentModelIndex();
if (bvi >= 0 && avi < parentSorter.getModelRowCount()) {
bvi = parentSorter.convertRowIndexToView(bvi);
}
return avi - bvi;
}
});
}
}
public synchronized void cancel() {
if (isCanceled) {
return;
}
isCanceled = true;
if (finished) {
return;
}
CancellationHandler.cancel(this);
}
public synchronized void checkCancellation() {
CancellationHandler.checkForCancellation(this);
}
@Override
public int getPriority() {
return 100;
}
}
private Runnable reloadAction;
public void setOnReloadAction(final Runnable runnable) {
if (reloadAction == null) {
reloadAction = runnable;
} else {
final Runnable prevReloadAction = reloadAction;
reloadAction = new Runnable() {
@Override
public void run() {
prevReloadAction.run();
runnable.run();
}
};
}
}
/**
* Current LoadJob.
*/
private LoadJob currentLoadJob;
/**
* Table to read rows from.
*/
Table table;
/**
* Parent row, or <code>null</code>.
*/
Row parentRow;
/**
* The data model.
*/
private final DataModel dataModel;
/**
* The execution context.
*/
protected final ExecutionContext executionContext;
/**
* {@link RowIdSupport} for data model.
*/
private final RowIdSupport rowIdSupport;
/**
* {@link Association} with parent row, or <code>null</code>.
*/
Association association;
/**
* Rows to render.
*/
public List<Row> rows = new ArrayList<Row>();
/**
* For in-place editing.
*/
private BrowserContentCellEditor browserContentCellEditor = new BrowserContentCellEditor(new int[0]);
/**
* Cache for association row count.
*/
private final Map<Pair<String, Association>, Pair<RowCount, Long>> rowCountCache =
Collections.synchronizedMap(new HashMap<Pair<String,Association>, Pair<RowCount, Long>>());
private final long MAX_ROWCOUNTCACHE_RETENTION_TIME = 5 * 60 * 1000L;
/**
* Number of non-distinct rows;
*/
private int noNonDistinctRows;
/**
* Number of distinct rows;
*/
private int noDistinctRows;
/**
* Indexes of highlighted rows.
*/
Set<Integer> highlightedRows = new HashSet<Integer>();
/**
* Indexes of primary key columns.
*/
private Set<Integer> pkColumns = new HashSet<Integer>();
/**
* Indexes of foreign key columns.
*/
private Set<Integer> fkColumns = new HashSet<Integer>();
/**
* Edit mode?
*/
private boolean isEditMode = false;
/**
* DB session.
*/
Session session;
private int currentRowSelection = -1;
private List<Row> parentRows;
private DetailsView singleRowDetailsView;
private MouseListener rowTableListener;
private int initialRowHeight;
public static class RowsClosure {
Set<Pair<BrowserContentPane, Row>> currentClosure = Collections.synchronizedSet(new HashSet<Pair<BrowserContentPane, Row>>());
Set<Pair<BrowserContentPane, String>> currentClosureRowIDs = new HashSet<Pair<BrowserContentPane, String>>();
String currentClosureRootID;
Set<BrowserContentPane> parentPath = new HashSet<BrowserContentPane>();
};
private final RowsClosure rowsClosure;
private boolean suppressReload;
/**
* Alias for row number column.
*/
private static final String ROWNUMBERALIAS = "RN";
protected static final String UNKNOWN = "- unknown column -";
protected static final int MAXLOBLENGTH = 2000;
private static final KeyStroke KS_COPY_TO_CLIPBOARD = KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_DOWN_MASK);
private static final KeyStroke KS_SQLCONSOLE = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.CTRL_DOWN_MASK);
private static final KeyStroke KS_QUERYBUILDER = KeyStroke.getKeyStroke(KeyEvent.VK_Q, InputEvent.CTRL_DOWN_MASK);
private static final KeyStroke KS_FILTER = KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.CTRL_DOWN_MASK);
private static final KeyStroke KS_EDIT = KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.CTRL_DOWN_MASK);
private static final KeyStroke KS_DETAILS = KeyStroke.getKeyStroke(KeyEvent.VK_D, InputEvent.CTRL_DOWN_MASK);
/**
* And-condition-combobox model.
*/
private final DefaultComboBoxModel<Object> andCondModel = new DefaultComboBoxModel<Object>();
private boolean isTableFilterEnabled = false;
public void setTableFilterEnabled(boolean isTableFilterEnabled) {
this.isTableFilterEnabled = isTableFilterEnabled;
}
static class SqlStatementTable extends Table {
public SqlStatementTable(String name, PrimaryKey primaryKey, boolean defaultUpsert) {
super(name, primaryKey, defaultUpsert, false);
}
}
/**
* Constructor.
*
* @param dataModel
* the data model
* @param table
* to read rows from. Opens SQL browser if table is <code>null</code>.
* @param condition
* initial condition
* @param session
* DB session
* @param parentRow
* parent row
* @param parentRows
* all parent rows, if there are more than 1
* @param association
* {@link Association} with parent row
*/
public BrowserContentPane(final DataModel dataModel, final Table table, String condition, Session session, Row parentRow, List<Row> parentRows,
final Association association, final Frame parentFrame, RowsClosure rowsClosure,
Boolean selectDistinct, boolean reload, ExecutionContext executionContext) {
this.table = table;
this.session = session;
this.dataModel = dataModel;
this.rowIdSupport = new RowIdSupport(dataModel, session.dbms, executionContext);
this.parentRow = parentRow;
this.parentRows = parentRows;
this.association = association;
this.rowsClosure = rowsClosure;
this.executionContext = executionContext;
rowIdSupport.setUseRowIdsOnlyForTablesWithoutPK(true);
suppressReload = true;
if (table == null) {
this.table = new SqlStatementTable(null, null, false);
}
initComponents();
loadingCauseLabel.setVisible(false);
andCondition = new JComboBox();
andCondition.setEditable(true);
GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
jPanel7.add(andCondition, gridBagConstraints);
setPendingState(false, false);
dropA.setText(null);
dropA.setIcon(dropDownIcon);
sqlLabel1.setIcon(dropDownIcon);
dropA.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mousePressed(java.awt.event.MouseEvent evt) {
openColumnDropDownBox(dropA, "A", table);
}
@Override
public void mouseEntered(java.awt.event.MouseEvent evt) {
dropA.setEnabled(false);
}
@Override
public void mouseExited(java.awt.event.MouseEvent evt) {
dropA.setEnabled(true);
}
});
if (association != null) {
dropB.setText(null);
dropB.setIcon(dropDownIcon);
dropB.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mousePressed(java.awt.event.MouseEvent evt) {
openColumnDropDownBox(dropB, "B", association.source);
}
@Override
public void mouseEntered(java.awt.event.MouseEvent evt) {
dropB.setEnabled(false);
}
@Override
public void mouseExited(java.awt.event.MouseEvent evt) {
dropB.setEnabled(true);
}
});
}
final ListCellRenderer acRenderer = andCondition.getRenderer();
andCondition.setRenderer(new ListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
boolean cellHasFocus) {
Component render = acRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (render instanceof JLabel) {
if (value != null && value.toString().trim().length() > 0) {
String tooltip = ConditionEditor.toMultiLine(value.toString());
((JLabel) render).setToolTipText(UIUtil.toHTML(tooltip, 200));
} else {
((JLabel) render).setToolTipText(null);
}
}
return render;
}
});
if (andCondition.getEditor() != null && (andCondition.getEditor().getEditorComponent() instanceof JTextField)) {
JTextField f = ((JTextField) andCondition.getEditor().getEditorComponent());
f.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
updateTooltip();
}
@Override
public void insertUpdate(DocumentEvent e) {
updateTooltip();
}
@Override
public void changedUpdate(DocumentEvent e) {
updateTooltip();
}
private void updateTooltip() {
if (andCondition.getEditor() != null && (andCondition.getEditor().getEditorComponent() instanceof JTextField)) {
JTextField f = ((JTextField) andCondition.getEditor().getEditorComponent());
String value = f.getText();
if (value != null && value.toString().trim().length() > 0) {
String tooltip = ConditionEditor.toMultiLine(value.toString());
andCondition.setToolTipText(UIUtil.toHTML(tooltip, 200));
} else {
andCondition.setToolTipText(null);
}
}
};
});
}
andCondModel.addElement("");
andCondition.setModel(andCondModel);
andCondition.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (!suppessReloadOnAndConditionAction) {
if (e.getStateChange() == ItemEvent.SELECTED) {
historizeAndCondition(e.getItem());
reloadRows();
}
}
}
});
initialRowHeight = rowsTable.getRowHeight();
rowsTable = new JTable() {
private int x[] = new int[2];
private int y[] = new int[2];
private Color color = new Color(0, 0, 200);
@Override
public void paint(Graphics graphics) {
super.paint(graphics);
if (!(graphics instanceof Graphics2D)) {
return;
}
if (BrowserContentPane.this.association != null && BrowserContentPane.this.association.isInsertDestinationBeforeSource()) {
return;
}
int maxI = Math.min(rowsTable.getRowCount(), rows.size());
RowSorter<? extends TableModel> sorter = getRowSorter();
if (sorter != null) {
maxI = sorter.getViewRowCount();
}
int lastPMIndex = -1;
for (int i = 0; i < maxI; ++i) {
int mi = sorter == null? i : sorter.convertRowIndexToModel(i);
if (mi >= rows.size()) {
continue;
}
if (rows.get(mi).getParentModelIndex() != lastPMIndex) {
lastPMIndex = rows.get(mi).getParentModelIndex();
int vi = i;
Graphics2D g2d = (Graphics2D) graphics;
g2d.setColor(color);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setStroke(new BasicStroke(1));
Rectangle r = rowsTable.getCellRect(vi, 0, false);
x[0] = (int) r.getMinX();
y[0] = (int) r.getMinY();
r = rowsTable.getCellRect(vi, rowsTable.getColumnCount() - 1, false);
x[1] = (int) r.getMaxX();
y[1] = (int) r.getMinY();
g2d.drawPolyline(x, y, 2);
}
}
}
};
InputMap im = rowsTable.getInputMap();
Object key = "copyClipboard";
im.put(KS_COPY_TO_CLIPBOARD, key);
ActionMap am = rowsTable.getActionMap();
Action a = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
UIUtil.copyToClipboard(rowsTable, true);
}
};
am.put(key, a);
registerAccelerator(KS_SQLCONSOLE, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
rowsTable.grabFocus();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
openQueryBuilder(true);
}
});
}
});
registerAccelerator(KS_QUERYBUILDER, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
rowsTable.grabFocus();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
openQueryBuilder(false);
}
});
}
});
registerAccelerator(KS_FILTER, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
isTableFilterEnabled = !isTableFilterEnabled;
updateTableModel();
}
});
registerAccelerator(KS_EDIT, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
setEditMode(!isEditMode);
updateTableModel();
}
});
registerAccelerator(KS_DETAILS, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
Point loc = new Point(18, 16);
SwingUtilities.convertPointToScreen(loc, rowsTable);
openDetails(loc.x, loc.y);
}
});
rowsTable.setAutoCreateRowSorter(true);
rowsTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
rowsTableScrollPane.setViewportView(rowsTable);
rowsTable.setAutoscrolls(false);
setAndCondition(ConditionEditor.toSingleLine(condition), true);
from.setText(table == null? "" : this.dataModel.getDisplayName(table));
adjustGui();
rowsTable.setShowGrid(false);
final TableCellRenderer defaultTableCellRenderer = rowsTable.getDefaultRenderer(String.class);
rowsTable.setDefaultRenderer(Object.class, new TableCellRenderer() {
final Color BG1 = new Color(255, 255, 255);
final Color BG2 = new Color(242, 255, 242);
final Color BG1_EM = new Color(255, 255, 236);
final Color BG2_EM = new Color(230, 255, 236);
final Color BG3 = new Color(194, 228, 255);
final Color BG3_2 = new Color(184, 220, 255);
final Color BG4 = new Color(30, 200, 255);
final Color FG1 = new Color(155, 0, 0);
final Color FG2 = new Color(0, 0, 255);
final Font font = new JLabel().getFont();
final Font nonbold = new Font(font.getName(), font.getStyle() & ~Font.BOLD, font.getSize());
final Font bold = new Font(nonbold.getName(), nonbold.getStyle() | Font.BOLD, nonbold.getSize());
final Font italic = new Font(nonbold.getName(), nonbold.getStyle() | Font.ITALIC, nonbold.getSize());
final Font italicBold = new Font(nonbold.getName(), nonbold.getStyle() | Font.ITALIC | Font.BOLD, nonbold.getSize());
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
boolean cellSelected = isSelected;
if (table.getSelectedColumnCount() <= 1 && table.getSelectedRowCount() <= 1) {
if (table == rowsTable) {
cellSelected = false;
}
}
isSelected = currentRowSelection == row || currentRowSelection == -2;
if (table != rowsTable) {
isSelected = false;
if (table.getSelectedRows().length <= 1 && table.getSelectedColumns().length <= 1) {
for (int sr: table.getSelectedRows()) {
if (sr == column) {
isSelected = true;
break;
}
}
}
}
Component render = defaultTableCellRenderer.getTableCellRendererComponent(rowsTable, value, isSelected, false, row, column);
final RowSorter<?> rowSorter = rowsTable.getRowSorter();
if (rowSorter.getViewRowCount() == 0 && table == rowsTable) {
return render;
}
boolean renderRowAsPK = false;
if (render instanceof JLabel) {
Row r = null;
int rowIndex = row;
((JLabel) render).setIcon(null);
if (row < rowSorter.getViewRowCount()) {
rowIndex = rowSorter.convertRowIndexToModel(row);
if (rowIndex < rows.size()) {
r = rows.get(rowIndex);
if (r != null) {
renderRowAsPK = renderRowAsPK(r);
Object cellContent = r.values.length > column? r.values[column] : null;
if (cellContent instanceof UIUtil.IconWithText) {
((JLabel) render).setIcon(((UIUtil.IconWithText) cellContent).icon);
((JLabel) render).setText(((UIUtil.IconWithText) cellContent).text);
}
}
}
}
((JLabel) render).setBorder(cellSelected? BorderFactory.createEtchedBorder() : null);
int convertedColumnIndex = rowsTable.convertColumnIndexToModel(column);
if (!isSelected && (table == rowsTable || !cellSelected)) {
if (BrowserContentPane.this.getQueryBuilderDialog() != null && // SQL Console
BrowserContentPane.this.rowsClosure.currentClosureRowIDs != null && row < rows.size() && BrowserContentPane.this.rowsClosure.currentClosureRowIDs.contains(new Pair<BrowserContentPane, String>(BrowserContentPane.this, rows.get(rowSorter.convertRowIndexToModel(row)).nonEmptyRowId))) {
((JLabel) render).setBackground((row % 2) == 0? BG3 : BG3_2);
if (BrowserContentPane.this.rowsClosure.currentClosureRootID != null
&& !BrowserContentPane.this.rowsClosure.currentClosureRootID.isEmpty()
&& BrowserContentPane.this.rowsClosure.currentClosureRootID.equals(rows.get(rowSorter.convertRowIndexToModel(row)).nonEmptyRowId)) {
((JLabel) render).setBackground(BG4);
}
} else {
Table type = getResultSetTypeForColumn(convertedColumnIndex);
if (isEditMode && r != null && (r.rowId != null && !r.rowId.isEmpty()) && browserContentCellEditor.isEditable(type, rowIndex, convertedColumnIndex, r.values[convertedColumnIndex])
&& isPKComplete(type, r) && !rowIdSupport.getPrimaryKey(type, BrowserContentPane.this.session).getColumns().isEmpty()) {
((JLabel) render).setBackground((row % 2 == 0) ? BG1_EM : BG2_EM);
} else {
((JLabel) render).setBackground((row % 2 == 0) ? BG1 : BG2);
}
}
} else {
((JLabel) render).setBackground(currentRowSelection == row? BG4.brighter() : BG4);
}
((JLabel) render).setForeground(
renderRowAsPK || pkColumns.contains(convertedColumnIndex) ? FG1 :
fkColumns.contains(convertedColumnIndex) ? FG2 :
Color.BLACK);
boolean isNull = false;
if (((JLabel) render).getText() == UIUtil.NULL || ((JLabel) render).getText() == UNKNOWN) {
((JLabel) render).setForeground(Color.gray);
((JLabel) render).setFont(italic);
isNull = true;
}
try {
((JLabel) render).setToolTipText(null);
if (isNull) {
((JLabel) render).setFont(highlightedRows.contains(rowSorter.convertRowIndexToModel(row)) ? italicBold : italic);
} else {
((JLabel) render).setFont(highlightedRows.contains(rowSorter.convertRowIndexToModel(row)) ? bold : nonbold);
String text = ((JLabel) render).getText();
if (text.indexOf('\n') >= 0) {
((JLabel) render).setToolTipText(UIUtil.toHTML(text, 200));
} else if (text.length() > 20) {
((JLabel) render).setToolTipText(text);
}
}
} catch (Exception e) {
// ignore
}
}
// indent 1. column
if (render instanceof JLabel) {
((JLabel) render).setText(" " + ((JLabel) render).getText());
}
return render;
}
});
rowsTable.setRowSelectionAllowed(true);
rowsTable.setColumnSelectionAllowed(true);
rowsTable.setCellSelectionEnabled(true);
rowsTable.setEnabled(true);
rowsTableScrollPane.getVerticalScrollBar().setUnitIncrement(32);
singleRowViewScrollPane.getVerticalScrollBar().setUnitIncrement(32);
rowTableListener = new MouseListener() {
private JPopupMenu lastMenu;
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
int ri;
JComponent source = (JComponent) e.getSource();
if (source == rowsTable) {
ri = rowsTable.rowAtPoint(e.getPoint());
} else {
ri = 0;
}
if (ri >= 0 && !rows.isEmpty() && rowsTable.getRowSorter().getViewRowCount() > 0) {
int i = 0;
if (source == rowsTable) {
i = rowsTable.getRowSorter().convertRowIndexToModel(ri);
} else if (source == rowsTableScrollPane) {
if (e.getButton() == MouseEvent.BUTTON1 && (e.getClickCount() <= 1 || getQueryBuilderDialog() == null /* SQL Console */)) {
return;
}
ri = rowsTable.getRowSorter().getViewRowCount() - 1;
i = rowsTable.getRowSorter().convertRowIndexToModel(ri);
}
Row row = rows.get(i);
if (lastMenu == null || !lastMenu.isVisible()) {
currentRowSelection = ri;
onRedraw();
int x, y;
if (source != rowsTable) {
x = e.getX();
y = e.getY();
} else {
Rectangle r = rowsTable.getCellRect(ri, 0, false);
x = Math.max(e.getPoint().x, (int) r.getMinX());
y = (int) r.getMaxY() - 2;
}
Point p = SwingUtilities.convertPoint(source, x, y, null);
if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() > 1) {
openDetailsView(i, p.x + getOwner().getX(), p.y + getOwner().getY());
} else if (e.getButton() != MouseEvent.BUTTON1) {
JPopupMenu popup;
popup = createPopupMenu(row, i, p.x + getOwner().getX(), p.y + getOwner().getY(), rows.size() == 1);
if (popup != null) {
UIUtil.showPopup(source, x, y, popup);
popup.addPropertyChangeListener("visible", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (Boolean.FALSE.equals(evt.getNewValue())) {
currentRowSelection = -1;
onRedraw();
}
}
});
}
lastMenu = popup;
} else {
setCurrentRowSelectionAndReloadChildrenIfLimitIsExceeded(ri);
if (getQueryBuilderDialog() != null) { // !SQL Console
setCurrentRowSelectionAndReloadChildrenIfLimitIsExceeded(-1);
}
}
}
}
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseClicked(MouseEvent e) {
}
};
rowsTable.addMouseListener(rowTableListener);
rowsTableScrollPane.addMouseListener(rowTableListener);
singleRowViewScrollContentPanel.addMouseListener(rowTableListener);
openEditorButton.setIcon(UIUtil.scaleIcon(this, conditionEditorIcon));
openEditorButton.setText(null);
openEditorButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final Point pos = new Point(openEditorButton.getX(), openEditorButton.getY() + openEditorButton.getHeight());
SwingUtilities.convertPointToScreen(pos, openEditorButton.getParent());
loadButton.grabFocus();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (andConditionEditor == null) {
andConditionEditor = new ConditionEditor(parentFrame, null, dataModel);
}
andConditionEditor.setLocationAndFit(pos);
String cond = andConditionEditor.edit(getAndConditionText(), "Table", "A", table, null, null, null, false, true);
if (cond != null) {
if (!getAndConditionText().equals(ConditionEditor.toSingleLine(cond))) {
setAndCondition(ConditionEditor.toSingleLine(cond), true);
loadButton.grabFocus();
reloadRows();
}
}
openEditorLabel.setIcon(conditionEditorSelectedIcon);
}
});
}
});
relatedRowsLabel.setIcon(UIUtil.scaleIcon(this, relatedRowsIcon));
relatedRowsLabel.setFont(relatedRowsLabel.getFont().deriveFont(relatedRowsLabel.getFont().getSize() * 1.1f));
if (createPopupMenu(null, -1, 0, 0, false).getComponentCount() == 0) {
relatedRowsLabel.setEnabled(false);
} else {
relatedRowsPanel.addMouseListener(new java.awt.event.MouseAdapter() {
private JPopupMenu popup;
private boolean in = false;
@Override
public void mousePressed(MouseEvent e) {
loadButton.grabFocus();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
popup = createPopupMenu(null, -1, 0, 0, false);
setCurrentRowSelectionAndReloadChildrenIfLimitIsExceeded(-2);
popup.addPropertyChangeListener("visible", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (Boolean.FALSE.equals(evt.getNewValue())) {
popup = null;
updateBorder();
setCurrentRowSelectionAndReloadChildrenIfLimitIsExceeded(-1);
}
}
});
UIUtil.showPopup(relatedRowsPanel, 0, relatedRowsPanel.getHeight(), popup);
}
});
}
@Override
public void mouseEntered(java.awt.event.MouseEvent evt) {
in = true;
updateBorder();
}
@Override
public void mouseExited(java.awt.event.MouseEvent evt) {
in = false;
updateBorder();
}
private void updateBorder() {
relatedRowsPanel.setBorder(new javax.swing.border.SoftBevelBorder((in || popup != null) ? javax.swing.border.BevelBorder.LOWERED
: javax.swing.border.BevelBorder.RAISED));
}
});
}
sqlPanel.addMouseListener(new java.awt.event.MouseAdapter() {
private JPopupMenu popup;
private boolean in = false;
@Override
public void mousePressed(MouseEvent e) {
loadButton.grabFocus();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Point loc = sqlPanel.getLocationOnScreen();
popup = createSqlPopupMenu(BrowserContentPane.this.parentRow, 0, (int) loc.getX(), (int) loc.getY(), false, BrowserContentPane.this);
setCurrentRowSelectionAndReloadChildrenIfLimitIsExceeded(-2);
popup.addPropertyChangeListener("visible", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (Boolean.FALSE.equals(evt.getNewValue())) {
popup = null;
updateBorder();
setCurrentRowSelectionAndReloadChildrenIfLimitIsExceeded(-1);
}
}
});
UIUtil.showPopup(sqlPanel, 0, sqlPanel.getHeight(), popup);
}
});
}
@Override
public void mouseEntered(java.awt.event.MouseEvent evt) {
in = true;
updateBorder();
}
@Override
public void mouseExited(java.awt.event.MouseEvent evt) {
in = false;
updateBorder();
}
private void updateBorder() {
sqlPanel.setBorder(new javax.swing.border.SoftBevelBorder((in || popup != null) ? javax.swing.border.BevelBorder.LOWERED
: javax.swing.border.BevelBorder.RAISED));
}
});
if (selectDistinct != null) {
selectDistinctCheckBox.setSelected(selectDistinct);
}
updateTableModel(0, false, false);
suppressReload = false;
if (reload) {
reloadRows();
}
}
private void registerAccelerator(KeyStroke ks, AbstractAction a) {
registerAccelerator(ks, a, this);
registerAccelerator(ks, a, rowsTable);
registerAccelerator(ks, a, loadButton);
registerAccelerator(ks, a, sqlLabel1);
registerAccelerator(ks, a, relatedRowsLabel);
registerAccelerator(ks, a, andCondition);
Component editor = andCondition.getEditor().getEditorComponent();
if (editor instanceof JComponent) {
registerAccelerator(ks, a, (JComponent) editor);
}
}
private void registerAccelerator(KeyStroke ks, AbstractAction a, JComponent comp) {
InputMap im = comp.getInputMap();
im.put(ks, a);
ActionMap am = comp.getActionMap();
am.put(a, a);
}
protected abstract boolean renderRowAsPK(Row theRow);
boolean isPending = false;
void setPendingState(boolean pending, boolean propagate) {
isPending = pending;
((CardLayout) pendingNonpendingPanel.getLayout()).show(pendingNonpendingPanel, "nonpending");
if (pending) {
updateMode("pending", null);
}
if (propagate) {
for (RowBrowser child: getChildBrowsers()) {
child.browserContentPane.setPendingState(pending, propagate);
}
}
}
protected void historizeAndCondition(Object item) {
if (item == null) {
return;
}
for (int i = 0; i < andCondModel.getSize(); ++i) {
if (item.equals(andCondModel.getElementAt(i))) {
return;
}
}
andCondModel.insertElementAt(item, 1);
}
private boolean suppessReloadOnAndConditionAction = false;
void setAndCondition(String cond, boolean historize) {
try {
suppessReloadOnAndConditionAction = true;
andCondition.setSelectedItem(cond);
if (historize) {
historizeAndCondition(cond);
}
} finally {
suppessReloadOnAndConditionAction = false;
}
}
String getAndConditionText() {
Object sel = andCondition.getSelectedItem();
if (sel == null) {
return "";
}
return sel.toString().trim();
}
private void adjustGui() {
if (this.association == null) {
joinPanel.setVisible(false);
onPanel.setVisible(false);
jLabel1.setText(" ");
jLabel4.setText(" ");
jLabel6.setVisible(false);
dropB.setVisible(false);
andLabel.setText(" Where ");
java.awt.GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 8;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridheight = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
} else {
join.setText(this.dataModel.getDisplayName(this.association.source));
on.setText(!this.association.reversed ? SqlUtil.reversRestrictionCondition(this.association.getUnrestrictedJoinCondition()) : this.association
.getUnrestrictedJoinCondition());
updateWhereField();
join.setToolTipText(join.getText());
on.setToolTipText(on.getText());
}
}
private class AllNonEmptyItem extends JMenuItem {
int todo;
int done;
private List<ActionListener> todoList = new ArrayList<ActionListener>();
private final String initText = "Counting rows... ";
AllNonEmptyItem() {
setEnabled(false);
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Component parent = SwingUtilities.getWindowAncestor(BrowserContentPane.this);
if (parent == null) {
parent = BrowserContentPane.this;
}
UIUtil.setWaitCursor(parent);
try {
Desktop.noArrangeLayoutOnNewTableBrowser = true;
Desktop.noArrangeLayoutOnNewTableBrowserWithAnchor = todoList.size() > 1;
Desktop.resetLastArrangeLayoutOnNewTableBrowser();
for (int i = 0; i < todoList.size(); ++i) {
if (i == todoList.size() - 1) {
Desktop.noArrangeLayoutOnNewTableBrowser = false;
}
todoList.get(i).actionPerformed(e);
}
} finally {
Desktop.noArrangeLayoutOnNewTableBrowser = false;
Desktop.noArrangeLayoutOnNewTableBrowserWithAnchor = false;
UIUtil.resetWaitCursor(parent);
}
}
});
}
public void rowsCounted(long count, ActionListener itemAction) {
++done;
if (count != 0) {
todoList.add(itemAction);
}
int p = todo > 0? (100 * done) / todo : 0;
if (done < todo) {
setText(initText + p + "%");
} else {
setText("All non-empty (" + todoList.size() + ")");
setEnabled(true);
}
}
public void setInitialText() {
if (todoList.isEmpty()) {
setText("All non-empty (0)");
} else {
setText(initText + "100%");
}
}
};
private String currentSelectedRowCondition = "";
/**
* Creates popup menu for navigation.
* @param navigateFromAllRows
* @param copyTCB
* @param runnable
* @param runnable
*/
public JPopupMenu createPopupMenu(final Row row, final int rowIndex, final int x, final int y, boolean navigateFromAllRows) {
return createPopupMenu(row, rowIndex, x, y, navigateFromAllRows, null, null);
}
/**
* Creates popup menu for navigation.
* @param navigateFromAllRows
* @param runnable
*/
public JPopupMenu createPopupMenu(final Row row, final int rowIndex, final int x, final int y, boolean navigateFromAllRows, JMenuItem altCopyTCB, final Runnable repaint) {
return createPopupMenu(row, rowIndex, x, y, navigateFromAllRows, altCopyTCB, repaint, true);
}
/**
* Creates popup menu for navigation.
* @param navigateFromAllRows
* @param runnable
*/
public JPopupMenu createPopupMenu(final Row row, final int rowIndex, final int x, final int y, boolean navigateFromAllRows, JMenuItem altCopyTCB, final Runnable repaint, final boolean withKeyStroke) {
JMenuItem tableFilter = new JCheckBoxMenuItem("Table Filter");
if (withKeyStroke) {
tableFilter.setAccelerator(KS_FILTER);
} else {
tableFilter.setVisible(false);
}
tableFilter.setSelected(isTableFilterEnabled);
if (isLimitExceeded) {
tableFilter.setForeground(Color.red);
tableFilter.setToolTipText("Row limit exceeded. Filtering may be incomplete.");
}
tableFilter.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
isTableFilterEnabled = !isTableFilterEnabled;
updateTableModel();
}
});
JMenuItem copyTCB;
if (altCopyTCB != null) {
copyTCB = altCopyTCB;
} else {
copyTCB = new JMenuItem("Copy to Clipboard");
if (withKeyStroke) {
copyTCB.setAccelerator(KS_COPY_TO_CLIPBOARD);
}
copyTCB.setEnabled(rowsTable.getSelectedColumnCount() > 0);
copyTCB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
UIUtil.copyToClipboard(rowsTable, true);
}
});
}
if (table instanceof SqlStatementTable && resultSetType == null) {
JPopupMenu jPopupMenu = new JPopupMenu();
if (row != null) {
JMenuItem det = new JMenuItem("Details");
if (withKeyStroke) {
det.setAccelerator(KS_DETAILS);
}
jPopupMenu.add(det);
jPopupMenu.add(new JSeparator());
det.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openDetailsView(rowIndex, x, y);
}
});
}
JMenu script = new JMenu("Create SQL");
script.setEnabled(false);
jPopupMenu.add(script);
jPopupMenu.addSeparator();
jPopupMenu.add(copyTCB);
jPopupMenu.addSeparator();
jPopupMenu.add(tableFilter);
JMenuItem editMode = new JMenuItem("Edit Mode");
if (withKeyStroke) {
editMode.setAccelerator(KS_EDIT);
}
jPopupMenu.add(editMode);
editMode.setEnabled(false);
return jPopupMenu;
}
List<String> assList = new ArrayList<String>();
Map<String, Association> assMap = new HashMap<String, Association>();
for (Association a : table.associations) {
int n = 0;
for (Association a2 : table.associations) {
if (a.destination == a2.destination) {
++n;
}
}
char c = ' ';
if (a.isIgnored()) {
c = '4';
} else if (a.isInsertDestinationBeforeSource()) {
c = '1';
} else if (a.isInsertSourceBeforeDestination()) {
c = '2';
} else {
c = '3';
}
String name = c + a.getDataModel().getDisplayName(a.destination) + (n > 1 ? " on " + a.getName() : "");
assList.add(name);
assMap.put(name, a);
}
Collections.sort(assList);
final Object context = new Object();
AllNonEmptyItem allNonEmpty = new AllNonEmptyItem();
JPopupMenu popup = new JPopupMenu();
popup = createNavigationMenu(popup, row, rowIndex, assList, assMap, "Parents", "1", navigateFromAllRows, 80, allNonEmpty, context);
popup = createNavigationMenu(popup, row, rowIndex, assList, assMap, "Children", "2", navigateFromAllRows, 60, allNonEmpty, context);
popup = createNavigationMenu(popup, row, rowIndex, assList, assMap, "Associated Rows", "3", navigateFromAllRows, 40, allNonEmpty, context);
popup = createNavigationMenu(popup, row, rowIndex, assList, assMap, "Detached Rows", "4", navigateFromAllRows, 40, allNonEmpty, context);
popup.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
cancel();
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
cancel();
}
private void cancel() {
CancellationHandler.cancelSilently(context);
getRunnableQueue().add(new RunnableWithPriority() {
@Override
public void run() {
CancellationHandler.reset(context);
}
@Override
public int getPriority() {
return 0;
}
});
}
});
if (!isPending && !rows.isEmpty()) {
popup.add(allNonEmpty);
allNonEmpty.setInitialText();
}
if (row != null) {
JMenuItem det = new JMenuItem("Details");
if (withKeyStroke) {
det.setAccelerator(KS_DETAILS);
}
popup.insert(det, 0);
popup.insert(new JSeparator(), 1);
det.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openDetailsView(rowIndex, x, y);
}
});
if (!(table instanceof SqlStatementTable) || resultSetType != null) {
if (popup.getComponentCount() > 0) {
popup.add(new JSeparator());
}
JMenuItem qb = new JMenuItem("Query Builder");
qb.setAccelerator(KS_QUERYBUILDER);
popup.add(qb);
qb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openQueryBuilder(false, SqlUtil.replaceAliases(row.rowId, "A", "A"));
}
});
JMenuItem sqlConsole = new JMenuItem("SQL Console");
sqlConsole.setAccelerator(KS_SQLCONSOLE);
popup.add(sqlConsole);
sqlConsole.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openQueryBuilder(true, SqlUtil.replaceAliases(row.rowId, "A", "A"));
}
});
if (!currentSelectedRowCondition.equals("")
&& currentSelectedRowCondition.equals(getAndConditionText())
&& rows.size() == 1) {
JMenuItem sr = new JMenuItem("Deselect Row");
popup.insert(sr, 0);
sr.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
andCondition.setSelectedItem("");
}
});
} else {
JMenuItem sr = new JMenuItem("Select Row");
sr.setEnabled(rows.size() > 1 && !row.rowId.isEmpty());
popup.insert(sr, 0);
sr.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selectRow(row);
}
});
}
JMenu sql = new JMenu("Create SQL");
final String rowName = !(table instanceof SqlStatementTable)? dataModel.getDisplayName(table) + "(" + SqlUtil.replaceAliases(row.rowId, null, null) + ")" : "";
JMenuItem update = new JMenuItem("Update");
sql.add(update);
update.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openSQLDialog("Update Row " + rowName, x, y, SQLDMLBuilder.buildUpdate(table, row, true, session));
}
});
JMenuItem insert = new JMenuItem("Insert");
sql.add(insert);
insert.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openSQLDialog("Insert Row " + rowName, x, y, SQLDMLBuilder.buildInsert(table, row, true, session));
}
});
JMenuItem insertNewRow = createInsertChildMenu(row, x, y);
sql.add(insertNewRow);
JMenuItem delete = new JMenuItem("Delete");
sql.add(delete);
delete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openSQLDialog("Delete Row " + rowName, x, y, SQLDMLBuilder.buildDelete(table, row, true, session));
}
});
insert.setEnabled(resultSetType == null);
update.setEnabled(resultSetType == null);
delete.setEnabled(resultSetType == null);
if (getQueryBuilderDialog() == null) {
popup.removeAll();
popup.add(det);
popup.addSeparator();
JMenu script = new JMenu("Create SQL");
popup.add(script);
if (table.getName() == null) {
script.setEnabled(false);
} else {
final String tableName = dataModel.getDisplayName(table);
script.add(update);
script.add(insert);
script.add(insertNewRow);
script.add(delete);
script.addSeparator();
JMenuItem updates = new JMenuItem("Updates (all rows)");
script.add(updates);
updates.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openSQLDialog("Update " + tableName, x, y, new Object() { @Override
public String toString() { return SQLDMLBuilder.buildUpdate(table, sortedAndFiltered(rows), session); }});
}
});
JMenuItem inserts = new JMenuItem("Inserts (all rows)");
script.add(inserts);
inserts.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openSQLDialog("Insert Into " + tableName, x, y, new Object() { @Override
public String toString() { return SQLDMLBuilder.buildInsert(table, sortedAndFiltered(rows), session); }});
}
});
JMenuItem deletes = new JMenuItem("Deletes (all rows)");
script.add(deletes);
deletes.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openSQLDialog("Delete from " + tableName, x, y, new Object() { @Override
public String toString() { return SQLDMLBuilder.buildDelete(table, sortedAndFiltered(rows), session); }
});
}
});
boolean hasPK = !rowIdSupport.getPrimaryKey(table).getColumns().isEmpty();
if (!hasPK) {
delete.setEnabled(false);
}
inserts.setEnabled(rows.size() > 0);
updates.setEnabled(hasPK && rows.size() > 0);
deletes.setEnabled(hasPK && rows.size() > 0);
}
} else {
popup.add(sql);
}
}
popup.addSeparator();
popup.add(copyTCB);
popup.addSeparator();
popup.add(tableFilter);
JCheckBoxMenuItem editMode = new JCheckBoxMenuItem("Edit Mode");
editMode.setEnabled(isTableEditable(table));
if (withKeyStroke) {
editMode.setAccelerator(KS_EDIT);
}
editMode.setSelected(isEditMode);
editMode.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setEditMode(!isEditMode);
updateTableModel();
if (repaint != null) {
SwingUtilities.invokeLater(repaint);
}
}
});
popup.add(editMode);
}
return popup;
}
/**
* Creates popup menu for SQL.
* @param forNavTree
* @param browserContentPane
*/
public JPopupMenu createSqlPopupMenu(final Row parentrow, final int rowIndex, final int x, final int y, boolean forNavTree, final Component parentComponent) {
JPopupMenu popup = new JPopupMenu();
JMenuItem qb = new JMenuItem("Query Builder");
qb.setAccelerator(KS_QUERYBUILDER);
popup.add(qb);
qb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openQueryBuilder(false);
}
});
JMenuItem sqlConsole = new JMenuItem("SQL Console");
sqlConsole.setAccelerator(KS_SQLCONSOLE);
popup.add(sqlConsole);
sqlConsole.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openQueryBuilder(true);
}
});
JMenu sqlDml = new JMenu("Create SQL");
popup.add(sqlDml);
final String tableName = dataModel.getDisplayName(table);
JMenuItem update = new JMenuItem("Updates");
sqlDml.add(update);
update.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openSQLDialog("Update " + tableName, x, y, new Object() { @Override
public String toString() { return SQLDMLBuilder.buildUpdate(table, sortedAndFiltered(rows), session); }});
}
});
JMenuItem insert = new JMenuItem("Inserts");
sqlDml.add(insert);
insert.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openSQLDialog("Insert Into " + tableName, x, y, new Object() { @Override
public String toString() { return SQLDMLBuilder.buildInsert(table, sortedAndFiltered(rows), session); }});
}
});
JMenuItem delete = new JMenuItem("Deletes");
sqlDml.add(delete);
delete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openSQLDialog("Delete from " + tableName, x, y, new Object() { @Override
public String toString() { return SQLDMLBuilder.buildDelete(table, sortedAndFiltered(rows), session); }});
}
});
boolean hasPK = !rowIdSupport.getPrimaryKey(table).getColumns().isEmpty();
insert.setEnabled(rows.size() > 0);
update.setEnabled(hasPK && rows.size() > 0);
delete.setEnabled(hasPK && rows.size() > 0);
popup.add(new JSeparator());
JMenuItem exportData = new JMenuItem("Export Data");
popup.add(exportData);
exportData.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openExtractionModelEditor(true);
}
});
JMenuItem extractionModel = new JMenuItem("Create Extraction Model");
popup.add(extractionModel);
extractionModel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openExtractionModelEditor(false);
}
});
popup.add(new JSeparator());
if (!forNavTree) {
JMenuItem det = new JMenuItem("Details");
det.setAccelerator(KS_DETAILS);
popup.add(det);
det.setEnabled(rows.size() > 0);
det.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openDetails(x, y);
}
});
}
// popup.add(new JSeparator());
JMenuItem snw = new JMenuItem("Show in New Window");
popup.add(snw);
snw.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
showInNewWindow();
}
});
JMenuItem al = new JMenuItem("Append Layout...");
popup.add(al);
al.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
appendLayout();
}
});
popup.addSeparator();
JMenuItem m = new JMenuItem("Hide (Minimize)");
popup.add(m);
m.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
onHide();
}
});
m = new JMenuItem("Close");
popup.add(m);
m.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
closeWithChildren(parentComponent);
}
});
popup.add(new JSeparator());
JMenuItem tableFilter = new JCheckBoxMenuItem("Table Filter");
tableFilter.setAccelerator(KS_FILTER);
tableFilter.setSelected(isTableFilterEnabled);
if (isLimitExceeded) {
tableFilter.setForeground(Color.red);
tableFilter.setToolTipText("Row limit exceeded. Filtering may be incomplete.");
}
tableFilter.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
isTableFilterEnabled = !isTableFilterEnabled;
updateTableModel();
}
});
popup.add(tableFilter);
JCheckBoxMenuItem editMode = new JCheckBoxMenuItem("Edit Mode");
editMode.setEnabled(isTableEditable(table));
editMode.setAccelerator(KS_EDIT);
editMode.setSelected(isEditMode);
editMode.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setEditMode(!isEditMode);
updateTableModel();
}
});
popup.add(editMode);
return popup;
}
protected boolean isTableEditable(Table theTable) {
return resultSetType != null || !rowIdSupport.getPrimaryKey(theTable).getColumns().isEmpty();
}
public boolean closeWithChildren(Component parentComponent) {
int count = countSubNodes(this);
Component parent = SwingUtilities.getWindowAncestor(this);
if (parent == null) {
parent = BrowserContentPane.this;
}
boolean closeThisToo = true;
if (count > 1) {
int o = JOptionPane.showOptionDialog(parentComponent, "Which tables do you want to close?", "Close",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
new Object[] {
"Only this table",
"This and related tables (" + (count) + ")",
"Related tables (" + (count - 1) + ")"
},
null);
if (o == 0) {
UIUtil.setWaitCursor(parent);
try {
close();
} finally {
UIUtil.resetWaitCursor(parent);
}
return true;
}
if (o == 1) {
closeThisToo = true;
} else if (o == 2) {
closeThisToo = false;
} else {
return false;
}
}
UIUtil.setWaitCursor(parent);
try {
closeSubTree(BrowserContentPane.this, closeThisToo);
} finally {
UIUtil.resetWaitCursor(parent);
}
return true;
}
private int countSubNodes(BrowserContentPane cp) {
int count = 0;
for (RowBrowser c: cp.getChildBrowsers()) {
count += countSubNodes(c.browserContentPane);
}
return count + 1;
}
private void closeSubTree(BrowserContentPane cp, boolean closeThisToo) {
for (RowBrowser c: cp.getChildBrowsers()) {
closeSubTree(c.browserContentPane, true);
}
if (closeThisToo) {
cp.close();
}
}
private JMenu createInsertChildMenu(Row row, final int x, final int y) {
JScrollMenu insertNewRow = new JScrollMenu("Insert Child");
if (table == null || table.getName() == null) {
insertNewRow.setEnabled(false);
return insertNewRow;
}
List<Association> tableAssociations = table.associations;
if (tableAssociations == null || tableAssociations.isEmpty()) {
// artificial table from SQL Console?
Table t = dataModel.getTable(table.getName());
if (t == null) {
insertNewRow.setEnabled(false);
return insertNewRow;
}
tableAssociations = t.associations;
}
List<Association> assocs = new ArrayList<Association>();
Map<Association, Row> children = new HashMap<Association, Row>();
if (tableAssociations != null) {
for (Association association: tableAssociations) {
Row child = createNewRow(row, table, association);
if (child != null) {
assocs.add(association);
children.put(association, child);
}
}
}
Collections.sort(assocs, new Comparator<Association>() {
@Override
public int compare(Association a, Association b) {
String dNameA = dataModel.getDisplayName(a.destination);
String dNameB = dataModel.getDisplayName(b.destination);
return dNameA.compareTo(dNameB);
}
});
for (int i = 0; i < assocs.size(); ++i) {
final Association association = assocs.get(i);
Association pred = i > 0? assocs.get(i - 1) : null;
Association succ = i < assocs.size() - 1? assocs.get(i + 1) : null;
final String dName = dataModel.getDisplayName(association.destination);
JMenuItem item;
if (pred != null && pred.destination == association.destination || succ != null && succ.destination == association.destination) {
item = new JMenuItem(dName + " on " + association.getName());
} else {
item = new JMenuItem(dName);
}
final Row child = children.get(association);
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openSQLDialog("Insert Child into " + dName, x, y, SQLDMLBuilder.buildInsert(association.destination, child, true, session));
}
});
insertNewRow.add(item);
}
insertNewRow.setEnabled(!assocs.isEmpty());
return insertNewRow;
}
void openExtractionModelEditor(boolean doExport) {
Component parent = SwingUtilities.getWindowAncestor(this);
if (parent == null) {
parent = this;
}
UIUtil.setWaitCursor(parent);
try {
String file;
String ts = new SimpleDateFormat("HH-mm-ss-SSS").format(new Date());
File newFile;
Table stable = table;
String subjectCondition;
QueryBuilderDialog.Relationship root = createQBRelations(false);
Collection<Association> restrictedAssociations = new HashSet<Association>();
Collection<Association> restrictedDependencies = new HashSet<Association>();
Collection<RestrictionDefinition> restrictedDependencyDefinitions = new HashSet<RestrictionDefinition>();
List<RestrictionDefinition> restrictionDefinitions = createRestrictions(root, stable, restrictedAssociations, restrictedDependencies, restrictedDependencyDefinitions);
// if (!restrictedDependencies.isEmpty()) {
Set<String> parents = new TreeSet<String>();
for (Association association: restrictedDependencies) {
parents.add(dataModel.getDisplayName(association.destination));
}
// String pList = "";
// int i = 0;
// for (String p: parents) {
// pList += p + "\n";
// if (++i > 20) {
// break;
// }
// }
final SbEDialog sbEDialog = new SbEDialog(SwingUtilities.getWindowAncestor(this),
(doExport? "Export rows and related rows from \"" : "Create Extraction Model for Subject \"") + dataModel.getDisplayName(stable) + "\".", (parents.isEmpty()? "" : ("\n\n" + parents.size() + " disregarded parent tables.")));
if (doExport) {
sbEDialog.setTitle("Export Data");
}
sbEDialog.regardButton.setVisible(!parents.isEmpty());
sbEDialog.dispose();
DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer() {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
Component result = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
if (value instanceof DefaultMutableTreeNode) {
if (!(((DefaultMutableTreeNode) value).getUserObject() instanceof String)) {
if (result instanceof JLabel) {
((JLabel) result).setForeground(Color.red);
} else {
((JLabel) result).setForeground(Color.black);
}
}
}
return result;
}
};
renderer.setOpenIcon(null);
renderer.setLeafIcon(null);
renderer.setClosedIcon(null);
sbEDialog.browserTree.setCellRenderer(renderer);
int[] count = new int[] { 0 };
DefaultTreeModel treeModel = new DefaultTreeModel(addChildNodes(this, restrictedDependencies, count));
sbEDialog.browserTree.setModel(treeModel);
for (int i = 0; i < count[0]; ++i) {
sbEDialog.browserTree.expandRow(i);
}
sbEDialog.browserTree.scrollRowToVisible(0);
sbEDialog.browserTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
sbEDialog.browserTree.getSelectionModel().clearSelection();
}
});
sbEDialog.grabFocus();
sbEDialog.setVisible(true);
if (!sbEDialog.ok) {
return;
}
if (sbEDialog.regardButton.isSelected()) {
restrictionDefinitions.removeAll(restrictedDependencyDefinitions);
for (Association a: restrictedDependencies) {
disableDisregardedNonParentsOfDestination(a, restrictedAssociations, restrictionDefinitions);
}
}
// int option = JOptionPane.showOptionDialog(parent, "Disregarded parent tables:\n\n" + pList + "\n", "Disregarded parent tables", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new Object[] { "regard parent tables", "Ok" }, "regard parent tables");
// switch (option) {
// case 0:
// restrictionDefinitions.removeAll(restrictedDependencyDefinitions);
// for (Association a: restrictedDependencies) {
// disableDisregardedNonParentsOfDestination(a, restrictedAssociations, restrictionDefinitions);
// }
// break;
// case 1:
// break;
// default: return;
// }
// }
subjectCondition = root.whereClause;
if (doExport && (getParentBrowser() != null /* || isLimitExceeded */)) {
subjectCondition = root.whereClause;
if (subjectCondition != null) {
subjectCondition = subjectCondition.replace('\r', ' ').replace('\n', ' ');
}
StringBuilder sb = new StringBuilder();
boolean f = true;
for (Row row: rows) {
if (f) {
f = false;
} else {
sb.append(" or ");
}
sb.append("(" + row.rowId + ")");
}
if (subjectCondition != null && subjectCondition.trim().length() > 0) {
subjectCondition = "(" + subjectCondition + ") and (" + sb + ")";
} else {
subjectCondition = sb.toString();
}
}
if (subjectCondition == null) {
subjectCondition = "";
}
// if (doExport && isLimitExceeded && rows != null && !rows.isEmpty()) {
// StringBuilder sb = new StringBuilder();
// boolean f = true;
// for (Row row: rows) {
// if (f) {
// f = false;
// } else {
// sb.append(" or ");
// }
// sb.append("(" + row.rowId + ")");
// }
// subjectCondition = sb.toString();
// }
subjectCondition = SqlUtil.replaceAliases(subjectCondition, "T", "T");
for (int i = 1; ; ++i) {
file = Environment.newFile("extractionmodel" + File.separator + "by-example").getPath();
newFile = new File(file);
newFile.mkdirs();
file += File.separator + "SbE-" + (dataModel.getDisplayName(stable).replaceAll("[\"'\\[\\]]", "")) + "-" + ts + (i > 1? "-" + Integer.toString(i) : "") + ".jm";
newFile = new File(file);
if (!newFile.exists()) {
break;
}
}
Map<String, Map<String, double[]>> positions = new TreeMap<String, Map<String,double[]>>();
collectPositions(positions);
String currentModelSubfolder = DataModelManager.getCurrentModelSubfolder(executionContext);
dataModel.save(file, stable, subjectCondition, ScriptFormat.SQL, restrictionDefinitions, positions, new ArrayList<ExtractionModel.AdditionalSubject>(), currentModelSubfolder);
ExtractionModelFrame extractionModelFrame = ExtractionModelFrame.createFrame(file, false, !doExport, null, executionContext);
extractionModelFrame.setDbConnectionDialogClone(getDbConnectionDialog());
if (doExport) {
extractionModelFrame.openExportDialog(false, new Runnable() {
@Override
public void run() {
try {
reloadDataModel();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
extractionModelFrame.dispose();
} else {
extractionModelFrame.markDirty();
extractionModelFrame.expandAll();
}
newFile.delete();
} catch (Throwable e) {
UIUtil.showException(this, "Error", e, session);
} finally {
UIUtil.resetWaitCursor(parent);
}
}
private DefaultMutableTreeNode addChildNodes(BrowserContentPane browserContentPane, Collection<Association> restrictedDependencies, int[] count) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(dataModel.getDisplayName(browserContentPane.table));
count[0]++;
Set<Table> regardedChildren = new HashSet<Table>();
for (RowBrowser rb: browserContentPane.getChildBrowsers()) {
DefaultMutableTreeNode childNode = addChildNodes(rb.browserContentPane, restrictedDependencies, count);
node.add(childNode);
regardedChildren.add(rb.browserContentPane.table);
}
for (final Association dep: restrictedDependencies) {
if (dep.source == browserContentPane.table && !regardedChildren.contains(dep.destination)) {
node.add(new DefaultMutableTreeNode(new Object() {
String item = dataModel.getDisplayName(dep.destination);
@Override
public String toString() {
return item;
}
}));
count[0]++;
}
}
return node;
}
private void disableDisregardedNonParentsOfDestination(Association a,
Collection<Association> regardedAssociations,
List<RestrictionDefinition> restrictionDefinitions) {
for (Association npa: a.destination.associations) {
if (!regardedAssociations.contains(npa)) {
regardedAssociations.add(npa);
if (npa.isInsertDestinationBeforeSource()) {
disableDisregardedNonParentsOfDestination(npa, regardedAssociations, restrictionDefinitions);
} else {
RestrictionDefinition rest = new RestrictionDefinition(npa.source, npa.destination, npa.getName(), null, true);
restrictionDefinitions.add(rest);
}
}
}
}
private static class RestrictionLiteral {
public String condition;
public int distanceFromRoot;
public boolean isIgnored;
public boolean isIgnoredIfReversalIsRestricted = false;
@Override
public String toString() {
return "Cond:" + condition + " Dist: " + distanceFromRoot + " isIgnored: " + isIgnored + " isIgnoredIfReversalIsRestricted: " + isIgnoredIfReversalIsRestricted;
}
}
/**
* Creates restriction according to the given {@link Relationship} tree.
*
* @param root root of tree
* @return restrictions
*/
private List<RestrictionDefinition> createRestrictions(Relationship root, Table subject, Collection<Association> regardedAssociations, Collection<Association> restrictedDependencies, Collection<RestrictionDefinition> restrictedDependencyDefinitions) {
List<RestrictionDefinition> restrictionDefinitions = new ArrayList<RestrictionDefinition>();
Map<Association, List<RestrictionLiteral>> restrictionLiterals = new HashMap<Association, List<RestrictionLiteral>>();
collectRestrictionLiterals(restrictionLiterals, root, subject, 0);
for (Association association: restrictionLiterals.keySet()) {
RestrictionDefinition rest = createRestrictionDefinition(association, restrictionLiterals, true);
regardedAssociations.add(association);
if (rest.isIgnored || (rest.condition != null && rest.condition.trim().length() != 0)) {
restrictionDefinitions.add(rest);
if (association.isInsertDestinationBeforeSource() && rest.isIgnored) {
restrictedDependencies.add(association);
restrictedDependencyDefinitions.add(rest);
}
}
}
return restrictionDefinitions;
}
private RestrictionDefinition createRestrictionDefinition(Association association, Map<Association, List<RestrictionLiteral>> restrictionLiterals, boolean checkReversal) {
List<RestrictionLiteral> lits = restrictionLiterals.get(association);
boolean useDistance = false;
boolean hasTrue = false;
boolean hasNotTrue = false;
boolean hasNotFalse = false;
Integer lastDist = null;
for (RestrictionLiteral l: lits) {
if (l.isIgnoredIfReversalIsRestricted) {
if (checkReversal) {
RestrictionDefinition revRest = createRestrictionDefinition(association.reversalAssociation, restrictionLiterals, false);
if (revRest.isIgnored || (revRest.condition != null && revRest.condition.trim().length() > 0)) {
l.isIgnored = true;
} else {
l.isIgnored = false;
l.condition = null;
}
l.isIgnoredIfReversalIsRestricted = false;
} else {
l.isIgnored = true;
l.isIgnoredIfReversalIsRestricted = false;
}
}
// disabled since 5.0
// if (lastDist != null && lastDist != l.distanceFromRoot) {
// useDistance = true;
// }
// lastDist = l.distanceFromRoot;
if (!l.isIgnored) {
hasNotFalse = true;
if (l.condition == null || l.condition.trim().length() == 0) {
hasTrue = true;
} else {
hasNotTrue = true;
}
} else {
hasNotTrue = true;
}
}
boolean isIgnored;
String condition = null;
if (!hasNotFalse) {
isIgnored = true;
} else if (!hasNotTrue) {
isIgnored = false;
} else if (hasTrue && !useDistance) {
isIgnored = false;
} else {
for (RestrictionLiteral l: lits) {
if (!l.isIgnored) {
String c = null;
if (useDistance) {
c = l.distanceFromRoot == 0? "A.$IS_SUBJECT" : ("A.$DISTANCE=" + l.distanceFromRoot);
}
if (l.condition != null && l.condition.trim().length() > 0) {
if (c == null) {
c = l.condition;
} else {
c = c + " and (" + l.condition + ")";
}
}
if (condition == null) {
condition = c;
} else {
condition += " or " + c;
}
}
}
isIgnored = false;
}
RestrictionDefinition rest = new RestrictionDefinition(association.source, association.destination, association.getName(), condition, isIgnored);
return rest;
}
/**
* Collects restriction literals per association according to a given {@link Relationship} tree.
*
* @param restrictionLiterals to put literals into
* @param root root of tree
* @param distanceFromRoot distance
*/
private void collectRestrictionLiterals(Map<Association, List<RestrictionLiteral>> restrictionLiterals, Relationship root, Table subject, int distanceFromRoot) {
for (Association association: subject.associations) {
List<Relationship> children = new ArrayList<QueryBuilderDialog.Relationship>();
for (Relationship r: root.children) {
if (r.association == association) {
children.add(r);
}
}
if (children.isEmpty()) {
children.add(null);
}
for (Relationship child: children) {
RestrictionLiteral restrictionLiteral = new RestrictionLiteral();
restrictionLiteral.distanceFromRoot = distanceFromRoot;
restrictionLiteral.isIgnored = false;
if (child == null) {
restrictionLiteral.isIgnored = true;
// if (association.isInsertDestinationBeforeSource()) {
if (root.association != null && association == root.association.reversalAssociation) {
if (association.getCardinality() == Cardinality.MANY_TO_ONE
||
association.getCardinality() == Cardinality.ONE_TO_ONE) {
restrictionLiteral.isIgnoredIfReversalIsRestricted = true;
}
}
// }
} else {
restrictionLiteral.condition = child.whereClause == null? "" : SqlUtil.replaceAliases(child.whereClause, "B", "A");
collectRestrictionLiterals(restrictionLiterals, child, association.destination, distanceFromRoot + 1);
}
List<RestrictionLiteral> literals = restrictionLiterals.get(association);
if (literals == null) {
literals = new ArrayList<BrowserContentPane.RestrictionLiteral>();
restrictionLiterals.put(association, literals);
}
literals.add(restrictionLiteral);
}
}
}
private void openSQLDialog(String titel, int x, int y, Object sql) {
UIUtil.setWaitCursor(this);
JDialog d;
try {
String LF = System.getProperty("line.separator", "\n");
String sqlString = sql.toString().trim() + LF;
if (sqlString.length() > 10L*1024L*1024L) {
int o = JOptionPane.showOptionDialog(this, "SQL Script is large (" + (sqlString.length() / 1024) + " KB)", "SQL Script is large", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new Object[] { "Open", "Cancel", "Save Script" }, "Save Script");
if (o == 2) {
String fn = UIUtil.choseFile(null, ".", "Save SQL Script", ".sql", this, false, false, false);
if (fn != null) {
try {
PrintWriter out = new PrintWriter(new FileWriter(fn));
out.print(sqlString);
out.close();
} catch (Throwable e) {
UIUtil.showException(this, "Error saving script", e, UIUtil.EXCEPTION_CONTEXT_USER_ERROR);
}
}
}
if (o != 0) {
return;
}
}
d = new JDialog(getOwner(), "Create SQL - " + titel, true);
d.getContentPane().add(new SQLDMLPanel(sqlString, getSqlConsole(false), session, getMetaDataSource(),
new Runnable() {
@Override
public void run() {
reloadRows();
}
},
new Runnable() {
@Override
public void run() {
getSqlConsole(true);
}
},
d, executionContext));
d.pack();
d.setLocation(x - 50, y - 100);
d.setSize(700, Math.max(d.getHeight() + 20, 400));
d.setLocation(getOwner().getX() + (getOwner().getWidth() - d.getWidth()) / 2, Math.max(0, getOwner().getY() + (getOwner().getHeight() - d.getHeight()) / 2));
UIUtil.fit(d);
} catch (Throwable e) {
UIUtil.showException(this, "Error", e);
return;
} finally {
UIUtil.resetWaitCursor(this);
}
d.setVisible(true);
}
protected abstract SQLConsole getSqlConsole(boolean switchToConsole);
private void appendClosure() {
if (getParentBrowser() != null) {
BrowserContentPane parentContentPane = getParentBrowser().browserContentPane;
Set<Pair<BrowserContentPane, Row>> newElements = new HashSet<Pair<BrowserContentPane, Row>>();
for (Pair<BrowserContentPane, Row> e: rowsClosure.currentClosure) {
if (e.a == parentContentPane) {
parentContentPane.findClosure(e.b, newElements, true);
}
}
rowsClosure.currentClosure.addAll(newElements);
rowsClosure.currentClosureRowIDs.clear();
for (Pair<BrowserContentPane, Row> r: rowsClosure.currentClosure) {
rowsClosure.currentClosureRowIDs.add(new Pair<BrowserContentPane, String>(r.a, r.b.nonEmptyRowId));
}
rowsTable.repaint();
adjustClosure(null, this);
}
}
protected void setCurrentRowSelectionAndReloadChildrenIfLimitIsExceeded(int i) {
setCurrentRowSelection(i);
if (i >= 0) {
reloadChildrenIfLimitIsExceeded();
}
}
protected void setCurrentRowSelection(int i) {
currentRowSelection = i;
if (i >= 0) {
Row row = rows.get(rowsTable.getRowSorter().convertRowIndexToModel(i));
rowsClosure.currentClosure.clear();
rowsClosure.parentPath.clear();
rowsClosure.currentClosureRootID = row.nonEmptyRowId;
findClosure(row);
Rectangle visibleRect = rowsTable.getVisibleRect();
Rectangle pos = rowsTable.getCellRect(i, 0, false);
rowsTable.scrollRectToVisible(new Rectangle(visibleRect.x, pos.y, 1, pos.height));
}
rowsClosure.currentClosureRowIDs.clear();
for (Pair<BrowserContentPane, Row> r: rowsClosure.currentClosure) {
rowsClosure.currentClosureRowIDs.add(new Pair<BrowserContentPane, String>(r.a, r.b.nonEmptyRowId));
}
rowsTable.repaint();
adjustClosure(this, null);
}
private void reloadChildrenIfLimitIsExceeded() {
for (RowBrowser ch: getChildBrowsers()) {
if (ch.browserContentPane != null) {
if (ch.browserContentPane.isLimitExceeded) {
ch.browserContentPane.reloadRows("because rows limit is exceeded");
} else {
ch.browserContentPane.reloadChildrenIfLimitIsExceeded();
}
}
}
}
private JPopupMenu createNavigationMenu(JPopupMenu popup, final Row row, final int rowIndex, List<String> assList, Map<String, Association> assMap,
String title, String prefix, final boolean navigateFromAllRows, final int rowCountPriority, final AllNonEmptyItem allNonEmptyItem, final Object context) {
JScrollC2Menu nav = new JScrollC2Menu(title);
if (prefix.equals("1")) {
nav.setIcon(UIUtil.scaleIcon(this, redDotIcon));
}
if (prefix.equals("2")) {
nav.setIcon(UIUtil.scaleIcon(this, greenDotIcon));
}
if (prefix.equals("3")) {
nav.setIcon(UIUtil.scaleIcon(this, blueDotIcon));
}
if (prefix.equals("4")) {
nav.setIcon(UIUtil.scaleIcon(this, greyDotIcon));
}
JMenu current = nav;
int l = 0;
for (String name : assList) {
if (!name.startsWith(prefix)) {
continue;
}
final Association association = assMap.get(name);
++l;
final JMenuItem item = new JMenuItem(" " + (name.substring(1)) + " ");
item.setToolTipText(association.getUnrestrictedJoinCondition());
final JLabel countLabel = new JLabel(". >99999 ") {
@Override
public void paint(Graphics g) {
if (!getText().startsWith(".")) {
super.paint(g);
}
}
};
boolean excludeFromANEmpty = false;
for (RowBrowser child: getChildBrowsers()) {
if (association == child.association) {
if (rowIndex < 0 && child.rowIndex < 0 || rowIndex == child.rowIndex) {
item.setFont(new Font(item.getFont().getName(), item.getFont().getStyle() | Font.ITALIC, item.getFont().getSize()));
excludeFromANEmpty = true;
break;
}
}
}
final ActionListener itemAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
highlightedRows.add(rowIndex);
if (navigateFromAllRows) {
navigateTo(association, -1, null);
} else {
navigateTo(association, rowIndex, row);
}
}
};
item.addActionListener(itemAction);
if (!excludeFromANEmpty) {
allNonEmptyItem.todo++;
}
final boolean fExcludeFromANEmpty = excludeFromANEmpty;
if (!isPending && !rows.isEmpty()) {
getRunnableQueue().add(new RunnableWithPriority() {
final int MAX_RC = 1000;
@Override
public int getPriority() {
return rowCountPriority;
}
@Override
public void run() {
List<Row> r;
Pair<String, Association> key;
if (rowIndex < 0) {
r = rows;
key = new Pair<String, Association>("", association);
} else {
r = Collections.singletonList(row);
key = new Pair<String, Association>(row.nonEmptyRowId, association);
}
Pair<RowCount, Long> cachedCount = rowCountCache.get(key);
RowCount rowCount;
if (cachedCount != null && cachedCount.b > System.currentTimeMillis()) {
rowCount = cachedCount.a;
} else {
RowCounter rc = new RowCounter(table, association, r, session, rowIdSupport);
try {
rowCount = rc.countRows(getAndConditionText(), context, MAX_RC + 1, false);
} catch (SQLException e) {
rowCount = new RowCount(-1, true);
}
rowCountCache.put(key, new Pair<RowCount, Long>(rowCount, System.currentTimeMillis() + MAX_ROWCOUNTCACHE_RETENTION_TIME));
}
final RowCount count = rowCount;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
String cs = " " + (count.count < 0? "?" : (count.count > MAX_RC)? (">" + MAX_RC) : count.isExact? count.count : (">" + count.count)) + " ";
countLabel.setText(cs);
if (count.count == 0) {
countLabel.setForeground(Color.lightGray);
}
if (!fExcludeFromANEmpty) {
allNonEmptyItem.rowsCounted(count.count, itemAction);
}
}
});
}
});
}
if (current != null) {
GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = l;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
current.getPopupMenu().add(item, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = l;
gridBagConstraints.fill = java.awt.GridBagConstraints.NONE;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weightx = 1.0;
current.getPopupMenu().add(countLabel, gridBagConstraints);
} else {
popup.add(item);
}
}
if (l > 0) {
popup.add(nav);
}
return popup;
}
private long lastReloadTS = 0;
/**
* Reloads rows.
*/
public void reloadRows() {
reloadRows(null);
}
/**
* Reloads rows.
*/
public void reloadRows(String cause) {
if (!suppressReload) {
session = retrieveCurrentSession();
lastReloadTS = System.currentTimeMillis();
cancelLoadJob(true);
setPendingState(true, true);
rows.clear();
updateMode("loading", cause);
setPendingState(false, false);
int limit = getReloadLimit();
LoadJob reloadJob;
if (statementForReloading != null) {
reloadJob = new LoadJob(limit, statementForReloading, getParentBrowser(), false);
} else {
reloadJob = new LoadJob(limit, (table instanceof SqlStatementTable)? "" : getAndConditionText(), getParentBrowser(), selectDistinctCheckBox.isSelected());
}
synchronized (this) {
currentLoadJob = reloadJob;
}
getRunnableQueue().add(reloadJob);
}
}
protected Session retrieveCurrentSession() {
return session;
}
/**
* Reload rows from {@link #table}.
*
* @param rows
* to put the rows into
* @param loadJob
* cancellation context
* @param limit
* row number limit
*/
private void reloadRows(ResultSet inputResultSet, String andCond, final List<Row> rows, LoadJob loadJob, int limit, boolean selectDistinct) throws SQLException {
try {
session.setSilent(true);
reloadRows(inputResultSet, andCond, rows, loadJob, limit, selectDistinct, null);
return;
} catch (Throwable e) { // embedded DBMS may throw non-SQLException
Session._log.warn("failed, try another strategy (" + e.getMessage() + ")");
} finally {
session.setSilent(false);
}
Set<String> existingColumnsLowerCase = null;
if (!(table instanceof SqlStatementTable) && statementForReloading == null) {
existingColumnsLowerCase = findColumnsLowerCase(table, session);
}
reloadRows(inputResultSet, andCond, rows, loadJob, limit, selectDistinct, existingColumnsLowerCase);
}
/**
* Finds the columns of a given {@link Table}.
*
* @param table the table
* @param session the statement executor for executing SQL-statements
*/
private Set<String> findColumnsLowerCase(Table table, Session session) {
try {
Set<String> columns = new HashSet<String>();
DatabaseMetaData metaData = session.getMetaData();
Quoting quoting = new Quoting(session);
String defaultSchema = JDBCMetaDataBasedModelElementFinder.getDefaultSchema(session, session.getSchema());
String schema = quoting.unquote(table.getOriginalSchema(defaultSchema));
String tableName = quoting.unquote(table.getUnqualifiedName());
ResultSet resultSet = JDBCMetaDataBasedModelElementFinder.getColumns(session, metaData, schema, tableName, "%", false, null);
while (resultSet.next()) {
String colName = resultSet.getString(4).toLowerCase();
columns.add(colName);
}
resultSet.close();
if (columns.isEmpty()) {
if (session.getMetaData().storesUpperCaseIdentifiers()) {
schema = schema.toUpperCase();
tableName = tableName.toUpperCase();
} else {
schema = schema.toLowerCase();
tableName = tableName.toLowerCase();
}
resultSet = JDBCMetaDataBasedModelElementFinder.getColumns(session, metaData, schema, tableName, "%", false, null);
while (resultSet.next()) {
String colName = resultSet.getString(4).toLowerCase();
columns.add(colName);
}
}
if (columns.isEmpty()) {
return null;
}
return columns;
} catch (Exception e) {
return null;
}
}
/**
* Reload rows from {@link #table}.
*
* @param rows
* to put the rows into
* @param loadJob
* cancellation context
* @param limit
* row number limit
*/
private void reloadRows(ResultSet inputResultSet, String andCond, final List<Row> rows, LoadJob loadJob, int limit, boolean selectDistinct, Set<String> existingColumnsLowerCase) throws SQLException {
if (table instanceof SqlStatementTable || statementForReloading != null) {
try {
session.setSilent(true);
Map<String, List<Row>> rowsMap = new HashMap<String, List<Row>>();
reloadRows(inputResultSet, null, andCond, null, rowsMap, loadJob, limit, false, null, existingColumnsLowerCase);
if (rowsMap.get("") != null) {
rows.addAll(rowsMap.get(""));
}
} finally {
session.setSilent(false);
}
return;
}
List<Row> pRows = parentRows;
if (pRows == null) {
pRows = Collections.singletonList(parentRow);
} else {
pRows = new ArrayList<Row>(pRows);
}
Map<String, Row> rowSet = new HashMap<String, Row>();
loadJob.checkCancellation();
if (parentRows != null) {
beforeReload();
}
noNonDistinctRows = 0;
noDistinctRows = 0;
if (association != null && rowIdSupport.getPrimaryKey(association.source, session).getColumns().isEmpty()) {
loadRowBlocks(inputResultSet, null, andCond, rows, loadJob, limit, selectDistinct, pRows, rowSet, 1, existingColumnsLowerCase);
} else {
if (useInlineViewForResolvingAssociation(session)) {
try {
InlineViewStyle inlineViewStyle = session.getInlineViewStyle();
if (inlineViewStyle != null) {
loadRowBlocks(inputResultSet, inlineViewStyle, andCond, rows, loadJob, limit, selectDistinct, pRows, rowSet, 510, existingColumnsLowerCase);
return;
}
} catch (Throwable e) { // embedded DBMS may throw non-SQLException
Session._log.warn("failed, try another blocking-size (" + e.getMessage() + ")");
}
}
try {
loadRowBlocks(inputResultSet, null, andCond, rows, loadJob, limit, selectDistinct, pRows, rowSet, 510, existingColumnsLowerCase);
return;
} catch (Throwable e) { // embedded DBMS may throw non-SQLException
Session._log.warn("failed, try another blocking-size (" + e.getMessage() + ")");
}
try {
loadRowBlocks(inputResultSet, null, andCond, rows, loadJob, limit, selectDistinct, pRows, rowSet, 300, existingColumnsLowerCase);
return;
} catch (Throwable e) { // embedded DBMS may throw non-SQLException
Session._log.warn("failed, try another blocking-size (" + e.getMessage() + ")");
}
try {
loadRowBlocks(inputResultSet, null, andCond, rows, loadJob, limit, selectDistinct, pRows, rowSet, 100, existingColumnsLowerCase);
return;
} catch (Throwable e) { // embedded DBMS may throw non-SQLException
Session._log.warn("failed, try another blocking-size (" + e.getMessage() + ")");
}
try {
loadRowBlocks(inputResultSet, null, andCond, rows, loadJob, limit, selectDistinct, pRows, rowSet, 40, existingColumnsLowerCase);
return;
} catch (Throwable e) { // embedded DBMS may throw non-SQLException
Session._log.warn("failed, try another blocking-size (" + e.getMessage() + ")");
}
}
loadRowBlocks(inputResultSet, null, andCond, rows, loadJob, limit, selectDistinct, pRows, rowSet, 1, existingColumnsLowerCase);
}
static boolean useInlineViewForResolvingAssociation(Session session) {
return session.dbms.isUseInlineViewsInDataBrowser();
}
private void loadRowBlocks(ResultSet inputResultSet, InlineViewStyle inlineViewStyle, String andCond, final List<Row> rows, LoadJob loadJob, int limit, boolean selectDistinct, List<Row> pRows,
Map<String, Row> rowSet, int NUM_PARENTS, Set<String> existingColumnsLowerCase) throws SQLException {
List<List<Row>> parentBlocks = new ArrayList<List<Row>>();
List<Row> currentBlock = new ArrayList<Row>();
Set<String> regPRows = new HashSet<String>();
Map<Row, Integer> parentRowIndex = new IdentityHashMap<Row, Integer>();
for (int i = 0; i < pRows.size(); ++i) {
parentRowIndex.put(pRows.get(i), i);
}
parentBlocks.add(currentBlock);
BrowserContentPane parentPane = null;
if (getParentBrowser() != null) {
parentPane = getParentBrowser().browserContentPane;
}
for (boolean inClosure: new boolean[] { true, false }) {
boolean firstNonClosure = false;
for (Row pRow : pRows) {
if (parentPane != null) {
if (rowsClosure.currentClosure.contains(new Pair<BrowserContentPane, Row>(parentPane, pRow))) {
if (!inClosure) {
continue;
}
} else {
if (inClosure) {
continue;
}
}
} else if (!inClosure) {
break;
}
if (currentBlock.size() >= NUM_PARENTS || (!inClosure && !firstNonClosure)) {
if (!currentBlock.isEmpty()) {
currentBlock = new ArrayList<Row>();
parentBlocks.add(currentBlock);
}
if (!inClosure) {
firstNonClosure = true;
}
}
currentBlock.add(pRow);
}
}
int parentIndex = 0;
if (!pRows.isEmpty()) for (List<Row> pRowBlockI : parentBlocks) {
List<Row> pRowBlock = pRowBlockI;
Map<String, List<Row>> newBlockRows = new HashMap<String, List<Row>>();
boolean loaded = false;
if (pRowBlock.size() == 1 && pRowBlock.get(0) == null) {
pRowBlock = null;
}
if (session.dbms.getSqlLimitSuffix() != null) {
try {
session.setSilent(true);
reloadRows(inputResultSet, inlineViewStyle, andCond, pRowBlock, newBlockRows, loadJob, limit, false, session.dbms.getSqlLimitSuffix(), existingColumnsLowerCase);
loaded = true;
} catch (Throwable e) { // embedded DBMS may throw non-SQLException
Session._log.warn("failed, try another limit-strategy (" + e.getMessage() + ")");
} finally {
session.setSilent(false);
}
}
if (!loaded) {
try {
session.setSilent(true);
reloadRows(inputResultSet, inlineViewStyle, andCond, pRowBlock, newBlockRows, loadJob, limit, true, null, existingColumnsLowerCase);
loaded = true;
} catch (Throwable e) { // embedded DBMS may throw non-SQLException
Session._log.warn("failed, try another limit-strategy (" + e.getMessage() + ")");
} finally {
session.setSilent(false);
}
if (!loaded) {
try {
session.setSilent(true);
reloadRows(inputResultSet, inlineViewStyle, andCond, pRowBlock, newBlockRows, loadJob, limit, false, null, existingColumnsLowerCase);
} finally {
session.setSilent(false);
}
}
}
if (pRowBlock == null) {
pRowBlock = new ArrayList<Row>();
pRowBlock.add(null);
}
for (Row pRow: pRowBlock) {
loadJob.checkCancellation();
boolean dupParent = false;
if (pRow != null) {
if (regPRows.contains(pRow.nonEmptyRowId)) {
dupParent = true;
}
regPRows.add(pRow.nonEmptyRowId);
}
List<Row> newRows = new ArrayList<Row>();
String rId = pRow == null? "" : pRow.nonEmptyRowId;
if (newBlockRows.get(rId) != null) {
newRows.addAll(newBlockRows.get(rId));
}
sortNewRows(newRows);
if (parentRows != null) {
if (!newRows.isEmpty()) {
Integer i = parentRowIndex.get(pRow);
for (Row r: newRows) {
r.setParentModelIndex(i != null? i : parentIndex);
}
}
++parentIndex;
for (Row row : newRows) {
Row exRow = rowSet.get(row.nonEmptyRowId);
if (!dupParent) {
if (exRow != null) {
++noNonDistinctRows;
} else {
++noDistinctRows;
}
}
if (exRow != null && (selectDistinct || dupParent)) {
addRowToRowLink(pRow, exRow);
} else {
rows.add(row);
addRowToRowLink(pRow, row);
rowSet.put(row.nonEmptyRowId, row);
--limit;
}
}
} else {
rows.addAll(newRows);
limit -= newRows.size();
}
if (limit <= 0) {
if (parentPane != null) {
if (rowsClosure.currentClosure.contains(new Pair<BrowserContentPane, Row>(parentPane, pRow))) {
loadJob.closureLimitExceeded = true;
}
}
break;
}
}
if (limit <= 0) {
break;
}
}
}
private void sortNewRows(List<Row> newRows) {
if (rowsTable != null && rowsTable.getRowSorter() != null) {
List<? extends SortKey> sk = rowsTable.getRowSorter().getSortKeys();
final int col;
final boolean asc;
if (!sk.isEmpty()) {
col = sk.get(0).getColumn();
asc = sk.get(0).getSortOrder() == SortOrder.ASCENDING;
} else {
col = getDefaultSortColumn();
asc = true;
}
if (col >= 0) {
Collections.sort(newRows, new Comparator<Row>() {
@Override
public int compare(Row a, Row b) {
Object va = null;
if (a != null && a.values != null && a.values.length > col) {
va = a.values[col];
}
Object vb = null;
if (b != null && b.values != null && b.values.length > col) {
vb = b.values[col];
}
if (va == null && vb == null) {
return 0;
}
if (va == null) {
return -1;
}
if (vb == null) {
return 1;
}
if (va.getClass().equals(vb.getClass())) {
if (va instanceof Comparable<?>) {
int cmp = ((Comparable<Object>) va).compareTo(vb);
return asc? cmp : -cmp;
}
return 0;
}
int cmp = va.getClass().getName().compareTo(vb.getClass().getName());
return asc? cmp : -cmp;
}
});
}
}
}
/**
* Reload rows from {@link #table}.
*
* @param rows
* to put the rows into
* @param context
* cancellation context
* @param rowCache
* @param allPRows
*/
private void reloadRows(ResultSet inputResultSet, InlineViewStyle inlineViewStyle, String andCond, final List<Row> parentRows, final Map<String, List<Row>> rows, LoadJob loadJob, int limit, boolean useOLAPLimitation,
String sqlLimitSuffix, Set<String> existingColumnsLowerCase) throws SQLException {
reloadRows0(inputResultSet, inlineViewStyle, andCond, parentRows, rows, loadJob, parentRows == null? limit : Math.max(5000, limit), useOLAPLimitation, sqlLimitSuffix, existingColumnsLowerCase);
}
/**
* Gets qualified table name.
*
* @param t the table
* @return qualified name of t
*/
private String qualifiedTableName(Table t, Quoting quoting) {
String schema = t.getSchema("");
if (schema.length() == 0) {
return quoting.requote(t.getUnqualifiedName());
}
return quoting.requote(schema) + "." + quoting.requote(t.getUnqualifiedName());
}
/**
* Reload rows from {@link #table}.
*
* @param rows
* to put the rows into
* @param loadJob
* cancellation context
*/
private void reloadRows0(ResultSet inputResultSet, InlineViewStyle inlineViewStyle, String andCond, final List<Row> parentRows, final Map<String, List<Row>> rows, LoadJob loadJob, int limit, boolean useOLAPLimitation,
String sqlLimitSuffix, Set<String> existingColumnsLowerCase) throws SQLException {
String sql = "Select ";
final Quoting quoting = new Quoting(session);
final Set<String> pkColumnNames = new HashSet<String>();
final Set<String> parentPkColumnNames = new HashSet<String>();
final boolean selectParentPK = association != null && parentRows != null && parentRows.size() > 1;
final Set<Integer> unknownColumnIndexes = new HashSet<Integer>();
int numParentPKColumns = 0;
if (table instanceof SqlStatementTable || statementForReloading != null) {
sql = andCond;
if (!(table instanceof SqlStatementTable)) {
for (Column pk: rowIdSupport.getPrimaryKey(table, session).getColumns()) {
pkColumnNames.add(quoting.requote(pk.name));
}
} else {
table.setColumns(new ArrayList<Column>());
}
} else {
String olapPrefix = "Select ";
String olapSuffix = ") S Where S." + ROWNUMBERALIAS + " <= " + limit;
boolean limitSuffixInSelectClause = sqlLimitSuffix != null &&
(sqlLimitSuffix.toLowerCase().startsWith("top ") || sqlLimitSuffix.toLowerCase().startsWith("first "));
if (sqlLimitSuffix != null && limitSuffixInSelectClause) {
sql += (sqlLimitSuffix.replace("%s", Integer.toString(limit))) + " ";
}
int colI = 1;
boolean f = true;
if (selectParentPK) {
int i = 0;
for (Column column: rowIdSupport.getPrimaryKey(association.source, session).getColumns()) {
String name = quoting.requote(column.name);
sql += (!f ? ", " : "") + "B." + name + " AS B" + i;
olapPrefix += (!f ? ", " : "") + "S.B" + i;
++numParentPKColumns;
++i;
++colI;
f = false;
}
}
int i = 0;
for (Column column : rowIdSupport.getColumns(table, session)) {
String name = quoting.requote(column.name);
if (existingColumnsLowerCase != null && !rowIdSupport.isRowIdColumn(column) && !existingColumnsLowerCase.contains(quoting.unquote(name).toLowerCase())) {
sql += (!f ? ", " : "") + "'?' AS A" + i;
unknownColumnIndexes.add(colI);
} else {
sql += (!f ? ", " : "") + "A." + name + " AS A" + i;
}
olapPrefix += (!f ? ", " : "") + "S.A" + i;
++i;
++colI;
f = false;
}
f = true;
if (selectParentPK) {
int j = 0;
for (Column pk: rowIdSupport.getPrimaryKey(association.source, session).getColumns()) {
parentPkColumnNames.add(quoting.requote(pk.name));
++j;
f = false;
}
}
int j = 0;
for (Column pk: rowIdSupport.getPrimaryKey(table, session).getColumns()) {
pkColumnNames.add(quoting.requote(pk.name));
++j;
f = false;
}
if (useOLAPLimitation) {
sql += ", row_number() over(";
if (useOLAPLimitation) {
sql += "order by -1"; // + orderBy;
}
sql += ") as " + ROWNUMBERALIAS + "";
}
sql += " From ";
if (association != null) {
sql += qualifiedTableName(association.source, quoting) + " B join ";
}
sql += qualifiedTableName(table, quoting) + " A";
if (association != null) {
if (association.reversed) {
sql += " on " + association.getUnrestrictedJoinCondition();
} else {
sql += " on " + SqlUtil.reversRestrictionCondition(association.getUnrestrictedJoinCondition());
}
}
boolean whereExists = false;
if (parentRows != null && !parentRows.isEmpty()) {
if (association != null && parentRows.get(0).rowId.length() == 0) {
throw new SqlException("Missing primary key for table: \"" + Quoting.staticUnquote(association.source.getName()) + "\"\n"
+ "Resolution: define the primary key manually using the data model editor.", "", null);
}
if (parentRows.size() == 1) {
sql += " Where (" + parentRows.get(0).rowId + ")";
} else {
StringBuilder sb = new StringBuilder();
if (inlineViewStyle != null && association != null) {
sb.append(" join ");
List<String> columnNames = new ArrayList<String>();
for (Column pkColumn: rowIdSupport.getPrimaryKey(association.source, session).getColumns()) {
columnNames.add(pkColumn.name);
}
String[] columnNamesAsArray = columnNames.toArray(new String[columnNames.size()]);
sb.append(inlineViewStyle.head(columnNamesAsArray));
int rowNumber = 0;
for (Row parentRow: parentRows) {
if (rowNumber > 0) {
sb.append(inlineViewStyle.separator());
}
sb.append(inlineViewStyle.item(parentRow.primaryKey, columnNamesAsArray, rowNumber));
++rowNumber;
}
sb.append(inlineViewStyle.terminator("C", columnNamesAsArray));
sb.append(" on (");
boolean f2 = true;
for (String pkColumnName: columnNames) {
if (!f2) {
sb.append(" and ");
}
sb.append("B." + pkColumnName + " = " + "C." + pkColumnName);
f2 = false;
}
sb.append(")");
} else {
for (Row parentRow: parentRows) {
if (sb.length() == 0) {
sb.append(" Where ((");
} else {
sb.append(" or (");
}
sb.append(parentRow.rowId).append(")");
}
sb.append(")");
}
sql += sb.toString();
}
whereExists = true;
}
if (andCond.trim().length() > 0) {
sql += (whereExists ? " and" : " Where") + " (" + ConditionEditor.toMultiLine(andCond) + ")";
}
olapPrefix += " From (";
if (useOLAPLimitation) {
sql = olapPrefix + sql + olapSuffix;
}
if (sqlLimitSuffix != null && !limitSuffixInSelectClause) {
sql += " " + (sqlLimitSuffix.replace("%s", Integer.toString(limit)));
}
}
if (sql.length() > 0 || inputResultSet != null) {
final Map<Integer, Integer> pkPosToColumnPos = new HashMap<Integer, Integer>();
if (!(table instanceof SqlStatementTable) && statementForReloading == null) {
List<Column> pks = rowIdSupport.getPrimaryKey(table, session).getColumns();
List<Column> columns = rowIdSupport.getColumns(table, session);
for (int i = 0; i < columns.size(); ++i) {
Column column = columns.get(i);
for (int j = 0; j < pks.size(); ++j) {
if (column.name.equals(pks.get(j).name)) {
pkPosToColumnPos.put(j, i);
break;
}
}
}
}
final int finalNumParentPKColumns = numParentPKColumns;
AbstractResultSetReader reader = new AbstractResultSetReader() {
Map<Integer, Integer> typeCache = new HashMap<Integer, Integer>();
int rowNr = 0;
@Override
public void init(ResultSet resultSet) throws SQLException {
ResultSetMetaData metaData = getMetaData(resultSet);
int columnCount = metaData.getColumnCount();
if (table instanceof SqlStatementTable) {
for (int ci = 1; ci <= columnCount; ++ci) {
table.getColumns().add(new Column(metaData.getColumnLabel(ci), metaData.getColumnTypeName(ci), -1, -1));
}
}
int[] columnTypes = new int[columnCount];
for (int ci = 1 + finalNumParentPKColumns; ci <= columnCount; ++ci) {
if (metaData instanceof MemorizedResultSetMetaData) {
columnTypes[ci - 1 - finalNumParentPKColumns] = ((MemorizedResultSetMetaData) metaData).types[ci - 1];
} else {
columnTypes[ci - 1 - finalNumParentPKColumns] = metaData.getColumnType(ci);
}
}
browserContentCellEditor = new BrowserContentCellEditor(columnTypes);
}
@Override
public void readCurrentRow(ResultSet resultSet) throws SQLException {
int i = 1, vi = 0;
String parentRowId = "";
if (selectParentPK) {
Object v[] = new Object[rowIdSupport.getPrimaryKey(association.source, session).getColumns().size()];
for (Column column: rowIdSupport.getPrimaryKey(association.source, session).getColumns()) {
parentRowId = readRowFromResultSet(parentPkColumnNames, resultSet, i, vi, parentRowId, v, column, null, null, unknownColumnIndexes);
++i;
++vi;
}
} else {
if (parentRows != null && parentRows.size() == 1) {
parentRowId = parentRows.get(0).rowId;
}
}
Map<String, String> pkColumn = new HashMap<String, String>();
Map<String, String> pkColumnValue = new HashMap<String, String>();
Object v[] = new Object[rowIdSupport.getColumns(table, session).size()];
vi = 0;
for (Column column: rowIdSupport.getColumns(table, session)) {
readRowFromResultSet(pkColumnNames, resultSet, i, vi, "", v, column, pkColumn, pkColumnValue, unknownColumnIndexes);
++i;
++vi;
}
String rowId = "";
String[] primaryKey = null;
PrimaryKey primaryKeys = rowIdSupport.getPrimaryKey(table, session);
if (primaryKeys != null && resultSetType == null) {
int pkPos = 0;
primaryKey = new String[primaryKeys.getColumns().size()];
for (Column column : primaryKeys.getColumns()) {
if (rowId.length() > 0) {
rowId += " and ";
}
rowId += pkColumn.get(column.name);
Integer colPos = pkPosToColumnPos.get(pkPos);
if (colPos != null) {
primaryKey[pkPos] = pkColumnValue.get(column.name);
}
++pkPos;
}
} else {
rowId = Integer.toString(++rowNr);
}
List<Row> cRows = rows.get(parentRowId);
if (cRows == null) {
cRows = new ArrayList<Row>();
rows.put(parentRowId, cRows);
}
cRows.add(new Row(rowId, primaryKey, v));
}
private String readRowFromResultSet(final Set<String> pkColumnNames, ResultSet resultSet, int i, int vi, String rowId, Object[] v, Column column, Map<String, String> pkColumn, Map<String, String> pkColumnValue, Set<Integer> unknownColumnIndexes)
throws SQLException {
Object value = "";
if (unknownColumnIndexes.contains(i)) {
value = new UnknownValue() {
@Override
public String toString() {
return "?";
}
};
} else {
int type = SqlUtil.getColumnType(resultSet, getMetaData(resultSet), i, typeCache);
Object lob = null;
if (type == 0) {
lob = resultSet.getObject(i);
}
if (type == Types.BLOB || type == Types.CLOB || type == Types.NCLOB || type == Types.SQLXML
|| (type == 0 &&
(lob instanceof Blob || lob instanceof Clob || lob instanceof SQLXML)
)) {
Object object = resultSet.getObject(i);
if (object == null || resultSet.wasNull()) {
value = null;
} else {
Object lobValue = toLobRender(object);
if (lobValue != null) {
value = lobValue;
}
}
} else {
CellContentConverter cellContentConverter = getCellContentConverter(resultSet, session, session.dbms);
Object o;
try {
o = cellContentConverter.getObject(resultSet, i);
if (o instanceof byte[]) {
final long length = ((byte[]) o).length;
o = new LobValue() {
@Override
public String toString() {
return "<Blob> " + length + " bytes";
}
};
}
} catch (Throwable e) {
o = "ERROR: " + e.getClass().getName() + ": " + e.getMessage();
}
boolean isPK = false;
if (pkColumnNames.isEmpty()) {
isPK = type != Types.BLOB && type != Types.CLOB && type != Types.DATALINK && type != Types.JAVA_OBJECT && type != Types.NCLOB
&& type != Types.NULL && type != Types.OTHER && type != Types.REF && type != Types.SQLXML && type != Types.STRUCT;
}
if (pkColumnNames.contains(quoting.requote(column.name)) || isPK) {
String cVal = cellContentConverter.toSql(o);
String pkValue = "B." + quoting.requote(column.name) + ("null".equalsIgnoreCase(cVal)? " is null" : ("=" + cVal));
if (pkColumn != null) {
pkColumn.put(column.name, pkValue);
}
if (pkColumnValue != null) {
pkColumnValue.put(column.name, cVal);
}
rowId += (rowId.length() == 0 ? "" : " and ") + pkValue;
}
if (o == null || resultSet.wasNull()) {
value = null;
}
if (o != null) {
value = o;
}
}
}
v[vi] = value;
return rowId;
}
};
if (inputResultSet != null) {
reader.init(inputResultSet);
while (inputResultSet.next()) {
reader.readCurrentRow(inputResultSet);
}
inputResultSet.close();
}
else {
session.executeQuery(sql, reader, null, loadJob, limit);
}
}
}
/**
* True if row-limit is exceeded.
*/
private boolean isLimitExceeded = false;
private boolean isClosureLimitExceeded = false;
/**
* Show single row in special view?
*/
protected boolean noSingleRowDetailsView = false;
protected String singleRowDetailsViewTitel = "Single Row Details";
/**
* Parent having row-limit exceeded.
*/
private RowBrowser parentWithExceededLimit() {
RowBrowser parent = getParentBrowser();
while (parent != null) {
if (parent.browserContentPane.isLimitExceeded) {
return parent;
}
parent = parent.browserContentPane.getParentBrowser();
}
return null;
}
public static class TableModelItem {
public int blockNr;
public Object value;
@Override
public String toString() {
if (value instanceof Double) {
return SqlUtil.toString((Double) value);
}
if (value instanceof BigDecimal) {
return SqlUtil.toString((BigDecimal) value);
}
return String.valueOf(value);
}
}
private int lastLimit;
private boolean lastLimitExceeded;
private boolean lastClosureLimitExceeded;
/**
* Updates the model of the {@link #rowsTable}.
*
* @param limit
* row limit
* @param limitExceeded
*/
private void updateTableModel() {
updateTableModel(lastLimit, lastLimitExceeded, lastClosureLimitExceeded);
}
/**
* Updates the model of the {@link #rowsTable}.
*
* @param limit
* row limit
* @param limitExceeded
*/
private void updateTableModel(int limit, boolean limitExceeded, boolean closureLimitExceeded) {
lastLimit = limit;
lastLimitExceeded = limitExceeded;
lastClosureLimitExceeded = closureLimitExceeded;
pkColumns.clear();
List<Column> columns = rowIdSupport.getColumns(table, session);
String[] columnNames = new String[columns.size()];
final Set<String> pkColumnNames = new HashSet<String>();
if (rowIdSupport.getPrimaryKey(table, session) != null) {
for (Column pk : rowIdSupport.getPrimaryKey(table, session).getColumns()) {
pkColumnNames.add(pk.name);
}
}
for (int i = 0; i < columnNames.length; ++i) {
columnNames[i] = columns.get(i).name;
if ("".equals(columnNames[i])) {
columnNames[i] = " ";
}
if (pkColumnNames.contains(columnNames[i])) {
pkColumns.add(i);
}
if (columnNames[i] == null) {
if (alternativeColumnLabels != null && i < alternativeColumnLabels.length) {
columnNames[i] = alternativeColumnLabels[i];
}
}
}
fkColumns.clear();
final Set<String> fkColumnNames = new HashSet<String>();
for (Association a: table.associations) {
if (a.isInsertDestinationBeforeSource()) {
Map<Column, Column> m = a.createSourceToDestinationKeyMapping();
for (Column fkColumn: m.keySet()) {
fkColumnNames.add(fkColumn.name);
}
}
}
if (rowIdSupport.getPrimaryKey(table, session) != null) {
for (Column pk : rowIdSupport.getPrimaryKey(table, session).getColumns()) {
pkColumnNames.add(pk.name);
}
}
for (int i = 0; i < columnNames.length; ++i) {
if (fkColumnNames.contains(columnNames[i])) {
fkColumns.add(i);
}
}
DefaultTableModel dtm;
singleRowDetailsView = null;
singleRowViewScrollPaneContainer.setVisible(false);
rowsTableContainerPanel.setVisible(true);
boolean noFilter = true;
int rn = 0;
if (rows.size() != 1 || isEditMode || noSingleRowDetailsView) {
noFilter = false;
Map<String, Integer> columnNameMap = new HashMap<String, Integer>();
for (int i = 0; i < columns.size(); ++i) {
columnNameMap.put(columnNames[i], i);
}
String[] uqColumnNames = new String[columnNames.length];
for (int i = 0; i < uqColumnNames.length; ++i) {
if (columnNames[i] != null) {
uqColumnNames[i] = Quoting.staticUnquote(columnNames[i]);
}
}
dtm = new DefaultTableModel(uqColumnNames, 0) {
@Override
public boolean isCellEditable(int row, int column) {
Row r = null;
if (row < rows.size()) {
r = rows.get(row);
}
Table type = getResultSetTypeForColumn(column);
if (isEditMode && r != null && (r.rowId != null && !r.rowId.isEmpty()) && browserContentCellEditor.isEditable(type, row, column, r.values[column]) && isPKComplete(type, r)) {
return !rowIdSupport.getPrimaryKey(type, session).getColumns().isEmpty();
}
return false;
}
@Override
public void setValueAt(Object aValue, int row, int column) {
String text = aValue.toString();
Row theRow = null;
if (row < rows.size()) {
theRow = rows.get(row);
Object content = browserContentCellEditor.textToContent(row, column, text, theRow.values[column]);
if (content != BrowserContentCellEditor.INVALID) {
if (!browserContentCellEditor.cellContentToText(row, column, theRow.values[column]).equals(text)) {
Table type = getResultSetTypeForColumn(column);
if (resultSetType != null) {
theRow = createRowWithNewID(theRow, type);
}
Object oldContent = theRow.values[column];
theRow.values[column] = content;
final String updateStatement = SQLDMLBuilder.buildUpdate(type, theRow, false, column, session);
theRow.values[column] = oldContent;
updateMode("updating", null);
getRunnableQueue().add(new RunnableWithPriority() {
private Exception exception;
@Override
public void run() {
final Object context = new Object();
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
CancellationHandler.cancel(context);
}
};
cancelLoadButton.addActionListener(listener);
try {
session.execute(updateStatement, context);
} catch (Exception e) {
exception = e;
} finally {
CancellationHandler.reset(context);
cancelLoadButton.removeActionListener(listener);
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (exception != null && !(exception instanceof CancellationException)) {
UIUtil.showException(BrowserContentPane.this, "Error", exception);
updateMode("table", null);
} else {
reloadRows();
}
}
});
}
@Override
public int getPriority() {
return 50;
}
});
}
}
}
}
};
boolean stripHour[] = new boolean[columns.size()];
final String HOUR = " 00:00:00.0";
for (int i = 0; i < columns.size(); ++i) {
stripHour[i] = true;
for (Row row : rows) {
Object value = row.values[i];
if (value == null) {
continue;
}
if (!(value instanceof java.sql.Date) && !(value instanceof java.sql.Timestamp)) {
stripHour[i] = false;
break;
}
String asString = value.toString();
if (asString.endsWith(HOUR)) {
continue;
}
stripHour[i] = false;
break;
}
}
for (Row row : rows) {
Object[] rowData = new Object[columns.size()];
for (int i = 0; i < columns.size(); ++i) {
rowData[i] = row.values[i];
if (rowData[i] instanceof PObjectWrapper) {
rowData[i] = ((PObjectWrapper) rowData[i]).getValue();
}
if (rowData[i] == null) {
rowData[i] = UIUtil.NULL;
} else if (rowData[i] instanceof UnknownValue) {
rowData[i] = UNKNOWN;
}
if (stripHour[i] && (rowData[i] instanceof java.sql.Date || rowData[i] instanceof java.sql.Timestamp)) {
String asString = rowData[i].toString();
rowData[i] = asString.substring(0, asString.length() - HOUR.length());
}
}
if (tableContentViewFilter != null) {
tableContentViewFilter.filter(rowData, columnNameMap);
}
for (int i = 0; i < columns.size(); ++i) {
TableModelItem item = new TableModelItem();
item.blockNr = row.getParentModelIndex();
item.value = rowData[i];
rowData[i] = item;
}
dtm.addRow(rowData);
if (++rn >= limit) {
break;
}
}
//set the editor as default on every column
JTextField textField = new JTextField();
textField.setBorder(new LineBorder(Color.black));
DefaultCellEditor anEditor = new DefaultCellEditor(textField) {
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
if (table != rowsTable) {
column = table.convertColumnIndexToModel(column);
if (column == 0) {
return null;
}
int h = row;
row = column - 1;
column = h;
}
if (row < rows.size()) {
Row r = rows.get(rowsTable.getRowSorter().convertRowIndexToModel(row));
int convertedColumnIndex = rowsTable.convertColumnIndexToModel(column);
if (r != null) {
value = browserContentCellEditor.cellContentToText(row, convertedColumnIndex, r.values[convertedColumnIndex]);
}
}
return super.getTableCellEditorComponent(table, value, isSelected, row, column);
}
};
anEditor.setClickCountToStart(1);
for (int i = 0; i < rowsTable.getColumnCount(); i++) {
rowsTable.setDefaultEditor(rowsTable.getColumnClass(i), anEditor);
}
List<? extends SortKey> sortKeys = new ArrayList(rowsTable.getRowSorter().getSortKeys());
List<Object> filterContent = new ArrayList<Object>();
if (filterHeader != null) {
try {
for (int i = 0; i < rowsTable.getColumnCount(); ++i) {
filterContent.add(filterHeader.getFilterEditor(i).getContent());
}
} catch (Exception e) {
// ignore
}
}
rowsTable.setModel(dtm);
rowsTable.getSelectionModel().clearSelection();
rowsTable.setRowHeight(initialRowHeight);
noRowsFoundPanel.setVisible(dtm.getRowCount() == 0 && getAndConditionText().length() > 0);
final int defaultSortColumn = getDefaultSortColumn();
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(dtm) {
@Override
protected boolean useToString(int column) {
return false;
}
@Override
public void toggleSortOrder(int column) {
if (association != null && association.isInsertDestinationBeforeSource()) {
return;
}
List<? extends SortKey> sortKeys = getSortKeys();
if (sortKeys.size() > 0) {
if (sortKeys.get(0).getSortOrder() == SortOrder.DESCENDING) {
List<SortKey> sk = new ArrayList<SortKey>();
if (defaultSortColumn >= 0) {
sk.add(new SortKey(defaultSortColumn, SortOrder.ASCENDING));
}
setSortKeys(sk);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
sortChildren();
}
});
return;
}
}
super.toggleSortOrder(column);
}
@Override
public Comparator<?> getComparator(int n) {
List<? extends SortKey> sortKeys = super.getSortKeys();
final boolean desc = sortKeys.size() > 0 && sortKeys.get(0).getSortOrder() == SortOrder.DESCENDING;
return new Comparator<Object>() {
@SuppressWarnings("unchecked")
@Override
public int compare(Object o1, Object o2) {
RowSorter pSorter = null;
RowBrowser pb = getParentBrowser();
if (pb != null) {
if (pb.browserContentPane != null) {
if (pb.browserContentPane.rowsTable != null) {
pSorter = pb.browserContentPane.rowsTable.getRowSorter();
}
}
}
if (o1 instanceof TableModelItem && o2 instanceof TableModelItem) {
int b1 = ((TableModelItem) o1).blockNr;
int b2 = ((TableModelItem) o2).blockNr;
if (pSorter != null) {
int b;
b = b1 < pSorter.getModelRowCount()? pSorter.convertRowIndexToView(b1) : -1;
if (b < 0) {
b = b1 + Integer.MAX_VALUE / 2;
}
b1 = b;
b = b2 < pSorter.getModelRowCount()? pSorter.convertRowIndexToView(b2) : -1;
if (b < 0) {
b = b2 + Integer.MAX_VALUE / 2;
}
b2 = b;
}
if (b1 != b2) {
return (b1 - b2) * (desc? -1 : 1);
}
}
if (o1 instanceof TableModelItem) {
o1 = ((TableModelItem) o1).value;
}
if (o2 instanceof TableModelItem) {
o2 = ((TableModelItem) o2).value;
}
if (o1 == null && o2 == null) {
return 0;
}
if (o1 == null) {
return -1;
}
if (o2 == null) {
return 1;
}
if (o1.getClass().equals(o2.getClass())) {
if (o1 instanceof Comparable<?>) {
return ((Comparable<Object>) o1).compareTo(o2);
}
return 0;
}
return o1.getClass().getName().compareTo(o2.getClass().getName());
}
};
}
};
sorter.addRowSorterListener(new RowSorterListener() {
@Override
public void sorterChanged(RowSorterEvent e) {
if (e.getType() == RowSorterEvent.Type.SORTED) {
List<RowBrowser> chBrs = getChildBrowsers();
if (chBrs != null) {
for (RowBrowser chBr: chBrs) {
if (chBr.browserContentPane != null) {
if (chBr.browserContentPane.rowsTable != null) {
final RowSorter chSorter = chBr.browserContentPane.rowsTable.getRowSorter();
if (chSorter instanceof TableRowSorter) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
((TableRowSorter) chSorter).sort();
}
});
}
}
}
}
}
}
}
});
rowsTable.setRowSorter(sorter);
try {
if (!sortKeys.isEmpty()) {
rowsTable.getRowSorter().setSortKeys(sortKeys);
} else {
List<SortKey> sk = new ArrayList<SortKey>();
if (defaultSortColumn >= 0) {
sk.add(new SortKey(defaultSortColumn, SortOrder.ASCENDING));
}
rowsTable.getRowSorter().setSortKeys(sk);
}
if (filterHeader != null) {
for (int i = 0; i < rowsTable.getColumnCount(); ++i) {
filterHeader.getFilterEditor(i).setContent(filterContent.get(i));
}
}
} catch (Exception e) {
// ignore
}
} else {
final boolean deselect = !currentSelectedRowCondition.equals("")
&& currentSelectedRowCondition.equals(getAndConditionText())
&& rows.size() == 1;
singleRowDetailsView = new DetailsView(Collections.singletonList(rows.get(0)), 1, dataModel, BrowserContentPane.this.table, 0, null, false, false, rowIdSupport, deselect, session) {
@Override
protected void onRowChanged(int row) {
}
@Override
protected void onClose() {
}
@Override
protected void onSelectRow(Row row) {
}
};
singleRowDetailsView.setSortColumns(sortColumnsCheckBox.isSelected());
dtm = new DefaultTableModel(new String[] { singleRowDetailsViewTitel }, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
for (Row row : rows) {
dtm.addRow(new Object[] { row });
if (++rn >= limit) {
break;
}
}
rowsTable.setModel(dtm);
JPanel detailsPanel = singleRowDetailsView.getDetailsPanel();
GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.weightx = 1;
gridBagConstraints.weighty = 0;
gridBagConstraints.insets = new Insets(2, 4, 2, 4);
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
singleRowViewContainterPanel.removeAll();
singleRowViewContainterPanel.add(detailsPanel, gridBagConstraints);
singleRowViewScrollPaneContainer.setVisible(true);
rowsTableContainerPanel.setVisible(false);
deselectButton.setVisible(deselect);
}
adjustRowTableColumnsWidth();
if (sortColumnsCheckBox.isSelected()) {
TableColumnModel cm = rowsTable.getColumnModel();
for (int a = 0; a < rowsTable.getColumnCount(); ++a) {
for (int b = a + 1; b < rowsTable.getColumnCount(); ++b) {
if (cm.getColumn(a).getHeaderValue().toString().compareToIgnoreCase(cm.getColumn(b).getHeaderValue().toString()) > 0) {
cm.moveColumn(b, a);
}
}
}
}
rowsTable.setIntercellSpacing(new Dimension(0, 0));
Set<BrowserContentPane> browserInClosure = new HashSet<BrowserContentPane>();
for (Pair<BrowserContentPane, Row> rid: rowsClosure.currentClosure) {
browserInClosure.add(rid.a);
}
updateRowsCountLabel(browserInClosure);
int nndr = noNonDistinctRows;
if (noDistinctRows + noNonDistinctRows >= limit) {
--nndr;
}
selectDistinctCheckBox.setVisible(nndr > 0);
selectDistinctCheckBox.setText("select distinct (-" + nndr + " row" + (nndr == 1? "" : "s") + ")");
if (filterHeader != null) {
if (rowsTable.getRowSorter() != null && rowsTable.getRowSorter().getViewRowCount() == 0) {
filterHeader.setTable(null);
filterHeader = null;
adjustRowTableColumnsWidth();
}
}
if (isTableFilterEnabled && !noFilter) {
if (filterHeader == null) {
filterHeader = new TableFilterHeader();
filterHeader.setAutoChoices(AutoChoices.ENABLED);
filterHeader.setTable(rowsTable);
filterHeader.setMaxVisibleRows(20);
try {
for (int i = 0; i < rowsTable.getColumnCount(); ++i) {
filterHeader.getFilterEditor(i).setChoicesComparator(new Comparator<Object>() {
@SuppressWarnings("unchecked")
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof TableModelItem) {
o1 = ((TableModelItem) o1).value;
}
if (o2 instanceof TableModelItem) {
o2 = ((TableModelItem) o2).value;
}
if (o1 == null && o2 == null) {
return 0;
}
if (o1 == null) {
return -1;
}
if (o2 == null) {
return 1;
}
if (o1.getClass().equals(o2.getClass())) {
if (o1 instanceof Comparable<?>) {
return ((Comparable<Object>) o1).compareTo(o2);
}
return 0;
}
return o1.getClass().getName().compareTo(o2.getClass().getName());
}
});
}
}
catch (Exception e) {
// ignore
}
}
} else {
if (filterHeader != null) {
filterHeader.setTable(null);
filterHeader = null;
}
}
isLimitExceeded = limitExceeded;
isClosureLimitExceeded = closureLimitExceeded;
appendClosure();
}
public void updateRowsCountLabel(Set<BrowserContentPane> browserInClosure) {
int limit = lastLimit;
boolean limitExceeded = lastLimitExceeded;
boolean closureLimitExceeded = lastClosureLimitExceeded;
int size = rows.size();
if (size > limit) {
size = limit;
}
rowsCount.setText((limitExceeded ? " more than " : " ") + size + " row" + (size != 1 ? "s" : ""));
RowBrowser theParentWithExceededLimit = parentWithExceededLimit();
boolean cle = closureLimitExceeded;
boolean cleRelevant = true;
// if (theParentWithExceededLimit != null && theParentWithExceededLimit.browserContentPane.isClosureLimitExceeded) {
// cle = true;
// }
if (rowsClosure.parentPath.contains(this) || rowsClosure.currentClosureRowIDs.isEmpty()) {
cleRelevant = false;
} else if (getParentBrowser() != null) {
BrowserContentPane parent = getParentBrowser().browserContentPane;
if (!browserInClosure.contains(parent)) {
cleRelevant = false;
}
}
boolean bold = false;
if (limitExceeded || theParentWithExceededLimit != null) {
if (cle || !cleRelevant) {
rowsCount.setForeground(Color.RED);
bold = true;
} else {
rowsCount.setForeground(new Color(140, 0, 0));
}
} else {
rowsCount.setForeground(new JLabel().getForeground());
}
if (bold) {
rowsCount.setFont(rowsCount.getFont().deriveFont(rowsCount.getFont().getStyle() | Font.BOLD));
} else {
rowsCount.setFont(rowsCount.getFont().deriveFont(rowsCount.getFont().getStyle() & ~Font.BOLD));
}
if (cle && cleRelevant) {
rowsCount.setToolTipText("row selection incomplete");
} else if (!limitExceeded && theParentWithExceededLimit != null) {
rowsCount.setToolTipText("potentially incomplete because " + theParentWithExceededLimit.internalFrame.getTitle() + " exceeded row limit");
} else {
rowsCount.setToolTipText(null);
}
}
private int getDefaultSortColumn() {
if (table == null || table instanceof SqlStatementTable || getQueryBuilderDialog() == null /* SQL Console */) {
return -1;
}
if (association != null && association.isInsertDestinationBeforeSource()) {
return table.getColumns().size() - 1;
}
if (table.primaryKey.getColumns() != null && table.primaryKey.getColumns().size() > 0) {
Column pk = table.primaryKey.getColumns().get(0);
for (int i = 0; i < table.getColumns().size(); ++i) {
if (table.getColumns().get(i).equals(pk)) {
return i;
}
}
}
return 0;
}
private TableFilterHeader filterHeader;
protected Row createRowWithNewID(Row theRow, Table type) {
CellContentConverter cellContentConverter = new CellContentConverter(null, session, session.dbms);
String rowId = "";
PrimaryKey primaryKeys = type.primaryKey;
for (Column pkColumn : primaryKeys.getColumns()) {
List<Column> cols = type.getColumns();
int colSize = cols.size();
for (int i = 0; i < colSize; ++i) {
Column column = cols.get(i);
if (column != null && pkColumn.name.equals(column.name)) {
if (rowId.length() > 0) {
rowId += " and ";
}
rowId += pkColumn.name + "=" + cellContentConverter.toSql(theRow.values[i]);
break;
}
}
}
return new Row(rowId, theRow.primaryKey, theRow.values);
}
public void adjustRowTableColumnsWidth() {
DefaultTableModel dtm = (DefaultTableModel) rowsTable.getModel();
int MAXLINES = 2000;
if (rowsTable.getColumnCount() > 0) {
MAXLINES = Math.max(10 * MAXLINES / rowsTable.getColumnCount(), 10);
}
DefaultTableCellRenderer defaultTableCellRenderer = new DefaultTableCellRenderer();
for (int i = 0; i < rowsTable.getColumnCount(); i++) {
TableColumn column = rowsTable.getColumnModel().getColumn(i);
int width = ((int) (Desktop.BROWSERTABLE_DEFAULT_WIDTH * getLayoutFactor()) - 18) / rowsTable.getColumnCount();
Component comp = defaultTableCellRenderer.getTableCellRendererComponent(rowsTable, column.getHeaderValue(), false, false, 0, i);
int pw = comp.getPreferredSize().width;
if (pw < 100) {
pw = (pw * 110) / 100 + 2;
}
width = Math.max(width, pw);
int line = 0;
for (; line < rowsTable.getRowCount(); ++line) {
comp = rowsTable.getCellRenderer(line, i).getTableCellRendererComponent(rowsTable, dtm.getValueAt(line, i), false, false, line, i);
width = Math.max(width, comp.getPreferredSize().width + 24);
if (line > MAXLINES) {
break;
}
}
Object maxValue = null;
int maxValueLength = 0;
for (; line < rowsTable.getRowCount(); ++line) {
Object value = dtm.getValueAt(line, i);
if (value != null) {
int valueLength = value.toString().length();
if (maxValue == null || maxValueLength < valueLength) {
maxValue = value;
maxValueLength = valueLength;
}
}
if (line > 4 * MAXLINES) {
break;
}
}
if (maxValue != null) {
comp = rowsTable.getCellRenderer(line, i).getTableCellRendererComponent(rowsTable, maxValue, false, false, line, i);
int maxValueWidth = comp.getPreferredSize().width + 16;
if (maxValueWidth > width) {
width = maxValueWidth;
}
}
column.setPreferredWidth(width);
}
}
protected int maxColumnWidth = 400;
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed"
// <editor-fold defaultstate="collapsed"
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
andCondition = new javax.swing.JComboBox();
openEditorLabel = new javax.swing.JLabel();
pendingNonpendingPanel = new javax.swing.JPanel();
cardPanel = new javax.swing.JPanel();
tablePanel = new javax.swing.JPanel();
jLayeredPane1 = new javax.swing.JLayeredPane();
jPanel6 = new javax.swing.JPanel();
sortColumnsCheckBox = new javax.swing.JCheckBox();
rowsCount = new javax.swing.JLabel();
selectDistinctCheckBox = new javax.swing.JCheckBox();
loadingPanel = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
cancelLoadButton = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jPanel13 = new javax.swing.JPanel();
loadingCauseLabel = new javax.swing.JLabel();
loadingLabel = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
rowsTableContainerPanel = new javax.swing.JPanel();
jLayeredPane2 = new javax.swing.JLayeredPane();
rowsTableScrollPane = new javax.swing.JScrollPane();
rowsTable = new javax.swing.JTable();
noRowsFoundPanel = new javax.swing.JPanel();
jLabel9 = new javax.swing.JLabel();
removeConditionButton = new javax.swing.JButton();
singleRowViewScrollPaneContainer = new javax.swing.JPanel();
singleRowViewScrollPane = new javax.swing.JScrollPane();
singleRowViewScrollContentPanel = new javax.swing.JPanel();
singleRowViewContainterPanel = new javax.swing.JPanel();
jPanel11 = new javax.swing.JPanel();
jLabel7 = new javax.swing.JLabel();
jPanel12 = new javax.swing.JPanel();
deselectButton = new javax.swing.JButton();
jPanel5 = new javax.swing.JPanel();
jLabel10 = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
jLabel8 = new javax.swing.JLabel();
jPanel8 = new javax.swing.JPanel();
jLabel11 = new javax.swing.JLabel();
menuPanel = new javax.swing.JPanel();
jPanel7 = new javax.swing.JPanel();
loadButton = new javax.swing.JButton();
onPanel = new javax.swing.JPanel();
on = new javax.swing.JLabel();
joinPanel = new javax.swing.JPanel();
join = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jPanel10 = new javax.swing.JPanel();
from = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
andLabel = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jPanel3 = new javax.swing.JPanel();
rrPanel = new javax.swing.JPanel();
relatedRowsPanel = new javax.swing.JPanel();
relatedRowsLabel = new javax.swing.JLabel();
sqlPanel = new javax.swing.JPanel();
sqlLabel1 = new javax.swing.JLabel();
jPanel9 = new javax.swing.JPanel();
dropA = new javax.swing.JLabel();
dropB = new javax.swing.JLabel();
openEditorButton = new javax.swing.JButton();
andCondition.setEditable(true);
andCondition.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
openEditorLabel.setText(" And ");
setLayout(new java.awt.GridBagLayout());
pendingNonpendingPanel.setLayout(new java.awt.CardLayout());
cardPanel.setLayout(new java.awt.CardLayout());
tablePanel.setLayout(new java.awt.GridBagLayout());
jLayeredPane1.setLayout(new java.awt.GridBagLayout());
jPanel6.setLayout(new java.awt.GridBagLayout());
sortColumnsCheckBox.setText("sort columns ");
sortColumnsCheckBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sortColumnsCheckBoxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 0);
jPanel6.add(sortColumnsCheckBox, gridBagConstraints);
rowsCount.setText("jLabel3");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
jPanel6.add(rowsCount, gridBagConstraints);
selectDistinctCheckBox.setSelected(true);
selectDistinctCheckBox.setText("select distinct (-100 rows)");
selectDistinctCheckBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectDistinctCheckBoxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
jPanel6.add(selectDistinctCheckBox, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTH;
jLayeredPane1.add(jPanel6, gridBagConstraints);
loadingPanel.setOpaque(false);
loadingPanel.setLayout(new java.awt.GridBagLayout());
jPanel1.setBackground(new Color(255,255,255,150));
jPanel1.setLayout(new java.awt.GridBagLayout());
cancelLoadButton.setText("Cancel");
cancelLoadButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelLoadButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jPanel1.add(cancelLoadButton, gridBagConstraints);
jLabel2.setText(" ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.weightx = 1.0;
jPanel1.add(jLabel2, gridBagConstraints);
jPanel13.setOpaque(false);
jPanel13.setLayout(new java.awt.GridBagLayout());
loadingCauseLabel.setFont(new java.awt.Font("DejaVu Sans", 0, 14)); // NOI18N
loadingCauseLabel.setForeground(new java.awt.Color(141, 16, 16));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jPanel13.add(loadingCauseLabel, gridBagConstraints);
loadingLabel.setFont(new java.awt.Font("DejaVu Sans", 1, 14)); // NOI18N
loadingLabel.setForeground(new java.awt.Color(141, 16, 16));
loadingLabel.setText("loading... ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jPanel13.add(loadingLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(8, 8, 8, 8);
jPanel1.add(jPanel13, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 2, 4);
loadingPanel.add(jPanel1, gridBagConstraints);
jLayeredPane1.setLayer(loadingPanel, javax.swing.JLayeredPane.MODAL_LAYER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridheight = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
jLayeredPane1.add(loadingPanel, gridBagConstraints);
jPanel2.setLayout(new java.awt.GridBagLayout());
rowsTableContainerPanel.setLayout(new java.awt.GridBagLayout());
jLayeredPane2.setLayout(new java.awt.GridBagLayout());
rowsTableScrollPane.setWheelScrollingEnabled(false);
rowsTable.setAutoCreateRowSorter(true);
rowsTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
rowsTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
rowsTableScrollPane.setViewportView(rowsTable);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jLayeredPane2.add(rowsTableScrollPane, gridBagConstraints);
noRowsFoundPanel.setOpaque(false);
noRowsFoundPanel.setLayout(new java.awt.GridBagLayout());
jLabel9.setText("No rows found.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTH;
gridBagConstraints.weighty = 1.0;
noRowsFoundPanel.add(jLabel9, gridBagConstraints);
removeConditionButton.setText("Remove condition");
removeConditionButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeConditionButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.weighty = 1.0;
noRowsFoundPanel.add(removeConditionButton, gridBagConstraints);
jLayeredPane2.setLayer(noRowsFoundPanel, javax.swing.JLayeredPane.PALETTE_LAYER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jLayeredPane2.add(noRowsFoundPanel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
rowsTableContainerPanel.add(jLayeredPane2, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jPanel2.add(rowsTableContainerPanel, gridBagConstraints);
singleRowViewScrollPaneContainer.setLayout(new java.awt.GridBagLayout());
singleRowViewScrollPane.setWheelScrollingEnabled(false);
singleRowViewScrollContentPanel.setLayout(new java.awt.GridBagLayout());
singleRowViewContainterPanel.setBackground(java.awt.Color.white);
singleRowViewContainterPanel.setBorder(new javax.swing.border.LineBorder(java.awt.Color.gray, 1, true));
singleRowViewContainterPanel.setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.weightx = 1.0;
singleRowViewScrollContentPanel.add(singleRowViewContainterPanel, gridBagConstraints);
jPanel11.setBackground(new java.awt.Color(228, 228, 232));
jPanel11.setLayout(new java.awt.GridBagLayout());
jLabel7.setBackground(new java.awt.Color(200, 200, 200));
jLabel7.setForeground(new java.awt.Color(1, 0, 0));
jLabel7.setText(" Single Row Details ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
jPanel11.add(jLabel7, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
singleRowViewScrollContentPanel.add(jPanel11, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.weighty = 1.0;
singleRowViewScrollContentPanel.add(jPanel12, gridBagConstraints);
deselectButton.setText("Deselect Row");
deselectButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deselectButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
singleRowViewScrollContentPanel.add(deselectButton, gridBagConstraints);
singleRowViewScrollPane.setViewportView(singleRowViewScrollContentPanel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
singleRowViewScrollPaneContainer.add(singleRowViewScrollPane, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jPanel2.add(singleRowViewScrollPaneContainer, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jLayeredPane1.add(jPanel2, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
tablePanel.add(jLayeredPane1, gridBagConstraints);
cardPanel.add(tablePanel, "table");
jPanel5.setLayout(new java.awt.GridBagLayout());
jLabel10.setFont(new java.awt.Font("DejaVu Sans", 1, 14)); // NOI18N
jLabel10.setForeground(new java.awt.Color(141, 16, 16));
jLabel10.setText("Error");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(8, 8, 8, 0);
jPanel5.add(jLabel10, gridBagConstraints);
cardPanel.add(jPanel5, "error");
jPanel4.setLayout(new java.awt.GridBagLayout());
jLabel8.setFont(new java.awt.Font("DejaVu Sans", 1, 14)); // NOI18N
jLabel8.setForeground(new java.awt.Color(141, 16, 16));
jLabel8.setText("Cancelled");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(8, 8, 8, 0);
jPanel4.add(jLabel8, gridBagConstraints);
cardPanel.add(jPanel4, "cancelled");
pendingNonpendingPanel.add(cardPanel, "nonpending");
jPanel8.setLayout(new java.awt.GridBagLayout());
jLabel11.setFont(new java.awt.Font("DejaVu Sans", 1, 14)); // NOI18N
jLabel11.setForeground(new java.awt.Color(141, 16, 16));
jLabel11.setText("pending...");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(8, 8, 8, 0);
jPanel8.add(jLabel11, gridBagConstraints);
pendingNonpendingPanel.add(jPanel8, "pending");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(pendingNonpendingPanel, gridBagConstraints);
menuPanel.setLayout(new java.awt.GridBagLayout());
jPanel7.setLayout(new java.awt.GridBagLayout());
loadButton.setText(" Reload ");
loadButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
loadButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
jPanel7.add(loadButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 8;
gridBagConstraints.gridwidth = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
menuPanel.add(jPanel7, gridBagConstraints);
onPanel.setMinimumSize(new java.awt.Dimension(66, 17));
onPanel.setLayout(new java.awt.BorderLayout());
on.setFont(new java.awt.Font("DejaVu Sans", 0, 13)); // NOI18N
on.setText("jLabel3");
onPanel.add(on, java.awt.BorderLayout.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 6;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHWEST;
gridBagConstraints.weightx = 1.0;
menuPanel.add(onPanel, gridBagConstraints);
joinPanel.setMinimumSize(new java.awt.Dimension(66, 17));
joinPanel.setLayout(new java.awt.GridBagLayout());
join.setFont(new java.awt.Font("DejaVu Sans", 0, 13)); // NOI18N
join.setText("jLabel3");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
joinPanel.add(join, gridBagConstraints);
jLabel6.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
jLabel6.setText(" as B ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
joinPanel.add(jLabel6, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHWEST;
gridBagConstraints.weightx = 1.0;
menuPanel.add(joinPanel, gridBagConstraints);
jPanel10.setMinimumSize(new java.awt.Dimension(66, 17));
jPanel10.setLayout(new java.awt.GridBagLayout());
from.setFont(new java.awt.Font("DejaVu Sans", 0, 13)); // NOI18N
from.setText("jLabel3");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
jPanel10.add(from, gridBagConstraints);
jLabel5.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel5.setText(" as A");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
jPanel10.add(jLabel5, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
menuPanel.add(jPanel10, gridBagConstraints);
jLabel1.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
jLabel1.setText(" Join ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 5;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
menuPanel.add(jLabel1, gridBagConstraints);
jLabel4.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
jLabel4.setText(" On ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 6;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
menuPanel.add(jLabel4, gridBagConstraints);
andLabel.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
andLabel.setText(" Where ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 8;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
menuPanel.add(andLabel, gridBagConstraints);
jLabel3.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
jLabel3.setText(" From ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
menuPanel.add(jLabel3, gridBagConstraints);
jPanel3.setLayout(new javax.swing.BoxLayout(jPanel3, javax.swing.BoxLayout.LINE_AXIS));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 9;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
menuPanel.add(jPanel3, gridBagConstraints);
rrPanel.setLayout(new java.awt.GridBagLayout());
relatedRowsPanel.setBackground(new java.awt.Color(224, 240, 255));
relatedRowsPanel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
relatedRowsPanel.setLayout(new java.awt.GridBagLayout());
relatedRowsLabel.setBackground(new java.awt.Color(224, 240, 255));
relatedRowsLabel.setText(" Related Rows ");
relatedRowsLabel.setOpaque(true);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
relatedRowsPanel.add(relatedRowsLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 7;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(2, 0, 4, 0);
rrPanel.add(relatedRowsPanel, gridBagConstraints);
sqlPanel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
sqlPanel.setLayout(new javax.swing.BoxLayout(sqlPanel, javax.swing.BoxLayout.LINE_AXIS));
sqlLabel1.setText(" Menu ");
sqlPanel.add(sqlLabel1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 8;
gridBagConstraints.gridy = 5;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
rrPanel.add(sqlPanel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 7;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.gridheight = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2);
menuPanel.add(rrPanel, gridBagConstraints);
jPanel9.setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 5;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 8, 0, 0);
menuPanel.add(jPanel9, gridBagConstraints);
dropA.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
dropA.setText("drop");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 4;
menuPanel.add(dropA, gridBagConstraints);
dropB.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
dropB.setText("drop");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 5;
menuPanel.add(dropB, gridBagConstraints);
openEditorButton.setText("jButton1");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 8;
menuPanel.add(openEditorButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
add(menuPanel, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
private void cancelLoadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelLoadButtonActionPerformed
cancelLoadJob(false);
updateMode("cancelled", null);
}//GEN-LAST:event_cancelLoadButtonActionPerformed
private void selectDistinctCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectDistinctCheckBoxActionPerformed
reloadRows();
}//GEN-LAST:event_selectDistinctCheckBoxActionPerformed
private void sortColumnsCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sortColumnsCheckBoxActionPerformed
updateTableModel();
}//GEN-LAST:event_sortColumnsCheckBoxActionPerformed
private void deselectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deselectButtonActionPerformed
andCondition.setSelectedItem("");
}//GEN-LAST:event_deselectButtonActionPerformed
private void removeConditionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeConditionButtonActionPerformed
andCondition.setSelectedItem("");
}//GEN-LAST:event_removeConditionButtonActionPerformed
private void loadButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_loadButtonActionPerformed
if (System.currentTimeMillis() - lastReloadTS > 200) {
reloadRows();
}
}// GEN-LAST:event_loadButtonActionPerformed
private void limitBoxItemStateChanged(java.awt.event.ItemEvent evt) {// GEN-FIRST:event_limitBoxItemStateChanged
if (evt.getStateChange() == ItemEvent.SELECTED) {
reloadRows();
}
}// GEN-LAST:event_limitBoxItemStateChanged
void openQueryBuilder(boolean openSQLConsole) {
openQueryBuilder(openSQLConsole, null);
}
void openQueryBuilder(boolean openSQLConsole, String alternativeWhere) {
QueryBuilderDialog.Relationship root = createQBRelations(true);
if (root != null) {
if (alternativeWhere != null) {
root.whereClause = alternativeWhere;
}
root.selectColumns = true;
getQueryBuilderDialog().buildQuery(table, root, dataModel, session, getMetaDataSource(), openSQLConsole);
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JComboBox andCondition;
javax.swing.JLabel andLabel;
private javax.swing.JButton cancelLoadButton;
private javax.swing.JPanel cardPanel;
private javax.swing.JButton deselectButton;
private javax.swing.JLabel dropA;
private javax.swing.JLabel dropB;
private javax.swing.JLabel from;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JLayeredPane jLayeredPane1;
private javax.swing.JLayeredPane jLayeredPane2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel10;
private javax.swing.JPanel jPanel11;
private javax.swing.JPanel jPanel12;
private javax.swing.JPanel jPanel13;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JPanel jPanel9;
private javax.swing.JLabel join;
private javax.swing.JPanel joinPanel;
public javax.swing.JButton loadButton;
private javax.swing.JLabel loadingCauseLabel;
private javax.swing.JLabel loadingLabel;
private javax.swing.JPanel loadingPanel;
javax.swing.JPanel menuPanel;
private javax.swing.JPanel noRowsFoundPanel;
private javax.swing.JLabel on;
private javax.swing.JPanel onPanel;
private javax.swing.JButton openEditorButton;
private javax.swing.JLabel openEditorLabel;
private javax.swing.JPanel pendingNonpendingPanel;
private javax.swing.JLabel relatedRowsLabel;
javax.swing.JPanel relatedRowsPanel;
private javax.swing.JButton removeConditionButton;
public javax.swing.JLabel rowsCount;
public javax.swing.JTable rowsTable;
private javax.swing.JPanel rowsTableContainerPanel;
protected javax.swing.JScrollPane rowsTableScrollPane;
private javax.swing.JPanel rrPanel;
javax.swing.JCheckBox selectDistinctCheckBox;
private javax.swing.JPanel singleRowViewContainterPanel;
private javax.swing.JPanel singleRowViewScrollContentPanel;
javax.swing.JScrollPane singleRowViewScrollPane;
private javax.swing.JPanel singleRowViewScrollPaneContainer;
public javax.swing.JCheckBox sortColumnsCheckBox;
private javax.swing.JLabel sqlLabel1;
javax.swing.JPanel sqlPanel;
private javax.swing.JPanel tablePanel;
// End of variables declaration//GEN-END:variables
JPanel thumbnail;
private ConditionEditor andConditionEditor;
private ImageIcon conditionEditorIcon;
private Icon conditionEditorSelectedIcon;
{
String dir = "/net/sf/jailer/ui/resource";
// load images
try {
conditionEditorIcon = new ImageIcon(getClass().getResource(dir + "/edit.png"));
} catch (Exception e) {
e.printStackTrace();
}
try {
conditionEditorSelectedIcon = new ImageIcon(getClass().getResource(dir + "/edit_s.png"));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Cancels current load job.
* @param propagate
*/
public void cancelLoadJob(boolean propagate) {
LoadJob cLoadJob;
synchronized (this) {
cLoadJob = currentLoadJob;
}
if (cLoadJob != null) {
cLoadJob.cancel();
}
if (propagate) {
for (RowBrowser child: getChildBrowsers()) {
child.browserContentPane.cancelLoadJob(propagate);
}
}
}
private void updateMode(String mode, String cause) {
String suffix;
if (cause != null) {
suffix = cause;
} else {
suffix = "";
}
loadingCauseLabel.setVisible(false);
if ("table".equals(mode)) {
loadingPanel.setVisible(false);
rowsTable.setEnabled(true);
} else if ("loading".equals(mode)) {
mode = "table";
loadingPanel.setVisible(true);
loadingLabel.setText("loading...");
loadingCauseLabel.setText(suffix);
loadingCauseLabel.setVisible(true);
cancelLoadButton.setVisible(true);
rowsTable.setEnabled(false);
} else if ("pending".equals(mode)) {
mode = "table";
loadingPanel.setVisible(true);
loadingLabel.setText("pending...");
cancelLoadButton.setVisible(false);
rowsTable.setEnabled(false);
} else if ("updating".equals(mode)) {
mode = "table";
loadingPanel.setVisible(true);
loadingLabel.setText("updating...");
cancelLoadButton.setVisible(true);
rowsTable.setEnabled(false);
}
((CardLayout) cardPanel.getLayout()).show(cardPanel, mode);
}
/**
* Opens a drop-down box which allows the user to select columns for restriction definitions.
*/
private void openColumnDropDownBox(JLabel label, String alias, Table table) {
JPopupMenu popup = new JScrollPopupMenu();
List<String> columns = new ArrayList<String>();
for (Column c: table.getColumns()) {
columns.add(alias + "." + c.name);
}
for (final String c: columns) {
if (c.equals("")) {
popup.add(new JSeparator());
continue;
}
JMenuItem m = new JMenuItem(c);
m.addActionListener(new ActionListener () {
@Override
public void actionPerformed(ActionEvent e) {
if (andCondition.isEnabled()) {
if (andCondition.isEditable()) {
if (andCondition.getEditor() != null && (andCondition.getEditor().getEditorComponent() instanceof JTextField)) {
JTextField f = ((JTextField) andCondition.getEditor().getEditorComponent());
int pos = f.getCaretPosition();
String current = f.getText();
if (pos < 0 || pos >= current.length()) {
setAndCondition(current + c, false);
} else {
setAndCondition(current.substring(0, pos) + c + current.substring(pos), false);
f.setCaretPosition(pos + c.length());
}
}
andCondition.grabFocus();
}
}
}
});
popup.add(m);
}
UIUtil.fit(popup);
UIUtil.showPopup(label, 0, label.getHeight(), popup);
}
/**
* Creates new row. Fills in foreign key.
*
* @param parentrow row holding the primary key
* @param table the table of the new row
* @return new row of table
*/
private Row createNewRow(Row parentrow, Table table, Association association) {
try {
if (parentrow != null && association != null && !association.isInsertDestinationBeforeSource()) {
Map<Column, Column> sToDMap = association.createSourceToDestinationKeyMapping();
if (!sToDMap.isEmpty()) {
Row row = new Row("", null, new Object[association.destination.getColumns().size()]);
for (Map.Entry<Column, Column> e: sToDMap.entrySet()) {
int iS = -1;
for (int i = 0; i < table.getColumns().size(); ++i) {
if (Quoting.equalsIgnoreQuotingAndCase(e.getKey().name, table.getColumns().get(i).name)) {
iS = i;
break;
}
}
int iD = -1;
for (int i = 0; i < association.destination.getColumns().size(); ++i) {
if (Quoting.equalsIgnoreQuotingAndCase(e.getValue().name, association.destination.getColumns().get(i).name)) {
iD = i;
break;
}
}
if (iS >= 0 && iD >= 0) {
row.values[iD] = parentrow.values[iS];
} else {
return null;
}
}
return row;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected abstract RowBrowser navigateTo(Association association, int rowIndex, Row row);
protected abstract void onContentChange(List<Row> rows, boolean reloadChildren);
protected abstract void onRedraw();
protected abstract void onHide();
protected abstract void beforeReload();
protected abstract QueryBuilderDialog.Relationship createQBRelations(boolean withParents);
protected abstract List<QueryBuilderDialog.Relationship> createQBChildrenRelations(RowBrowser tabu, boolean all);
protected abstract void addRowToRowLink(Row pRow, Row exRow);
protected abstract JFrame getOwner();
protected abstract void findClosure(Row row);
protected abstract void findClosure(Row row, Set<Pair<BrowserContentPane, Row>> closure, boolean forward);
protected abstract QueryBuilderDialog getQueryBuilderDialog();
protected abstract void openSchemaMappingDialog();
protected abstract void openSchemaAnalyzer();
protected abstract DbConnectionDialog getDbConnectionDialog();
protected abstract double getLayoutFactor();
protected abstract List<RowBrowser> getChildBrowsers();
protected abstract RowBrowser getParentBrowser();
protected abstract List<RowBrowser> getTableBrowser();
protected abstract void unhide();
protected abstract void close();
protected abstract void showInNewWindow();
protected abstract void appendLayout();
protected abstract void adjustClosure(BrowserContentPane tabu, BrowserContentPane thisOne);
protected abstract void reloadDataModel() throws Exception;
protected abstract MetaDataSource getMetaDataSource();
protected abstract void deselectChildrenIfNeededWithoutReload();
protected abstract int getReloadLimit();
public interface RunnableWithPriority extends Runnable {
int getPriority();
};
protected abstract PriorityBlockingQueue<RunnableWithPriority> getRunnableQueue();
/**
* Collect layout of tables in a extraction model.
*
* @param positions to put positions into
*/
protected abstract void collectPositions(Map<String, Map<String, double[]>> positions);
private void openDetails(final int x, final int y) {
final JDialog d = new JDialog(getOwner(), (table instanceof SqlStatementTable)? "" : dataModel.getDisplayName(table), true);
final boolean deselect = !currentSelectedRowCondition.equals("")
&& currentSelectedRowCondition.equals(getAndConditionText())
&& rows.size() == 1;
d.getContentPane().add(new DetailsView(rows, rowsTable.getRowCount(), dataModel, table, 0, rowsTable.getRowSorter(), true, getQueryBuilderDialog() != null, rowIdSupport, deselect, session) {
@Override
protected void onRowChanged(int row) {
setCurrentRowSelectionAndReloadChildrenIfLimitIsExceeded(row);
}
@Override
protected void onClose() {
d.setVisible(false);
}
@Override
protected void onSelectRow(Row row) {
d.setVisible(false);
if (deselect) {
andCondition.setSelectedItem("");
} else {
selectRow(row);
}
}
});
d.pack();
d.setLocation(x, y);
d.setSize(400, d.getHeight() + 20);
UIUtil.fit(d);
d.setVisible(true);
setCurrentRowSelectionAndReloadChildrenIfLimitIsExceeded(-1);
onRedraw();
}
private void updateWhereField() {
if (association != null) {
if (parentRow == null && parentRows != null && parentRows.size() > 0) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < parentRows.size(); ++i) {
if (i > 0) {
sb.append(" or\n");
}
sb.append(parentRows.get(i).rowId);
if (i > 50) {
sb.append("\n...");
break;
}
}
String currentCond = getAndConditionText().trim();
String toolTip;
if (currentCond.length() > 0) {
toolTip = currentCond + "\nand (\n" + sb + ")";
} else {
toolTip = sb.toString();
}
andLabel.setToolTipText(UIUtil.toHTML(toolTip, 0));
} else {
andLabel.setToolTipText(null);
}
} else {
andLabel.setToolTipText(null);
}
}
public void convertToRoot() {
association = null;
parentRow = null;
parentRows = null;
rowsClosure.currentClosureRowIDs.clear();
adjustGui();
reloadRows();
}
public void openDetailsView(int rowIndex, int x, int y) {
final JDialog d = new JDialog(getOwner(), (table instanceof SqlStatementTable)? "" : dataModel.getDisplayName(table), true);
final boolean deselect = !currentSelectedRowCondition.equals("")
&& currentSelectedRowCondition.equals(getAndConditionText())
&& rows.size() == 1;
d.getContentPane().add(new DetailsView(rows, rowsTable.getRowCount(), dataModel, table, rowIndex, rowsTable.getRowSorter(), true, getQueryBuilderDialog() != null, rowIdSupport, deselect, session) {
@Override
protected void onRowChanged(int row) {
setCurrentRowSelectionAndReloadChildrenIfLimitIsExceeded(row);
}
@Override
protected void onClose() {
d.setVisible(false);
}
@Override
protected void onSelectRow(Row row) {
d.setVisible(false);
if (deselect) {
andCondition.setSelectedItem("");
} else {
selectRow(row);
}
}
});
d.pack();
d.setLocation(x, y);
d.setSize(400, d.getHeight() + 20);
int h = d.getHeight();
UIUtil.fit(d);
if (d.getHeight() < h) {
y = Math.max(y - Math.min(h - d.getHeight(), Math.max(400 - d.getHeight(), 0)), 20);
d.pack();
d.setLocation(x, y);
d.setSize(400, d.getHeight() + 20);
UIUtil.fit(d);
}
d.setVisible(true);
setCurrentRowSelectionAndReloadChildrenIfLimitIsExceeded(-1);
onRedraw();
}
public void updateSingleRowDetailsView() {
if (singleRowDetailsView != null) {
if (rowsClosure != null && rowsClosure.currentClosureRowIDs != null) {
singleRowDetailsView.updateInClosureState(rows.size() == 1 && rowsClosure.currentClosureRowIDs.contains(new Pair<BrowserContentPane, String>(this, rows.get(0).nonEmptyRowId)));
}
}
}
private static TableContentViewFilter tableContentViewFilter = TableContentViewFilter.create();
private Icon dropDownIcon;
private ImageIcon relatedRowsIcon;
private ImageIcon redDotIcon;
private ImageIcon blueDotIcon;
private ImageIcon greenDotIcon;
private ImageIcon greyDotIcon;
{
String dir = "/net/sf/jailer/ui/resource";
// load images
try {
dropDownIcon = new ImageIcon(getClass().getResource(dir + "/dropdown.png"));
relatedRowsIcon = new ImageIcon(getClass().getResource(dir + "/right.png"));
redDotIcon = new ImageIcon(getClass().getResource(dir + "/reddot.gif"));
blueDotIcon = new ImageIcon(getClass().getResource(dir + "/bluedot.gif"));
greenDotIcon = new ImageIcon(getClass().getResource(dir + "/greendot.gif"));
greyDotIcon = new ImageIcon(getClass().getResource(dir + "/greydot.gif"));
} catch (Exception e) {
e.printStackTrace();
}
}
public void resetRowsTableContainer() {
cardPanel.setVisible(true);
}
public JComponent getRowsTableContainer() {
return cardPanel;
}
public JTable getRowsTable() {
return rowsTable;
}
public LoadJob newLoadJob(ResultSet resultSet, Integer limit) {
return new LoadJob(resultSet, limit == null? Integer.MAX_VALUE : limit);
}
public boolean isEditMode() {
return isEditMode;
}
public void setEditMode(boolean isEditMode) {
this.isEditMode = isEditMode;
}
private String statementForReloading;
public synchronized void setStatementForReloading(String statementForReloading) {
this.statementForReloading = statementForReloading;
}
/**
* Type of result set for in-place editing of query result.
*/
private List<Table> resultSetType;
/**
* Sets type of result set for in-place editing of query result.
*
* @param resultSetType the type
*/
public void setResultSetType(List<Table> resultSetType) {
this.resultSetType = resultSetType;
}
/**
* Gets a table from {@link #resultSetType} where a given column is defined.
*
* @param column the column
* @return suitable table for column or {@link #table}
*/
private Table getResultSetTypeForColumn(int column) {
if (resultSetType == null) {
return table;
}
if (typePerColumn.containsKey(column)) {
return typePerColumn.get(column);
}
for (Table type: resultSetType) {
if (type.getColumns().size() > column) {
Column col = type.getColumns().get(column);
if (col != null && col.name != null) {
typePerColumn.put(column, type);
return type;
}
}
}
typePerColumn.put(column, table);
return table;
}
private boolean isPKComplete(Table type, Row r) {
if (type.primaryKey == null) {
return false;
}
int[] indexes = pkColumnIndexes.get(type);
if (indexes == null) {
indexes = new int[type.primaryKey.getColumns().size()];
int ii = 0;
for (Column pk: type.primaryKey.getColumns()) {
Integer index = null;
int i = 0;
for (Column c: type.getColumns()) {
if (c.name != null && c.name.equals(pk.name)) {
index = i;
break;
}
++i;
}
if (index == null) {
return false;
}
indexes[ii++] = index;
}
pkColumnIndexes.put(type, indexes);
}
for (int i: indexes) {
if (i >= r.values.length) {
return false;
}
Object content = r.values[i];
if (content == null || content instanceof TableModelItem && (((TableModelItem) content).value == UIUtil.NULL || ((TableModelItem) content).value == null)) {
return false;
}
}
return true;
}
private Map<Integer, Table> typePerColumn = new HashMap<Integer, Table>();
private Map<Table, int[]> pkColumnIndexes = new HashMap<Table, int[]>();
private String[] alternativeColumnLabels;
public void setAlternativeColumnLabels(String[] columnLabels) {
this.alternativeColumnLabels = columnLabels;
}
private void selectRow(final Row row) {
if (row.rowId.isEmpty()) {
return;
}
for (int i = 0; i < rows.size(); ++i) {
if (row.rowId.equals(rows.get(i).rowId)) {
setCurrentRowSelection(i);
currentRowSelection = -1;
break;
}
}
deselectChildrenIfNeededWithoutReload();
String cond = SqlUtil.replaceAliases(row.rowId, "A", "A");
String currentCond = getAndConditionText().trim();
if (currentCond.length() > 0) {
cond = "(" + cond + ") and (" + currentCond + ")";
}
andCondition.setSelectedItem(cond);
currentSelectedRowCondition = cond;
}
protected void deselectIfNeededWithoutReload() {
if (rows.size() == 1) {
String rowId = rows.get(0).rowId;
if (rowId != null && !rowId.isEmpty()) {
String cond = SqlUtil.replaceAliases(rowId, "A", "A");
String currentCond = getAndConditionText().trim();
if (cond.equals(currentCond)) {
boolean isSingleRowNotInClosure = false;
if (rowsClosure != null && rowsClosure.currentClosureRowIDs != null) {
isSingleRowNotInClosure = !rowsClosure.currentClosureRowIDs.contains(new Pair<BrowserContentPane, String>(this, rowId));
}
if (isSingleRowNotInClosure) {
try {
suppessReloadOnAndConditionAction = true;
andCondition.setSelectedItem("");
} finally {
suppessReloadOnAndConditionAction = false;
}
}
}
}
}
}
private static String readCharacterStream(final Reader reader)
throws IOException {
final StringBuilder sb = new StringBuilder();
final BufferedReader br = new BufferedReader(reader);
int b;
while(-1 != (b = br.read()))
{
sb.append((char)b);
if (sb.length() > MAXLOBLENGTH) {
sb.append("...");
break;
}
}
br.close();
return sb.toString();
}
private List<Row> sortedAndFiltered(List<Row> rows) {
RowSorter<? extends TableModel> sorter = rowsTable.getRowSorter();
if (sorter != null) {
List<Row> result = new ArrayList<Row>();
for (int i = 0; i < sorter.getViewRowCount(); ++i) {
result.add(rows.get(sorter.convertRowIndexToModel(i)));
}
return result;
}
return rows;
}
private void sortChildren() {
((TableRowSorter) rowsTable.getRowSorter()).sort();
for (RowBrowser ch: getChildBrowsers()) {
if (ch.browserContentPane != null) {
ch.browserContentPane.sortChildren();
}
}
}
private static String readClob(Clob clob) throws SQLException, IOException {
return readCharacterStream(clob.getCharacterStream());
}
private static String readSQLXML(SQLXML xml) throws SQLException, IOException {
return readCharacterStream(xml.getCharacterStream());
}
public static Object toLobRender(Object object) {
Object value = null;
if (object instanceof Blob) {
try {
final long length = ((Blob) object).length();
value = new LobValue() {
@Override
public String toString() {
return "<Blob> " + length + " bytes";
}
};
} catch (Exception e) {
value = new LobValue() {
@Override
public String toString() {
return "<Blob>";
}
};
}
}
if (object instanceof Clob) {
try {
final String content = readClob((Clob) object);
value = new LobValue() {
@Override
public String toString() {
return content;
}
};
} catch (Exception e) {
value = new LobValue() {
@Override
public String toString() {
return "<Clob>";
}
};e.printStackTrace();
}
}
if (object instanceof SQLXML) {
try {
final String content = readSQLXML((SQLXML) object);
value = new LobValue() {
@Override
public String toString() {
return content;
}
};
} catch (Exception e) {
value = new LobValue() {
@Override
public String toString() {
return "<XML>";
}
};
e.printStackTrace();
}
}
return value;
}
}
| src/main/gui/net/sf/jailer/ui/databrowser/BrowserContentPane.java | /*
* Copyright 2007 - 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.jailer.ui.databrowser;
import java.awt.BasicStroke;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.math.BigDecimal;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.PriorityBlockingQueue;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.InputMap;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.ListCellRenderer;
import javax.swing.RowSorter;
import javax.swing.RowSorter.SortKey;
import javax.swing.SortOrder;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.event.RowSorterEvent;
import javax.swing.event.RowSorterListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import net.coderazzi.filters.gui.AutoChoices;
import net.coderazzi.filters.gui.TableFilterHeader;
import net.sf.jailer.ExecutionContext;
import net.sf.jailer.database.InlineViewStyle;
import net.sf.jailer.database.Session;
import net.sf.jailer.database.Session.AbstractResultSetReader;
import net.sf.jailer.database.SqlException;
import net.sf.jailer.datamodel.Association;
import net.sf.jailer.datamodel.Cardinality;
import net.sf.jailer.datamodel.Column;
import net.sf.jailer.datamodel.DataModel;
import net.sf.jailer.datamodel.PrimaryKey;
import net.sf.jailer.datamodel.RestrictionDefinition;
import net.sf.jailer.datamodel.RowIdSupport;
import net.sf.jailer.datamodel.Table;
import net.sf.jailer.extractionmodel.ExtractionModel;
import net.sf.jailer.modelbuilder.JDBCMetaDataBasedModelElementFinder;
import net.sf.jailer.modelbuilder.MemorizedResultSet.MemorizedResultSetMetaData;
import net.sf.jailer.subsetting.ScriptFormat;
import net.sf.jailer.ui.ConditionEditor;
import net.sf.jailer.ui.DataModelManager;
import net.sf.jailer.ui.DbConnectionDialog;
import net.sf.jailer.ui.Environment;
import net.sf.jailer.ui.ExtractionModelFrame;
import net.sf.jailer.ui.JComboBox;
import net.sf.jailer.ui.QueryBuilderDialog;
import net.sf.jailer.ui.QueryBuilderDialog.Relationship;
import net.sf.jailer.ui.UIUtil;
import net.sf.jailer.ui.databrowser.Desktop.RowBrowser;
import net.sf.jailer.ui.databrowser.RowCounter.RowCount;
import net.sf.jailer.ui.databrowser.metadata.MetaDataSource;
import net.sf.jailer.ui.databrowser.sqlconsole.SQLConsole;
import net.sf.jailer.ui.scrollmenu.JScrollC2Menu;
import net.sf.jailer.ui.scrollmenu.JScrollMenu;
import net.sf.jailer.ui.scrollmenu.JScrollPopupMenu;
import net.sf.jailer.util.CancellationException;
import net.sf.jailer.util.CancellationHandler;
import net.sf.jailer.util.CellContentConverter;
import net.sf.jailer.util.CellContentConverter.PObjectWrapper;
import net.sf.jailer.util.Pair;
import net.sf.jailer.util.Quoting;
import net.sf.jailer.util.SqlUtil;
/**
* Content UI of a row browser frame (as {@link JInternalFrame}s). Contains a
* table for rendering rows.
*
* @author Ralf Wisser
*/
@SuppressWarnings("serial")
public abstract class BrowserContentPane extends javax.swing.JPanel {
/**
* Concurrently loads rows.
*/
public class LoadJob implements RunnableWithPriority {
private List<Row> rows = Collections.synchronizedList(new ArrayList<Row>());
private Throwable exception;
private boolean isCanceled;
private final int limit;
private final String andCond;
private final boolean selectDistinct;
private boolean finished;
private final ResultSet inputResultSet;
private final RowBrowser parentBrowser;
public boolean closureLimitExceeded = false;
public LoadJob(int limit, String andCond, RowBrowser parentBrowser, boolean selectDistinct) {
this.andCond = andCond;
this.selectDistinct = selectDistinct;
this.inputResultSet = null;
synchronized (this) {
this.limit = limit;
finished = false;
isCanceled = false;
this.parentBrowser = parentBrowser;
}
}
public LoadJob(ResultSet inputResultSet, int limit) {
this.andCond = "";
this.selectDistinct = false;
this.inputResultSet = inputResultSet;
synchronized (this) {
this.limit = limit;
finished = false;
isCanceled = false;
parentBrowser = null;
}
}
@Override
public void run() {
int l;
synchronized (this) {
l = limit;
if (isCanceled) {
CancellationHandler.reset(this);
return;
}
}
rowCountCache.clear();
try {
reloadRows(inputResultSet, andCond, rows, this, l + 1, selectDistinct);
CancellationHandler.checkForCancellation(this);
synchronized (this) {
finished = true;
}
} catch (SQLException e) {
synchronized (rows) {
exception = e;
}
} catch (CancellationException e) {
Session._log.info("cancelled");
CancellationHandler.reset(this);
return;
} catch (Throwable e) {
synchronized (rows) {
exception = e;
}
}
CancellationHandler.reset(this);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Throwable e;
int l;
boolean limitExceeded = false;
synchronized (rows) {
e = exception;
l = limit;
while (rows.size() > limit) {
limitExceeded = true;
rows.remove(rows.size() - 1);
}
isCanceled = true; // done
sortRowsByParentViewIndex();
}
if (e != null) {
updateMode("error", null);
unhide();
UIUtil.showException(BrowserContentPane.this, "Error", e);
} else {
Set<String> prevIDs = new TreeSet<String>();
long prevHash = 0;
if (BrowserContentPane.this.rows != null) {
for (Row r: BrowserContentPane.this.rows) {
prevIDs.add(r.nonEmptyRowId);
try {
for (Object v: r.values) {
if (v != null) {
prevHash = 2 * prevHash + v.hashCode();
}
}
} catch (RuntimeException e1) {
// ignore
}
}
}
onContentChange(new ArrayList<Row>(), false);
BrowserContentPane.this.rows.clear();
BrowserContentPane.this.rows.addAll(rows);
updateTableModel(l, limitExceeded, closureLimitExceeded);
Set<String> currentIDs = new TreeSet<String>();
long currentHash = 0;
if (rows != null) {
for (Row r: rows) {
currentIDs.add(r.nonEmptyRowId);
try {
for (Object v: r.values) {
if (v != null) {
currentHash = 2 * currentHash + v.hashCode();
}
}
} catch (RuntimeException e1) {
// ignore
}
}
}
setPendingState(false, true);
onContentChange(rows, true); // rows.isEmpty() || currentHash != prevHash || rows.size() != prevSize || !prevIDs.equals(currentIDs) || rows.size() != currentIDs.size());
updateMode("table", null);
updateWhereField();
if (reloadAction != null) {
reloadAction.run();
}
}
}
});
}
protected void sortRowsByParentViewIndex() {
if (parentBrowser != null && parentBrowser.browserContentPane != null && parentBrowser.browserContentPane.rowsTable != null) {
final RowSorter<? extends TableModel> parentSorter = parentBrowser.browserContentPane.rowsTable.getRowSorter();
Collections.sort(rows, new Comparator<Row>() {
@Override
public int compare(Row a, Row b) {
int avi = a.getParentModelIndex();
if (avi >= 0 && avi < parentSorter.getModelRowCount()) {
avi = parentSorter.convertRowIndexToView(avi);
}
int bvi = b.getParentModelIndex();
if (bvi >= 0 && avi < parentSorter.getModelRowCount()) {
bvi = parentSorter.convertRowIndexToView(bvi);
}
return avi - bvi;
}
});
}
}
public synchronized void cancel() {
if (isCanceled) {
return;
}
isCanceled = true;
if (finished) {
return;
}
CancellationHandler.cancel(this);
}
public synchronized void checkCancellation() {
CancellationHandler.checkForCancellation(this);
}
@Override
public int getPriority() {
return 100;
}
}
private Runnable reloadAction;
public void setOnReloadAction(final Runnable runnable) {
if (reloadAction == null) {
reloadAction = runnable;
} else {
final Runnable prevReloadAction = reloadAction;
reloadAction = new Runnable() {
@Override
public void run() {
prevReloadAction.run();
runnable.run();
}
};
}
}
/**
* Current LoadJob.
*/
private LoadJob currentLoadJob;
/**
* Table to read rows from.
*/
Table table;
/**
* Parent row, or <code>null</code>.
*/
Row parentRow;
/**
* The data model.
*/
private final DataModel dataModel;
/**
* The execution context.
*/
protected final ExecutionContext executionContext;
/**
* {@link RowIdSupport} for data model.
*/
private final RowIdSupport rowIdSupport;
/**
* {@link Association} with parent row, or <code>null</code>.
*/
Association association;
/**
* Rows to render.
*/
public List<Row> rows = new ArrayList<Row>();
/**
* For in-place editing.
*/
private BrowserContentCellEditor browserContentCellEditor = new BrowserContentCellEditor(new int[0]);
/**
* Cache for association row count.
*/
private final Map<Pair<String, Association>, Pair<RowCount, Long>> rowCountCache =
Collections.synchronizedMap(new HashMap<Pair<String,Association>, Pair<RowCount, Long>>());
private final long MAX_ROWCOUNTCACHE_RETENTION_TIME = 5 * 60 * 1000L;
/**
* Number of non-distinct rows;
*/
private int noNonDistinctRows;
/**
* Number of distinct rows;
*/
private int noDistinctRows;
/**
* Indexes of highlighted rows.
*/
Set<Integer> highlightedRows = new HashSet<Integer>();
/**
* Indexes of primary key columns.
*/
private Set<Integer> pkColumns = new HashSet<Integer>();
/**
* Indexes of foreign key columns.
*/
private Set<Integer> fkColumns = new HashSet<Integer>();
/**
* Edit mode?
*/
private boolean isEditMode = false;
/**
* DB session.
*/
Session session;
private int currentRowSelection = -1;
private List<Row> parentRows;
private DetailsView singleRowDetailsView;
private MouseListener rowTableListener;
private int initialRowHeight;
public static class RowsClosure {
Set<Pair<BrowserContentPane, Row>> currentClosure = Collections.synchronizedSet(new HashSet<Pair<BrowserContentPane, Row>>());
Set<Pair<BrowserContentPane, String>> currentClosureRowIDs = new HashSet<Pair<BrowserContentPane, String>>();
String currentClosureRootID;
Set<BrowserContentPane> parentPath = new HashSet<BrowserContentPane>();
};
private final RowsClosure rowsClosure;
private boolean suppressReload;
/**
* Alias for row number column.
*/
private static final String ROWNUMBERALIAS = "RN";
protected static final String UNKNOWN = "- unknown column -";
protected static final int MAXLOBLENGTH = 2000;
private static final KeyStroke KS_COPY_TO_CLIPBOARD = KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_DOWN_MASK);
private static final KeyStroke KS_SQLCONSOLE = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.CTRL_DOWN_MASK);
private static final KeyStroke KS_QUERYBUILDER = KeyStroke.getKeyStroke(KeyEvent.VK_Q, InputEvent.CTRL_DOWN_MASK);
private static final KeyStroke KS_FILTER = KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.CTRL_DOWN_MASK);
private static final KeyStroke KS_EDIT = KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.CTRL_DOWN_MASK);
private static final KeyStroke KS_DETAILS = KeyStroke.getKeyStroke(KeyEvent.VK_D, InputEvent.CTRL_DOWN_MASK);
/**
* And-condition-combobox model.
*/
private final DefaultComboBoxModel<Object> andCondModel = new DefaultComboBoxModel<Object>();
private boolean isTableFilterEnabled = false;
public void setTableFilterEnabled(boolean isTableFilterEnabled) {
this.isTableFilterEnabled = isTableFilterEnabled;
}
static class SqlStatementTable extends Table {
public SqlStatementTable(String name, PrimaryKey primaryKey, boolean defaultUpsert) {
super(name, primaryKey, defaultUpsert, false);
}
}
/**
* Constructor.
*
* @param dataModel
* the data model
* @param table
* to read rows from. Opens SQL browser if table is <code>null</code>.
* @param condition
* initial condition
* @param session
* DB session
* @param parentRow
* parent row
* @param parentRows
* all parent rows, if there are more than 1
* @param association
* {@link Association} with parent row
*/
public BrowserContentPane(final DataModel dataModel, final Table table, String condition, Session session, Row parentRow, List<Row> parentRows,
final Association association, final Frame parentFrame, RowsClosure rowsClosure,
Boolean selectDistinct, boolean reload, ExecutionContext executionContext) {
this.table = table;
this.session = session;
this.dataModel = dataModel;
this.rowIdSupport = new RowIdSupport(dataModel, session.dbms, executionContext);
this.parentRow = parentRow;
this.parentRows = parentRows;
this.association = association;
this.rowsClosure = rowsClosure;
this.executionContext = executionContext;
rowIdSupport.setUseRowIdsOnlyForTablesWithoutPK(true);
suppressReload = true;
if (table == null) {
this.table = new SqlStatementTable(null, null, false);
}
initComponents();
loadingCauseLabel.setVisible(false);
andCondition = new JComboBox();
andCondition.setEditable(true);
GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
jPanel7.add(andCondition, gridBagConstraints);
setPendingState(false, false);
dropA.setText(null);
dropA.setIcon(dropDownIcon);
sqlLabel1.setIcon(dropDownIcon);
dropA.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mousePressed(java.awt.event.MouseEvent evt) {
openColumnDropDownBox(dropA, "A", table);
}
@Override
public void mouseEntered(java.awt.event.MouseEvent evt) {
dropA.setEnabled(false);
}
@Override
public void mouseExited(java.awt.event.MouseEvent evt) {
dropA.setEnabled(true);
}
});
if (association != null) {
dropB.setText(null);
dropB.setIcon(dropDownIcon);
dropB.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mousePressed(java.awt.event.MouseEvent evt) {
openColumnDropDownBox(dropB, "B", association.source);
}
@Override
public void mouseEntered(java.awt.event.MouseEvent evt) {
dropB.setEnabled(false);
}
@Override
public void mouseExited(java.awt.event.MouseEvent evt) {
dropB.setEnabled(true);
}
});
}
final ListCellRenderer acRenderer = andCondition.getRenderer();
andCondition.setRenderer(new ListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
boolean cellHasFocus) {
Component render = acRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (render instanceof JLabel) {
if (value != null && value.toString().trim().length() > 0) {
String tooltip = ConditionEditor.toMultiLine(value.toString());
((JLabel) render).setToolTipText(UIUtil.toHTML(tooltip, 200));
} else {
((JLabel) render).setToolTipText(null);
}
}
return render;
}
});
if (andCondition.getEditor() != null && (andCondition.getEditor().getEditorComponent() instanceof JTextField)) {
JTextField f = ((JTextField) andCondition.getEditor().getEditorComponent());
f.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
updateTooltip();
}
@Override
public void insertUpdate(DocumentEvent e) {
updateTooltip();
}
@Override
public void changedUpdate(DocumentEvent e) {
updateTooltip();
}
private void updateTooltip() {
if (andCondition.getEditor() != null && (andCondition.getEditor().getEditorComponent() instanceof JTextField)) {
JTextField f = ((JTextField) andCondition.getEditor().getEditorComponent());
String value = f.getText();
if (value != null && value.toString().trim().length() > 0) {
String tooltip = ConditionEditor.toMultiLine(value.toString());
andCondition.setToolTipText(UIUtil.toHTML(tooltip, 200));
} else {
andCondition.setToolTipText(null);
}
}
};
});
}
andCondModel.addElement("");
andCondition.setModel(andCondModel);
andCondition.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (!suppessReloadOnAndConditionAction) {
if (e.getStateChange() == ItemEvent.SELECTED) {
historizeAndCondition(e.getItem());
reloadRows();
}
}
}
});
initialRowHeight = rowsTable.getRowHeight();
rowsTable = new JTable() {
private int x[] = new int[2];
private int y[] = new int[2];
private Color color = new Color(0, 0, 200);
@Override
public void paint(Graphics graphics) {
super.paint(graphics);
if (!(graphics instanceof Graphics2D)) {
return;
}
if (BrowserContentPane.this.association != null && BrowserContentPane.this.association.isInsertDestinationBeforeSource()) {
return;
}
int maxI = Math.min(rowsTable.getRowCount(), rows.size());
RowSorter<? extends TableModel> sorter = getRowSorter();
if (sorter != null) {
maxI = sorter.getViewRowCount();
}
int lastPMIndex = -1;
for (int i = 0; i < maxI; ++i) {
int mi = sorter == null? i : sorter.convertRowIndexToModel(i);
if (mi >= rows.size()) {
continue;
}
if (rows.get(mi).getParentModelIndex() != lastPMIndex) {
lastPMIndex = rows.get(mi).getParentModelIndex();
int vi = i;
Graphics2D g2d = (Graphics2D) graphics;
g2d.setColor(color);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setStroke(new BasicStroke(1));
Rectangle r = rowsTable.getCellRect(vi, 0, false);
x[0] = (int) r.getMinX();
y[0] = (int) r.getMinY();
r = rowsTable.getCellRect(vi, rowsTable.getColumnCount() - 1, false);
x[1] = (int) r.getMaxX();
y[1] = (int) r.getMinY();
g2d.drawPolyline(x, y, 2);
}
}
}
};
InputMap im = rowsTable.getInputMap();
Object key = "copyClipboard";
im.put(KS_COPY_TO_CLIPBOARD, key);
ActionMap am = rowsTable.getActionMap();
Action a = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
UIUtil.copyToClipboard(rowsTable, true);
}
};
am.put(key, a);
registerAccelerator(KS_SQLCONSOLE, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
rowsTable.grabFocus();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
openQueryBuilder(true);
}
});
}
});
registerAccelerator(KS_QUERYBUILDER, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
rowsTable.grabFocus();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
openQueryBuilder(false);
}
});
}
});
registerAccelerator(KS_FILTER, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
isTableFilterEnabled = !isTableFilterEnabled;
updateTableModel();
}
});
registerAccelerator(KS_EDIT, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
setEditMode(!isEditMode);
updateTableModel();
}
});
registerAccelerator(KS_DETAILS, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
Point loc = new Point(18, 16);
SwingUtilities.convertPointToScreen(loc, rowsTable);
openDetails(loc.x, loc.y);
}
});
rowsTable.setAutoCreateRowSorter(true);
rowsTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
rowsTableScrollPane.setViewportView(rowsTable);
rowsTable.setAutoscrolls(false);
setAndCondition(ConditionEditor.toSingleLine(condition), true);
from.setText(table == null? "" : this.dataModel.getDisplayName(table));
adjustGui();
rowsTable.setShowGrid(false);
final TableCellRenderer defaultTableCellRenderer = rowsTable.getDefaultRenderer(String.class);
rowsTable.setDefaultRenderer(Object.class, new TableCellRenderer() {
final Color BG1 = new Color(255, 255, 255);
final Color BG2 = new Color(242, 255, 242);
final Color BG1_EM = new Color(255, 255, 236);
final Color BG2_EM = new Color(230, 255, 236);
final Color BG3 = new Color(194, 228, 255);
final Color BG3_2 = new Color(184, 220, 255);
final Color BG4 = new Color(30, 200, 255);
final Color FG1 = new Color(155, 0, 0);
final Color FG2 = new Color(0, 0, 255);
final Font font = new JLabel().getFont();
final Font nonbold = new Font(font.getName(), font.getStyle() & ~Font.BOLD, font.getSize());
final Font bold = new Font(nonbold.getName(), nonbold.getStyle() | Font.BOLD, nonbold.getSize());
final Font italic = new Font(nonbold.getName(), nonbold.getStyle() | Font.ITALIC, nonbold.getSize());
final Font italicBold = new Font(nonbold.getName(), nonbold.getStyle() | Font.ITALIC | Font.BOLD, nonbold.getSize());
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
boolean cellSelected = isSelected;
if (table.getSelectedColumnCount() <= 1 && table.getSelectedRowCount() <= 1) {
if (table == rowsTable) {
cellSelected = false;
}
}
isSelected = currentRowSelection == row || currentRowSelection == -2;
if (table != rowsTable) {
isSelected = false;
if (table.getSelectedRows().length <= 1 && table.getSelectedColumns().length <= 1) {
for (int sr: table.getSelectedRows()) {
if (sr == column) {
isSelected = true;
break;
}
}
}
}
Component render = defaultTableCellRenderer.getTableCellRendererComponent(rowsTable, value, isSelected, false, row, column);
final RowSorter<?> rowSorter = rowsTable.getRowSorter();
if (rowSorter.getViewRowCount() == 0 && table == rowsTable) {
return render;
}
boolean renderRowAsPK = false;
if (render instanceof JLabel) {
Row r = null;
int rowIndex = row;
((JLabel) render).setIcon(null);
if (row < rowSorter.getViewRowCount()) {
rowIndex = rowSorter.convertRowIndexToModel(row);
if (rowIndex < rows.size()) {
r = rows.get(rowIndex);
if (r != null) {
renderRowAsPK = renderRowAsPK(r);
Object cellContent = r.values.length > column? r.values[column] : null;
if (cellContent instanceof UIUtil.IconWithText) {
((JLabel) render).setIcon(((UIUtil.IconWithText) cellContent).icon);
((JLabel) render).setText(((UIUtil.IconWithText) cellContent).text);
}
}
}
}
((JLabel) render).setBorder(cellSelected? BorderFactory.createEtchedBorder() : null);
int convertedColumnIndex = rowsTable.convertColumnIndexToModel(column);
if (!isSelected && (table == rowsTable || !cellSelected)) {
if (BrowserContentPane.this.getQueryBuilderDialog() != null && // SQL Console
BrowserContentPane.this.rowsClosure.currentClosureRowIDs != null && row < rows.size() && BrowserContentPane.this.rowsClosure.currentClosureRowIDs.contains(new Pair<BrowserContentPane, String>(BrowserContentPane.this, rows.get(rowSorter.convertRowIndexToModel(row)).nonEmptyRowId))) {
((JLabel) render).setBackground((row % 2) == 0? BG3 : BG3_2);
if (BrowserContentPane.this.rowsClosure.currentClosureRootID != null
&& !BrowserContentPane.this.rowsClosure.currentClosureRootID.isEmpty()
&& BrowserContentPane.this.rowsClosure.currentClosureRootID.equals(rows.get(rowSorter.convertRowIndexToModel(row)).nonEmptyRowId)) {
((JLabel) render).setBackground(BG4);
}
} else {
Table type = getResultSetTypeForColumn(convertedColumnIndex);
if (isEditMode && r != null && (r.rowId != null && !r.rowId.isEmpty()) && browserContentCellEditor.isEditable(type, rowIndex, convertedColumnIndex, r.values[convertedColumnIndex])
&& isPKComplete(type, r) && !rowIdSupport.getPrimaryKey(type, BrowserContentPane.this.session).getColumns().isEmpty()) {
((JLabel) render).setBackground((row % 2 == 0) ? BG1_EM : BG2_EM);
} else {
((JLabel) render).setBackground((row % 2 == 0) ? BG1 : BG2);
}
}
} else {
((JLabel) render).setBackground(currentRowSelection == row? BG4.brighter() : BG4);
}
((JLabel) render).setForeground(
renderRowAsPK || pkColumns.contains(convertedColumnIndex) ? FG1 :
fkColumns.contains(convertedColumnIndex) ? FG2 :
Color.BLACK);
boolean isNull = false;
if (((JLabel) render).getText() == UIUtil.NULL || ((JLabel) render).getText() == UNKNOWN) {
((JLabel) render).setForeground(Color.gray);
((JLabel) render).setFont(italic);
isNull = true;
}
try {
((JLabel) render).setToolTipText(null);
if (isNull) {
((JLabel) render).setFont(highlightedRows.contains(rowSorter.convertRowIndexToModel(row)) ? italicBold : italic);
} else {
((JLabel) render).setFont(highlightedRows.contains(rowSorter.convertRowIndexToModel(row)) ? bold : nonbold);
String text = ((JLabel) render).getText();
if (text.indexOf('\n') >= 0) {
((JLabel) render).setToolTipText(UIUtil.toHTML(text, 200));
} else if (text.length() > 20) {
((JLabel) render).setToolTipText(text);
}
}
} catch (Exception e) {
// ignore
}
}
// indent 1. column
if (render instanceof JLabel) {
((JLabel) render).setText(" " + ((JLabel) render).getText());
}
return render;
}
});
rowsTable.setRowSelectionAllowed(true);
rowsTable.setColumnSelectionAllowed(true);
rowsTable.setCellSelectionEnabled(true);
rowsTable.setEnabled(true);
rowsTableScrollPane.getVerticalScrollBar().setUnitIncrement(32);
singleRowViewScrollPane.getVerticalScrollBar().setUnitIncrement(32);
rowTableListener = new MouseListener() {
private JPopupMenu lastMenu;
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
int ri;
JComponent source = (JComponent) e.getSource();
if (source == rowsTable) {
ri = rowsTable.rowAtPoint(e.getPoint());
} else {
ri = 0;
}
if (ri >= 0 && !rows.isEmpty() && rowsTable.getRowSorter().getViewRowCount() > 0) {
int i = 0;
if (source == rowsTable) {
i = rowsTable.getRowSorter().convertRowIndexToModel(ri);
} else if (source == rowsTableScrollPane) {
if (e.getButton() == MouseEvent.BUTTON1 && (e.getClickCount() <= 1 || getQueryBuilderDialog() == null /* SQL Console */)) {
return;
}
ri = rowsTable.getRowSorter().getViewRowCount() - 1;
i = rowsTable.getRowSorter().convertRowIndexToModel(ri);
}
Row row = rows.get(i);
if (lastMenu == null || !lastMenu.isVisible()) {
currentRowSelection = ri;
onRedraw();
int x, y;
if (source != rowsTable) {
x = e.getX();
y = e.getY();
} else {
Rectangle r = rowsTable.getCellRect(ri, 0, false);
x = Math.max(e.getPoint().x, (int) r.getMinX());
y = (int) r.getMaxY() - 2;
}
Point p = SwingUtilities.convertPoint(source, x, y, null);
if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() > 1) {
openDetailsView(i, p.x + getOwner().getX(), p.y + getOwner().getY());
} else if (e.getButton() != MouseEvent.BUTTON1) {
JPopupMenu popup;
popup = createPopupMenu(row, i, p.x + getOwner().getX(), p.y + getOwner().getY(), rows.size() == 1);
if (popup != null) {
UIUtil.showPopup(source, x, y, popup);
popup.addPropertyChangeListener("visible", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (Boolean.FALSE.equals(evt.getNewValue())) {
currentRowSelection = -1;
onRedraw();
}
}
});
}
lastMenu = popup;
} else {
setCurrentRowSelectionAndReloadChildrenIfLimitIsExceeded(ri);
if (getQueryBuilderDialog() != null) { // !SQL Console
setCurrentRowSelectionAndReloadChildrenIfLimitIsExceeded(-1);
}
}
}
}
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseClicked(MouseEvent e) {
}
};
rowsTable.addMouseListener(rowTableListener);
rowsTableScrollPane.addMouseListener(rowTableListener);
singleRowViewScrollContentPanel.addMouseListener(rowTableListener);
openEditorButton.setIcon(UIUtil.scaleIcon(this, conditionEditorIcon));
openEditorButton.setText(null);
openEditorButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final Point pos = new Point(openEditorButton.getX(), openEditorButton.getY() + openEditorButton.getHeight());
SwingUtilities.convertPointToScreen(pos, openEditorButton.getParent());
loadButton.grabFocus();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (andConditionEditor == null) {
andConditionEditor = new ConditionEditor(parentFrame, null, dataModel);
}
andConditionEditor.setLocationAndFit(pos);
String cond = andConditionEditor.edit(getAndConditionText(), "Table", "A", table, null, null, null, false, true);
if (cond != null) {
if (!getAndConditionText().equals(ConditionEditor.toSingleLine(cond))) {
setAndCondition(ConditionEditor.toSingleLine(cond), true);
loadButton.grabFocus();
reloadRows();
}
}
openEditorLabel.setIcon(conditionEditorSelectedIcon);
}
});
}
});
relatedRowsLabel.setIcon(UIUtil.scaleIcon(this, relatedRowsIcon));
relatedRowsLabel.setFont(relatedRowsLabel.getFont().deriveFont(relatedRowsLabel.getFont().getSize() * 1.1f));
if (createPopupMenu(null, -1, 0, 0, false).getComponentCount() == 0) {
relatedRowsLabel.setEnabled(false);
} else {
relatedRowsPanel.addMouseListener(new java.awt.event.MouseAdapter() {
private JPopupMenu popup;
private boolean in = false;
@Override
public void mousePressed(MouseEvent e) {
loadButton.grabFocus();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
popup = createPopupMenu(null, -1, 0, 0, false);
setCurrentRowSelectionAndReloadChildrenIfLimitIsExceeded(-2);
popup.addPropertyChangeListener("visible", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (Boolean.FALSE.equals(evt.getNewValue())) {
popup = null;
updateBorder();
setCurrentRowSelectionAndReloadChildrenIfLimitIsExceeded(-1);
}
}
});
UIUtil.showPopup(relatedRowsPanel, 0, relatedRowsPanel.getHeight(), popup);
}
});
}
@Override
public void mouseEntered(java.awt.event.MouseEvent evt) {
in = true;
updateBorder();
}
@Override
public void mouseExited(java.awt.event.MouseEvent evt) {
in = false;
updateBorder();
}
private void updateBorder() {
relatedRowsPanel.setBorder(new javax.swing.border.SoftBevelBorder((in || popup != null) ? javax.swing.border.BevelBorder.LOWERED
: javax.swing.border.BevelBorder.RAISED));
}
});
}
sqlPanel.addMouseListener(new java.awt.event.MouseAdapter() {
private JPopupMenu popup;
private boolean in = false;
@Override
public void mousePressed(MouseEvent e) {
loadButton.grabFocus();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Point loc = sqlPanel.getLocationOnScreen();
popup = createSqlPopupMenu(BrowserContentPane.this.parentRow, 0, (int) loc.getX(), (int) loc.getY(), false, BrowserContentPane.this);
setCurrentRowSelectionAndReloadChildrenIfLimitIsExceeded(-2);
popup.addPropertyChangeListener("visible", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (Boolean.FALSE.equals(evt.getNewValue())) {
popup = null;
updateBorder();
setCurrentRowSelectionAndReloadChildrenIfLimitIsExceeded(-1);
}
}
});
UIUtil.showPopup(sqlPanel, 0, sqlPanel.getHeight(), popup);
}
});
}
@Override
public void mouseEntered(java.awt.event.MouseEvent evt) {
in = true;
updateBorder();
}
@Override
public void mouseExited(java.awt.event.MouseEvent evt) {
in = false;
updateBorder();
}
private void updateBorder() {
sqlPanel.setBorder(new javax.swing.border.SoftBevelBorder((in || popup != null) ? javax.swing.border.BevelBorder.LOWERED
: javax.swing.border.BevelBorder.RAISED));
}
});
if (selectDistinct != null) {
selectDistinctCheckBox.setSelected(selectDistinct);
}
updateTableModel(0, false, false);
suppressReload = false;
if (reload) {
reloadRows();
}
}
private void registerAccelerator(KeyStroke ks, AbstractAction a) {
registerAccelerator(ks, a, this);
registerAccelerator(ks, a, rowsTable);
registerAccelerator(ks, a, loadButton);
registerAccelerator(ks, a, sqlLabel1);
registerAccelerator(ks, a, relatedRowsLabel);
registerAccelerator(ks, a, andCondition);
Component editor = andCondition.getEditor().getEditorComponent();
if (editor instanceof JComponent) {
registerAccelerator(ks, a, (JComponent) editor);
}
}
private void registerAccelerator(KeyStroke ks, AbstractAction a, JComponent comp) {
InputMap im = comp.getInputMap();
im.put(ks, a);
ActionMap am = comp.getActionMap();
am.put(a, a);
}
protected abstract boolean renderRowAsPK(Row theRow);
boolean isPending = false;
void setPendingState(boolean pending, boolean propagate) {
isPending = pending;
((CardLayout) pendingNonpendingPanel.getLayout()).show(pendingNonpendingPanel, "nonpending");
if (pending) {
updateMode("pending", null);
}
if (propagate) {
for (RowBrowser child: getChildBrowsers()) {
child.browserContentPane.setPendingState(pending, propagate);
}
}
}
protected void historizeAndCondition(Object item) {
if (item == null) {
return;
}
for (int i = 0; i < andCondModel.getSize(); ++i) {
if (item.equals(andCondModel.getElementAt(i))) {
return;
}
}
andCondModel.insertElementAt(item, 1);
}
private boolean suppessReloadOnAndConditionAction = false;
void setAndCondition(String cond, boolean historize) {
try {
suppessReloadOnAndConditionAction = true;
andCondition.setSelectedItem(cond);
if (historize) {
historizeAndCondition(cond);
}
} finally {
suppessReloadOnAndConditionAction = false;
}
}
String getAndConditionText() {
Object sel = andCondition.getSelectedItem();
if (sel == null) {
return "";
}
return sel.toString().trim();
}
private void adjustGui() {
if (this.association == null) {
joinPanel.setVisible(false);
onPanel.setVisible(false);
jLabel1.setText(" ");
jLabel4.setText(" ");
jLabel6.setVisible(false);
dropB.setVisible(false);
andLabel.setText(" Where ");
java.awt.GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 8;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridheight = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
} else {
join.setText(this.dataModel.getDisplayName(this.association.source));
on.setText(!this.association.reversed ? SqlUtil.reversRestrictionCondition(this.association.getUnrestrictedJoinCondition()) : this.association
.getUnrestrictedJoinCondition());
updateWhereField();
join.setToolTipText(join.getText());
on.setToolTipText(on.getText());
}
}
private class AllNonEmptyItem extends JMenuItem {
int todo;
int done;
private List<ActionListener> todoList = new ArrayList<ActionListener>();
private final String initText = "Counting rows... ";
AllNonEmptyItem() {
setEnabled(false);
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Component parent = SwingUtilities.getWindowAncestor(BrowserContentPane.this);
if (parent == null) {
parent = BrowserContentPane.this;
}
UIUtil.setWaitCursor(parent);
try {
Desktop.noArrangeLayoutOnNewTableBrowser = true;
Desktop.noArrangeLayoutOnNewTableBrowserWithAnchor = todoList.size() > 1;
Desktop.resetLastArrangeLayoutOnNewTableBrowser();
for (int i = 0; i < todoList.size(); ++i) {
if (i == todoList.size() - 1) {
Desktop.noArrangeLayoutOnNewTableBrowser = false;
}
todoList.get(i).actionPerformed(e);
}
} finally {
Desktop.noArrangeLayoutOnNewTableBrowser = false;
Desktop.noArrangeLayoutOnNewTableBrowserWithAnchor = false;
UIUtil.resetWaitCursor(parent);
}
}
});
}
public void rowsCounted(long count, ActionListener itemAction) {
++done;
if (count != 0) {
todoList.add(itemAction);
}
int p = todo > 0? (100 * done) / todo : 0;
if (done < todo) {
setText(initText + p + "%");
} else {
setText("All non-empty (" + todoList.size() + ")");
setEnabled(true);
}
}
public void setInitialText() {
if (todoList.isEmpty()) {
setText("All non-empty (0)");
} else {
setText(initText + "100%");
}
}
};
private String currentSelectedRowCondition = "";
/**
* Creates popup menu for navigation.
* @param navigateFromAllRows
* @param copyTCB
* @param runnable
* @param runnable
*/
public JPopupMenu createPopupMenu(final Row row, final int rowIndex, final int x, final int y, boolean navigateFromAllRows) {
return createPopupMenu(row, rowIndex, x, y, navigateFromAllRows, null, null);
}
/**
* Creates popup menu for navigation.
* @param navigateFromAllRows
* @param runnable
*/
public JPopupMenu createPopupMenu(final Row row, final int rowIndex, final int x, final int y, boolean navigateFromAllRows, JMenuItem altCopyTCB, final Runnable repaint) {
return createPopupMenu(row, rowIndex, x, y, navigateFromAllRows, altCopyTCB, repaint, true);
}
/**
* Creates popup menu for navigation.
* @param navigateFromAllRows
* @param runnable
*/
public JPopupMenu createPopupMenu(final Row row, final int rowIndex, final int x, final int y, boolean navigateFromAllRows, JMenuItem altCopyTCB, final Runnable repaint, final boolean withKeyStroke) {
JMenuItem tableFilter = new JCheckBoxMenuItem("Table Filter");
if (withKeyStroke) {
tableFilter.setAccelerator(KS_FILTER);
} else {
tableFilter.setVisible(false);
}
tableFilter.setSelected(isTableFilterEnabled);
if (isLimitExceeded) {
tableFilter.setForeground(Color.red);
tableFilter.setToolTipText("Row limit exceeded. Filtering may be incomplete.");
}
tableFilter.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
isTableFilterEnabled = !isTableFilterEnabled;
updateTableModel();
}
});
JMenuItem copyTCB;
if (altCopyTCB != null) {
copyTCB = altCopyTCB;
} else {
copyTCB = new JMenuItem("Copy to Clipboard");
if (withKeyStroke) {
copyTCB.setAccelerator(KS_COPY_TO_CLIPBOARD);
}
copyTCB.setEnabled(rowsTable.getSelectedColumnCount() > 0);
copyTCB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
UIUtil.copyToClipboard(rowsTable, true);
}
});
}
if (table instanceof SqlStatementTable && resultSetType == null) {
JPopupMenu jPopupMenu = new JPopupMenu();
if (row != null) {
JMenuItem det = new JMenuItem("Details");
if (withKeyStroke) {
det.setAccelerator(KS_DETAILS);
}
jPopupMenu.add(det);
jPopupMenu.add(new JSeparator());
det.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openDetailsView(rowIndex, x, y);
}
});
}
JMenu script = new JMenu("Create SQL");
script.setEnabled(false);
jPopupMenu.add(script);
jPopupMenu.addSeparator();
jPopupMenu.add(copyTCB);
jPopupMenu.addSeparator();
jPopupMenu.add(tableFilter);
JMenuItem editMode = new JMenuItem("Edit Mode");
if (withKeyStroke) {
editMode.setAccelerator(KS_EDIT);
}
jPopupMenu.add(editMode);
editMode.setEnabled(false);
return jPopupMenu;
}
List<String> assList = new ArrayList<String>();
Map<String, Association> assMap = new HashMap<String, Association>();
for (Association a : table.associations) {
int n = 0;
for (Association a2 : table.associations) {
if (a.destination == a2.destination) {
++n;
}
}
char c = ' ';
if (a.isIgnored()) {
c = '4';
} else if (a.isInsertDestinationBeforeSource()) {
c = '1';
} else if (a.isInsertSourceBeforeDestination()) {
c = '2';
} else {
c = '3';
}
String name = c + a.getDataModel().getDisplayName(a.destination) + (n > 1 ? " on " + a.getName() : "");
assList.add(name);
assMap.put(name, a);
}
Collections.sort(assList);
final Object context = new Object();
AllNonEmptyItem allNonEmpty = new AllNonEmptyItem();
JPopupMenu popup = new JPopupMenu();
popup = createNavigationMenu(popup, row, rowIndex, assList, assMap, "Parents", "1", navigateFromAllRows, 80, allNonEmpty, context);
popup = createNavigationMenu(popup, row, rowIndex, assList, assMap, "Children", "2", navigateFromAllRows, 60, allNonEmpty, context);
popup = createNavigationMenu(popup, row, rowIndex, assList, assMap, "Associated Rows", "3", navigateFromAllRows, 40, allNonEmpty, context);
popup = createNavigationMenu(popup, row, rowIndex, assList, assMap, "Detached Rows", "4", navigateFromAllRows, 40, allNonEmpty, context);
popup.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
cancel();
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
cancel();
}
private void cancel() {
CancellationHandler.cancelSilently(context);
getRunnableQueue().add(new RunnableWithPriority() {
@Override
public void run() {
CancellationHandler.reset(context);
}
@Override
public int getPriority() {
return 0;
}
});
}
});
if (!isPending && !rows.isEmpty()) {
popup.add(allNonEmpty);
allNonEmpty.setInitialText();
}
if (row != null) {
JMenuItem det = new JMenuItem("Details");
if (withKeyStroke) {
det.setAccelerator(KS_DETAILS);
}
popup.insert(det, 0);
popup.insert(new JSeparator(), 1);
det.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openDetailsView(rowIndex, x, y);
}
});
if (!(table instanceof SqlStatementTable) || resultSetType != null) {
if (popup.getComponentCount() > 0) {
popup.add(new JSeparator());
}
JMenuItem qb = new JMenuItem("Query Builder");
qb.setAccelerator(KS_QUERYBUILDER);
popup.add(qb);
qb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openQueryBuilder(false, SqlUtil.replaceAliases(row.rowId, "A", "A"));
}
});
JMenuItem sqlConsole = new JMenuItem("SQL Console");
sqlConsole.setAccelerator(KS_SQLCONSOLE);
popup.add(sqlConsole);
sqlConsole.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openQueryBuilder(true, SqlUtil.replaceAliases(row.rowId, "A", "A"));
}
});
if (!currentSelectedRowCondition.equals("")
&& currentSelectedRowCondition.equals(getAndConditionText())
&& rows.size() == 1) {
JMenuItem sr = new JMenuItem("Deselect Row");
popup.insert(sr, 0);
sr.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
andCondition.setSelectedItem("");
}
});
} else {
JMenuItem sr = new JMenuItem("Select Row");
sr.setEnabled(rows.size() > 1 && !row.rowId.isEmpty());
popup.insert(sr, 0);
sr.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selectRow(row);
}
});
}
JMenu sql = new JMenu("Create SQL");
final String rowName = !(table instanceof SqlStatementTable)? dataModel.getDisplayName(table) + "(" + SqlUtil.replaceAliases(row.rowId, null, null) + ")" : "";
JMenuItem update = new JMenuItem("Update");
sql.add(update);
update.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openSQLDialog("Update Row " + rowName, x, y, SQLDMLBuilder.buildUpdate(table, row, true, session));
}
});
JMenuItem insert = new JMenuItem("Insert");
sql.add(insert);
insert.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openSQLDialog("Insert Row " + rowName, x, y, SQLDMLBuilder.buildInsert(table, row, true, session));
}
});
JMenuItem insertNewRow = createInsertChildMenu(row, x, y);
sql.add(insertNewRow);
JMenuItem delete = new JMenuItem("Delete");
sql.add(delete);
delete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openSQLDialog("Delete Row " + rowName, x, y, SQLDMLBuilder.buildDelete(table, row, true, session));
}
});
insert.setEnabled(resultSetType == null);
update.setEnabled(resultSetType == null);
delete.setEnabled(resultSetType == null);
if (getQueryBuilderDialog() == null) {
popup.removeAll();
popup.add(det);
popup.addSeparator();
JMenu script = new JMenu("Create SQL");
popup.add(script);
if (table.getName() == null) {
script.setEnabled(false);
} else {
final String tableName = dataModel.getDisplayName(table);
script.add(update);
script.add(insert);
script.add(insertNewRow);
script.add(delete);
script.addSeparator();
JMenuItem updates = new JMenuItem("Updates (all rows)");
script.add(updates);
updates.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openSQLDialog("Update " + tableName, x, y, new Object() { @Override
public String toString() { return SQLDMLBuilder.buildUpdate(table, sortedAndFiltered(rows), session); }});
}
});
JMenuItem inserts = new JMenuItem("Inserts (all rows)");
script.add(inserts);
inserts.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openSQLDialog("Insert Into " + tableName, x, y, new Object() { @Override
public String toString() { return SQLDMLBuilder.buildInsert(table, sortedAndFiltered(rows), session); }});
}
});
JMenuItem deletes = new JMenuItem("Deletes (all rows)");
script.add(deletes);
deletes.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openSQLDialog("Delete from " + tableName, x, y, new Object() { @Override
public String toString() { return SQLDMLBuilder.buildDelete(table, sortedAndFiltered(rows), session); }
});
}
});
boolean hasPK = !rowIdSupport.getPrimaryKey(table).getColumns().isEmpty();
if (!hasPK) {
delete.setEnabled(false);
}
inserts.setEnabled(rows.size() > 0);
updates.setEnabled(hasPK && rows.size() > 0);
deletes.setEnabled(hasPK && rows.size() > 0);
}
} else {
popup.add(sql);
}
}
popup.addSeparator();
popup.add(copyTCB);
popup.addSeparator();
popup.add(tableFilter);
JCheckBoxMenuItem editMode = new JCheckBoxMenuItem("Edit Mode");
editMode.setEnabled(isTableEditable(table));
if (withKeyStroke) {
editMode.setAccelerator(KS_EDIT);
}
editMode.setSelected(isEditMode);
editMode.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setEditMode(!isEditMode);
updateTableModel();
if (repaint != null) {
SwingUtilities.invokeLater(repaint);
}
}
});
popup.add(editMode);
}
return popup;
}
/**
* Creates popup menu for SQL.
* @param forNavTree
* @param browserContentPane
*/
public JPopupMenu createSqlPopupMenu(final Row parentrow, final int rowIndex, final int x, final int y, boolean forNavTree, final Component parentComponent) {
JPopupMenu popup = new JPopupMenu();
JMenuItem qb = new JMenuItem("Query Builder");
qb.setAccelerator(KS_QUERYBUILDER);
popup.add(qb);
qb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openQueryBuilder(false);
}
});
JMenuItem sqlConsole = new JMenuItem("SQL Console");
sqlConsole.setAccelerator(KS_SQLCONSOLE);
popup.add(sqlConsole);
sqlConsole.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openQueryBuilder(true);
}
});
JMenu sqlDml = new JMenu("Create SQL");
popup.add(sqlDml);
final String tableName = dataModel.getDisplayName(table);
JMenuItem update = new JMenuItem("Updates");
sqlDml.add(update);
update.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openSQLDialog("Update " + tableName, x, y, new Object() { @Override
public String toString() { return SQLDMLBuilder.buildUpdate(table, sortedAndFiltered(rows), session); }});
}
});
JMenuItem insert = new JMenuItem("Inserts");
sqlDml.add(insert);
insert.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openSQLDialog("Insert Into " + tableName, x, y, new Object() { @Override
public String toString() { return SQLDMLBuilder.buildInsert(table, sortedAndFiltered(rows), session); }});
}
});
JMenuItem delete = new JMenuItem("Deletes");
sqlDml.add(delete);
delete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openSQLDialog("Delete from " + tableName, x, y, new Object() { @Override
public String toString() { return SQLDMLBuilder.buildDelete(table, sortedAndFiltered(rows), session); }});
}
});
boolean hasPK = !rowIdSupport.getPrimaryKey(table).getColumns().isEmpty();
insert.setEnabled(rows.size() > 0);
update.setEnabled(hasPK && rows.size() > 0);
delete.setEnabled(hasPK && rows.size() > 0);
popup.add(new JSeparator());
JMenuItem exportData = new JMenuItem("Export Data");
popup.add(exportData);
exportData.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openExtractionModelEditor(true);
}
});
JMenuItem extractionModel = new JMenuItem("Create Extraction Model");
popup.add(extractionModel);
extractionModel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openExtractionModelEditor(false);
}
});
popup.add(new JSeparator());
if (!forNavTree) {
JMenuItem det = new JMenuItem("Details");
det.setAccelerator(KS_DETAILS);
popup.add(det);
det.setEnabled(rows.size() > 0);
det.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openDetails(x, y);
}
});
}
// popup.add(new JSeparator());
JMenuItem snw = new JMenuItem("Show in New Window");
popup.add(snw);
snw.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
showInNewWindow();
}
});
JMenuItem al = new JMenuItem("Append Layout...");
popup.add(al);
al.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
appendLayout();
}
});
popup.addSeparator();
JMenuItem m = new JMenuItem("Hide (Minimize)");
popup.add(m);
m.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
onHide();
}
});
m = new JMenuItem("Close");
popup.add(m);
m.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
closeWithChildren(parentComponent);
}
});
popup.add(new JSeparator());
JMenuItem tableFilter = new JCheckBoxMenuItem("Table Filter");
tableFilter.setAccelerator(KS_FILTER);
tableFilter.setSelected(isTableFilterEnabled);
if (isLimitExceeded) {
tableFilter.setForeground(Color.red);
tableFilter.setToolTipText("Row limit exceeded. Filtering may be incomplete.");
}
tableFilter.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
isTableFilterEnabled = !isTableFilterEnabled;
updateTableModel();
}
});
popup.add(tableFilter);
JCheckBoxMenuItem editMode = new JCheckBoxMenuItem("Edit Mode");
editMode.setEnabled(isTableEditable(table));
editMode.setAccelerator(KS_EDIT);
editMode.setSelected(isEditMode);
editMode.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setEditMode(!isEditMode);
updateTableModel();
}
});
popup.add(editMode);
return popup;
}
protected boolean isTableEditable(Table theTable) {
return resultSetType != null || !rowIdSupport.getPrimaryKey(theTable).getColumns().isEmpty();
}
public boolean closeWithChildren(Component parentComponent) {
int count = countSubNodes(this);
Component parent = SwingUtilities.getWindowAncestor(this);
if (parent == null) {
parent = BrowserContentPane.this;
}
boolean closeThisToo = true;
if (count > 1) {
int o = JOptionPane.showOptionDialog(parentComponent, "Which tables do you want to close?", "Close",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
new Object[] {
"Only this table",
"This and related tables (" + (count) + ")",
"Related tables (" + (count - 1) + ")"
},
null);
if (o == 0) {
UIUtil.setWaitCursor(parent);
try {
close();
} finally {
UIUtil.resetWaitCursor(parent);
}
return true;
}
if (o == 1) {
closeThisToo = true;
} else if (o == 2) {
closeThisToo = false;
} else {
return false;
}
}
UIUtil.setWaitCursor(parent);
try {
closeSubTree(BrowserContentPane.this, closeThisToo);
} finally {
UIUtil.resetWaitCursor(parent);
}
return true;
}
private int countSubNodes(BrowserContentPane cp) {
int count = 0;
for (RowBrowser c: cp.getChildBrowsers()) {
count += countSubNodes(c.browserContentPane);
}
return count + 1;
}
private void closeSubTree(BrowserContentPane cp, boolean closeThisToo) {
for (RowBrowser c: cp.getChildBrowsers()) {
closeSubTree(c.browserContentPane, true);
}
if (closeThisToo) {
cp.close();
}
}
private JMenu createInsertChildMenu(Row row, final int x, final int y) {
JScrollMenu insertNewRow = new JScrollMenu("Insert Child");
if (table == null || table.getName() == null) {
insertNewRow.setEnabled(false);
return insertNewRow;
}
List<Association> tableAssociations = table.associations;
if (tableAssociations == null || tableAssociations.isEmpty()) {
// artificial table from SQL Console?
Table t = dataModel.getTable(table.getName());
if (t == null) {
insertNewRow.setEnabled(false);
return insertNewRow;
}
tableAssociations = t.associations;
}
List<Association> assocs = new ArrayList<Association>();
Map<Association, Row> children = new HashMap<Association, Row>();
if (tableAssociations != null) {
for (Association association: tableAssociations) {
Row child = createNewRow(row, table, association);
if (child != null) {
assocs.add(association);
children.put(association, child);
}
}
}
Collections.sort(assocs, new Comparator<Association>() {
@Override
public int compare(Association a, Association b) {
String dNameA = dataModel.getDisplayName(a.destination);
String dNameB = dataModel.getDisplayName(b.destination);
return dNameA.compareTo(dNameB);
}
});
for (int i = 0; i < assocs.size(); ++i) {
final Association association = assocs.get(i);
Association pred = i > 0? assocs.get(i - 1) : null;
Association succ = i < assocs.size() - 1? assocs.get(i + 1) : null;
final String dName = dataModel.getDisplayName(association.destination);
JMenuItem item;
if (pred != null && pred.destination == association.destination || succ != null && succ.destination == association.destination) {
item = new JMenuItem(dName + " on " + association.getName());
} else {
item = new JMenuItem(dName);
}
final Row child = children.get(association);
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openSQLDialog("Insert Child into " + dName, x, y, SQLDMLBuilder.buildInsert(association.destination, child, true, session));
}
});
insertNewRow.add(item);
}
insertNewRow.setEnabled(!assocs.isEmpty());
return insertNewRow;
}
void openExtractionModelEditor(boolean doExport) {
Component parent = SwingUtilities.getWindowAncestor(this);
if (parent == null) {
parent = this;
}
UIUtil.setWaitCursor(parent);
try {
String file;
String ts = new SimpleDateFormat("HH-mm-ss-SSS").format(new Date());
File newFile;
Table stable = table;
String subjectCondition;
QueryBuilderDialog.Relationship root = createQBRelations(false);
Collection<Association> restrictedAssociations = new HashSet<Association>();
Collection<Association> restrictedDependencies = new HashSet<Association>();
Collection<RestrictionDefinition> restrictedDependencyDefinitions = new HashSet<RestrictionDefinition>();
List<RestrictionDefinition> restrictionDefinitions = createRestrictions(root, stable, restrictedAssociations, restrictedDependencies, restrictedDependencyDefinitions);
// if (!restrictedDependencies.isEmpty()) {
Set<String> parents = new TreeSet<String>();
for (Association association: restrictedDependencies) {
parents.add(dataModel.getDisplayName(association.destination));
}
// String pList = "";
// int i = 0;
// for (String p: parents) {
// pList += p + "\n";
// if (++i > 20) {
// break;
// }
// }
final SbEDialog sbEDialog = new SbEDialog(SwingUtilities.getWindowAncestor(this),
(doExport? "Export rows and related rows from \"" : "Create Extraction Model for Subject \"") + dataModel.getDisplayName(stable) + "\".", (parents.isEmpty()? "" : ("\n\n" + parents.size() + " disregarded parent tables.")));
if (doExport) {
sbEDialog.setTitle("Export Data");
}
sbEDialog.regardButton.setVisible(!parents.isEmpty());
sbEDialog.dispose();
DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer() {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
Component result = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
if (value instanceof DefaultMutableTreeNode) {
if (!(((DefaultMutableTreeNode) value).getUserObject() instanceof String)) {
if (result instanceof JLabel) {
((JLabel) result).setForeground(Color.red);
} else {
((JLabel) result).setForeground(Color.black);
}
}
}
return result;
}
};
renderer.setOpenIcon(null);
renderer.setLeafIcon(null);
renderer.setClosedIcon(null);
sbEDialog.browserTree.setCellRenderer(renderer);
int[] count = new int[] { 0 };
DefaultTreeModel treeModel = new DefaultTreeModel(addChildNodes(this, restrictedDependencies, count));
sbEDialog.browserTree.setModel(treeModel);
for (int i = 0; i < count[0]; ++i) {
sbEDialog.browserTree.expandRow(i);
}
sbEDialog.browserTree.scrollRowToVisible(0);
sbEDialog.browserTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
sbEDialog.browserTree.getSelectionModel().clearSelection();
}
});
sbEDialog.grabFocus();
sbEDialog.setVisible(true);
if (!sbEDialog.ok) {
return;
}
if (sbEDialog.regardButton.isSelected()) {
restrictionDefinitions.removeAll(restrictedDependencyDefinitions);
for (Association a: restrictedDependencies) {
disableDisregardedNonParentsOfDestination(a, restrictedAssociations, restrictionDefinitions);
}
}
// int option = JOptionPane.showOptionDialog(parent, "Disregarded parent tables:\n\n" + pList + "\n", "Disregarded parent tables", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new Object[] { "regard parent tables", "Ok" }, "regard parent tables");
// switch (option) {
// case 0:
// restrictionDefinitions.removeAll(restrictedDependencyDefinitions);
// for (Association a: restrictedDependencies) {
// disableDisregardedNonParentsOfDestination(a, restrictedAssociations, restrictionDefinitions);
// }
// break;
// case 1:
// break;
// default: return;
// }
// }
subjectCondition = root.whereClause;
if (doExport && (getParentBrowser() != null /* || isLimitExceeded */)) {
subjectCondition = root.whereClause;
if (subjectCondition != null) {
subjectCondition = subjectCondition.replace('\r', ' ').replace('\n', ' ');
}
StringBuilder sb = new StringBuilder();
boolean f = true;
for (Row row: rows) {
if (f) {
f = false;
} else {
sb.append(" or ");
}
sb.append("(" + row.rowId + ")");
}
if (subjectCondition != null && subjectCondition.trim().length() > 0) {
subjectCondition = "(" + subjectCondition + ") and (" + sb + ")";
} else {
subjectCondition = sb.toString();
}
}
if (subjectCondition == null) {
subjectCondition = "";
}
// if (doExport && isLimitExceeded && rows != null && !rows.isEmpty()) {
// StringBuilder sb = new StringBuilder();
// boolean f = true;
// for (Row row: rows) {
// if (f) {
// f = false;
// } else {
// sb.append(" or ");
// }
// sb.append("(" + row.rowId + ")");
// }
// subjectCondition = sb.toString();
// }
subjectCondition = SqlUtil.replaceAliases(subjectCondition, "T", "T");
for (int i = 1; ; ++i) {
file = Environment.newFile("extractionmodel" + File.separator + "by-example").getPath();
newFile = new File(file);
newFile.mkdirs();
file += File.separator + "SbE-" + (dataModel.getDisplayName(stable).replaceAll("[\"'\\[\\]]", "")) + "-" + ts + (i > 1? "-" + Integer.toString(i) : "") + ".jm";
newFile = new File(file);
if (!newFile.exists()) {
break;
}
}
Map<String, Map<String, double[]>> positions = new TreeMap<String, Map<String,double[]>>();
collectPositions(positions);
String currentModelSubfolder = DataModelManager.getCurrentModelSubfolder(executionContext);
dataModel.save(file, stable, subjectCondition, ScriptFormat.SQL, restrictionDefinitions, positions, new ArrayList<ExtractionModel.AdditionalSubject>(), currentModelSubfolder);
ExtractionModelFrame extractionModelFrame = ExtractionModelFrame.createFrame(file, false, !doExport, null, executionContext);
extractionModelFrame.setDbConnectionDialogClone(getDbConnectionDialog());
if (doExport) {
extractionModelFrame.openExportDialog(false, new Runnable() {
@Override
public void run() {
try {
reloadDataModel();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
extractionModelFrame.dispose();
} else {
extractionModelFrame.markDirty();
extractionModelFrame.expandAll();
}
newFile.delete();
} catch (Throwable e) {
UIUtil.showException(this, "Error", e, session);
} finally {
UIUtil.resetWaitCursor(parent);
}
}
private DefaultMutableTreeNode addChildNodes(BrowserContentPane browserContentPane, Collection<Association> restrictedDependencies, int[] count) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(dataModel.getDisplayName(browserContentPane.table));
count[0]++;
Set<Table> regardedChildren = new HashSet<Table>();
for (RowBrowser rb: browserContentPane.getChildBrowsers()) {
DefaultMutableTreeNode childNode = addChildNodes(rb.browserContentPane, restrictedDependencies, count);
node.add(childNode);
regardedChildren.add(rb.browserContentPane.table);
}
for (final Association dep: restrictedDependencies) {
if (dep.source == browserContentPane.table && !regardedChildren.contains(dep.destination)) {
node.add(new DefaultMutableTreeNode(new Object() {
String item = dataModel.getDisplayName(dep.destination);
@Override
public String toString() {
return item;
}
}));
count[0]++;
}
}
return node;
}
private void disableDisregardedNonParentsOfDestination(Association a,
Collection<Association> regardedAssociations,
List<RestrictionDefinition> restrictionDefinitions) {
for (Association npa: a.destination.associations) {
if (!regardedAssociations.contains(npa)) {
regardedAssociations.add(npa);
if (npa.isInsertDestinationBeforeSource()) {
disableDisregardedNonParentsOfDestination(npa, regardedAssociations, restrictionDefinitions);
} else {
RestrictionDefinition rest = new RestrictionDefinition(npa.source, npa.destination, npa.getName(), null, true);
restrictionDefinitions.add(rest);
}
}
}
}
private static class RestrictionLiteral {
public String condition;
public int distanceFromRoot;
public boolean isIgnored;
public boolean isIgnoredIfReversalIsRestricted = false;
@Override
public String toString() {
return "Cond:" + condition + " Dist: " + distanceFromRoot + " isIgnored: " + isIgnored + " isIgnoredIfReversalIsRestricted: " + isIgnoredIfReversalIsRestricted;
}
}
/**
* Creates restriction according to the given {@link Relationship} tree.
*
* @param root root of tree
* @return restrictions
*/
private List<RestrictionDefinition> createRestrictions(Relationship root, Table subject, Collection<Association> regardedAssociations, Collection<Association> restrictedDependencies, Collection<RestrictionDefinition> restrictedDependencyDefinitions) {
List<RestrictionDefinition> restrictionDefinitions = new ArrayList<RestrictionDefinition>();
Map<Association, List<RestrictionLiteral>> restrictionLiterals = new HashMap<Association, List<RestrictionLiteral>>();
collectRestrictionLiterals(restrictionLiterals, root, subject, 0);
for (Association association: restrictionLiterals.keySet()) {
RestrictionDefinition rest = createRestrictionDefinition(association, restrictionLiterals, true);
regardedAssociations.add(association);
if (rest.isIgnored || (rest.condition != null && rest.condition.trim().length() != 0)) {
restrictionDefinitions.add(rest);
if (association.isInsertDestinationBeforeSource() && rest.isIgnored) {
restrictedDependencies.add(association);
restrictedDependencyDefinitions.add(rest);
}
}
}
return restrictionDefinitions;
}
private RestrictionDefinition createRestrictionDefinition(Association association, Map<Association, List<RestrictionLiteral>> restrictionLiterals, boolean checkReversal) {
List<RestrictionLiteral> lits = restrictionLiterals.get(association);
boolean useDistance = false;
boolean hasTrue = false;
boolean hasNotTrue = false;
boolean hasNotFalse = false;
Integer lastDist = null;
for (RestrictionLiteral l: lits) {
if (l.isIgnoredIfReversalIsRestricted) {
if (checkReversal) {
RestrictionDefinition revRest = createRestrictionDefinition(association.reversalAssociation, restrictionLiterals, false);
if (revRest.isIgnored || (revRest.condition != null && revRest.condition.trim().length() > 0)) {
l.isIgnored = true;
} else {
l.isIgnored = false;
l.condition = null;
}
l.isIgnoredIfReversalIsRestricted = false;
} else {
l.isIgnored = true;
l.isIgnoredIfReversalIsRestricted = false;
}
}
// disabled since 5.0
// if (lastDist != null && lastDist != l.distanceFromRoot) {
// useDistance = true;
// }
// lastDist = l.distanceFromRoot;
if (!l.isIgnored) {
hasNotFalse = true;
if (l.condition == null || l.condition.trim().length() == 0) {
hasTrue = true;
} else {
hasNotTrue = true;
}
} else {
hasNotTrue = true;
}
}
boolean isIgnored;
String condition = null;
if (!hasNotFalse) {
isIgnored = true;
} else if (!hasNotTrue) {
isIgnored = false;
} else if (hasTrue && !useDistance) {
isIgnored = false;
} else {
for (RestrictionLiteral l: lits) {
if (!l.isIgnored) {
String c = null;
if (useDistance) {
c = l.distanceFromRoot == 0? "A.$IS_SUBJECT" : ("A.$DISTANCE=" + l.distanceFromRoot);
}
if (l.condition != null && l.condition.trim().length() > 0) {
if (c == null) {
c = l.condition;
} else {
c = c + " and (" + l.condition + ")";
}
}
if (condition == null) {
condition = c;
} else {
condition += " or " + c;
}
}
}
isIgnored = false;
}
RestrictionDefinition rest = new RestrictionDefinition(association.source, association.destination, association.getName(), condition, isIgnored);
return rest;
}
/**
* Collects restriction literals per association according to a given {@link Relationship} tree.
*
* @param restrictionLiterals to put literals into
* @param root root of tree
* @param distanceFromRoot distance
*/
private void collectRestrictionLiterals(Map<Association, List<RestrictionLiteral>> restrictionLiterals, Relationship root, Table subject, int distanceFromRoot) {
for (Association association: subject.associations) {
List<Relationship> children = new ArrayList<QueryBuilderDialog.Relationship>();
for (Relationship r: root.children) {
if (r.association == association) {
children.add(r);
}
}
if (children.isEmpty()) {
children.add(null);
}
for (Relationship child: children) {
RestrictionLiteral restrictionLiteral = new RestrictionLiteral();
restrictionLiteral.distanceFromRoot = distanceFromRoot;
restrictionLiteral.isIgnored = false;
if (child == null) {
restrictionLiteral.isIgnored = true;
// if (association.isInsertDestinationBeforeSource()) {
if (root.association != null && association == root.association.reversalAssociation) {
if (association.getCardinality() == Cardinality.MANY_TO_ONE
||
association.getCardinality() == Cardinality.ONE_TO_ONE) {
restrictionLiteral.isIgnoredIfReversalIsRestricted = true;
}
}
// }
} else {
restrictionLiteral.condition = child.whereClause == null? "" : SqlUtil.replaceAliases(child.whereClause, "B", "A");
collectRestrictionLiterals(restrictionLiterals, child, association.destination, distanceFromRoot + 1);
}
List<RestrictionLiteral> literals = restrictionLiterals.get(association);
if (literals == null) {
literals = new ArrayList<BrowserContentPane.RestrictionLiteral>();
restrictionLiterals.put(association, literals);
}
literals.add(restrictionLiteral);
}
}
}
private void openSQLDialog(String titel, int x, int y, Object sql) {
UIUtil.setWaitCursor(this);
JDialog d;
try {
String LF = System.getProperty("line.separator", "\n");
String sqlString = sql.toString().trim() + LF;
if (sqlString.length() > 10L*1024L*1024L) {
int o = JOptionPane.showOptionDialog(this, "SQL Script is large (" + (sqlString.length() / 1024) + " KB)", "SQL Script is large", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new Object[] { "Open", "Cancel", "Save Script" }, "Save Script");
if (o == 2) {
String fn = UIUtil.choseFile(null, ".", "Save SQL Script", ".sql", this, false, false, false);
if (fn != null) {
try {
PrintWriter out = new PrintWriter(new FileWriter(fn));
out.print(sqlString);
out.close();
} catch (Throwable e) {
UIUtil.showException(this, "Error saving script", e, UIUtil.EXCEPTION_CONTEXT_USER_ERROR);
}
}
}
if (o != 0) {
return;
}
}
d = new JDialog(getOwner(), "Create SQL - " + titel, true);
d.getContentPane().add(new SQLDMLPanel(sqlString, getSqlConsole(false), session, getMetaDataSource(),
new Runnable() {
@Override
public void run() {
reloadRows();
}
},
new Runnable() {
@Override
public void run() {
getSqlConsole(true);
}
},
d, executionContext));
d.pack();
d.setLocation(x - 50, y - 100);
d.setSize(700, Math.max(d.getHeight() + 20, 400));
d.setLocation(getOwner().getX() + (getOwner().getWidth() - d.getWidth()) / 2, Math.max(0, getOwner().getY() + (getOwner().getHeight() - d.getHeight()) / 2));
UIUtil.fit(d);
} catch (Throwable e) {
UIUtil.showException(this, "Error", e);
return;
} finally {
UIUtil.resetWaitCursor(this);
}
d.setVisible(true);
}
protected abstract SQLConsole getSqlConsole(boolean switchToConsole);
private void appendClosure() {
if (getParentBrowser() != null) {
BrowserContentPane parentContentPane = getParentBrowser().browserContentPane;
Set<Pair<BrowserContentPane, Row>> newElements = new HashSet<Pair<BrowserContentPane, Row>>();
for (Pair<BrowserContentPane, Row> e: rowsClosure.currentClosure) {
if (e.a == parentContentPane) {
parentContentPane.findClosure(e.b, newElements, true);
}
}
rowsClosure.currentClosure.addAll(newElements);
rowsClosure.currentClosureRowIDs.clear();
for (Pair<BrowserContentPane, Row> r: rowsClosure.currentClosure) {
rowsClosure.currentClosureRowIDs.add(new Pair<BrowserContentPane, String>(r.a, r.b.nonEmptyRowId));
}
rowsTable.repaint();
adjustClosure(null, this);
}
}
protected void setCurrentRowSelectionAndReloadChildrenIfLimitIsExceeded(int i) {
setCurrentRowSelection(i);
if (i >= 0) {
reloadChildrenIfLimitIsExceeded();
}
}
protected void setCurrentRowSelection(int i) {
currentRowSelection = i;
if (i >= 0) {
Row row = rows.get(rowsTable.getRowSorter().convertRowIndexToModel(i));
rowsClosure.currentClosure.clear();
rowsClosure.parentPath.clear();
rowsClosure.currentClosureRootID = row.nonEmptyRowId;
findClosure(row);
Rectangle visibleRect = rowsTable.getVisibleRect();
Rectangle pos = rowsTable.getCellRect(i, 0, false);
rowsTable.scrollRectToVisible(new Rectangle(visibleRect.x, pos.y, 1, pos.height));
}
rowsClosure.currentClosureRowIDs.clear();
for (Pair<BrowserContentPane, Row> r: rowsClosure.currentClosure) {
rowsClosure.currentClosureRowIDs.add(new Pair<BrowserContentPane, String>(r.a, r.b.nonEmptyRowId));
}
rowsTable.repaint();
adjustClosure(this, null);
}
private void reloadChildrenIfLimitIsExceeded() {
for (RowBrowser ch: getChildBrowsers()) {
if (ch.browserContentPane != null) {
if (ch.browserContentPane.isLimitExceeded) {
ch.browserContentPane.reloadRows("because rows limit is exceeded");
} else {
ch.browserContentPane.reloadChildrenIfLimitIsExceeded();
}
}
}
}
private JPopupMenu createNavigationMenu(JPopupMenu popup, final Row row, final int rowIndex, List<String> assList, Map<String, Association> assMap,
String title, String prefix, final boolean navigateFromAllRows, final int rowCountPriority, final AllNonEmptyItem allNonEmptyItem, final Object context) {
JScrollC2Menu nav = new JScrollC2Menu(title);
if (prefix.equals("1")) {
nav.setIcon(UIUtil.scaleIcon(this, redDotIcon));
}
if (prefix.equals("2")) {
nav.setIcon(UIUtil.scaleIcon(this, greenDotIcon));
}
if (prefix.equals("3")) {
nav.setIcon(UIUtil.scaleIcon(this, blueDotIcon));
}
if (prefix.equals("4")) {
nav.setIcon(UIUtil.scaleIcon(this, greyDotIcon));
}
JMenu current = nav;
int l = 0;
for (String name : assList) {
if (!name.startsWith(prefix)) {
continue;
}
final Association association = assMap.get(name);
++l;
final JMenuItem item = new JMenuItem(" " + (name.substring(1)) + " ");
item.setToolTipText(association.getUnrestrictedJoinCondition());
final JLabel countLabel = new JLabel(". >99999 ") {
@Override
public void paint(Graphics g) {
if (!getText().startsWith(".")) {
super.paint(g);
}
}
};
boolean excludeFromANEmpty = false;
for (RowBrowser child: getChildBrowsers()) {
if (association == child.association) {
if (rowIndex < 0 && child.rowIndex < 0 || rowIndex == child.rowIndex) {
item.setFont(new Font(item.getFont().getName(), item.getFont().getStyle() | Font.ITALIC, item.getFont().getSize()));
excludeFromANEmpty = true;
break;
}
}
}
final ActionListener itemAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
highlightedRows.add(rowIndex);
if (navigateFromAllRows) {
navigateTo(association, -1, null);
} else {
navigateTo(association, rowIndex, row);
}
}
};
item.addActionListener(itemAction);
if (!excludeFromANEmpty) {
allNonEmptyItem.todo++;
}
final boolean fExcludeFromANEmpty = excludeFromANEmpty;
if (!isPending && !rows.isEmpty()) {
getRunnableQueue().add(new RunnableWithPriority() {
final int MAX_RC = 1000;
@Override
public int getPriority() {
return rowCountPriority;
}
@Override
public void run() {
List<Row> r;
Pair<String, Association> key;
if (rowIndex < 0) {
r = rows;
key = new Pair<String, Association>("", association);
} else {
r = Collections.singletonList(row);
key = new Pair<String, Association>(row.nonEmptyRowId, association);
}
Pair<RowCount, Long> cachedCount = rowCountCache.get(key);
RowCount rowCount;
if (cachedCount != null && cachedCount.b > System.currentTimeMillis()) {
rowCount = cachedCount.a;
} else {
RowCounter rc = new RowCounter(table, association, r, session, rowIdSupport);
try {
rowCount = rc.countRows(getAndConditionText(), context, MAX_RC + 1, false);
} catch (SQLException e) {
rowCount = new RowCount(-1, true);
}
rowCountCache.put(key, new Pair<RowCount, Long>(rowCount, System.currentTimeMillis() + MAX_ROWCOUNTCACHE_RETENTION_TIME));
}
final RowCount count = rowCount;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
String cs = " " + (count.count < 0? "?" : (count.count > MAX_RC)? (">" + MAX_RC) : count.isExact? count.count : (">" + count.count)) + " ";
countLabel.setText(cs);
if (count.count == 0) {
countLabel.setForeground(Color.lightGray);
}
if (!fExcludeFromANEmpty) {
allNonEmptyItem.rowsCounted(count.count, itemAction);
}
}
});
}
});
}
if (current != null) {
GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = l;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
current.getPopupMenu().add(item, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = l;
gridBagConstraints.fill = java.awt.GridBagConstraints.NONE;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weightx = 1.0;
current.getPopupMenu().add(countLabel, gridBagConstraints);
} else {
popup.add(item);
}
}
if (l > 0) {
popup.add(nav);
}
return popup;
}
private long lastReloadTS = 0;
/**
* Reloads rows.
*/
public void reloadRows() {
reloadRows(null);
}
/**
* Reloads rows.
*/
public void reloadRows(String cause) {
if (!suppressReload) {
lastReloadTS = System.currentTimeMillis();
cancelLoadJob(true);
setPendingState(true, true);
rows.clear();
updateMode("loading", cause);
setPendingState(false, false);
int limit = getReloadLimit();
LoadJob reloadJob;
if (statementForReloading != null) {
reloadJob = new LoadJob(limit, statementForReloading, getParentBrowser(), false);
} else {
reloadJob = new LoadJob(limit, (table instanceof SqlStatementTable)? "" : getAndConditionText(), getParentBrowser(), selectDistinctCheckBox.isSelected());
}
synchronized (this) {
currentLoadJob = reloadJob;
}
getRunnableQueue().add(reloadJob);
}
}
/**
* Reload rows from {@link #table}.
*
* @param rows
* to put the rows into
* @param loadJob
* cancellation context
* @param limit
* row number limit
*/
private void reloadRows(ResultSet inputResultSet, String andCond, final List<Row> rows, LoadJob loadJob, int limit, boolean selectDistinct) throws SQLException {
try {
session.setSilent(true);
reloadRows(inputResultSet, andCond, rows, loadJob, limit, selectDistinct, null);
return;
} catch (Throwable e) { // embedded DBMS may throw non-SQLException
Session._log.warn("failed, try another strategy (" + e.getMessage() + ")");
} finally {
session.setSilent(false);
}
Set<String> existingColumnsLowerCase = null;
if (!(table instanceof SqlStatementTable) && statementForReloading == null) {
existingColumnsLowerCase = findColumnsLowerCase(table, session);
}
reloadRows(inputResultSet, andCond, rows, loadJob, limit, selectDistinct, existingColumnsLowerCase);
}
/**
* Finds the columns of a given {@link Table}.
*
* @param table the table
* @param session the statement executor for executing SQL-statements
*/
private Set<String> findColumnsLowerCase(Table table, Session session) {
try {
Set<String> columns = new HashSet<String>();
DatabaseMetaData metaData = session.getMetaData();
Quoting quoting = new Quoting(session);
String defaultSchema = JDBCMetaDataBasedModelElementFinder.getDefaultSchema(session, session.getSchema());
String schema = quoting.unquote(table.getOriginalSchema(defaultSchema));
String tableName = quoting.unquote(table.getUnqualifiedName());
ResultSet resultSet = JDBCMetaDataBasedModelElementFinder.getColumns(session, metaData, schema, tableName, "%", false, null);
while (resultSet.next()) {
String colName = resultSet.getString(4).toLowerCase();
columns.add(colName);
}
resultSet.close();
if (columns.isEmpty()) {
if (session.getMetaData().storesUpperCaseIdentifiers()) {
schema = schema.toUpperCase();
tableName = tableName.toUpperCase();
} else {
schema = schema.toLowerCase();
tableName = tableName.toLowerCase();
}
resultSet = JDBCMetaDataBasedModelElementFinder.getColumns(session, metaData, schema, tableName, "%", false, null);
while (resultSet.next()) {
String colName = resultSet.getString(4).toLowerCase();
columns.add(colName);
}
}
if (columns.isEmpty()) {
return null;
}
return columns;
} catch (Exception e) {
return null;
}
}
/**
* Reload rows from {@link #table}.
*
* @param rows
* to put the rows into
* @param loadJob
* cancellation context
* @param limit
* row number limit
*/
private void reloadRows(ResultSet inputResultSet, String andCond, final List<Row> rows, LoadJob loadJob, int limit, boolean selectDistinct, Set<String> existingColumnsLowerCase) throws SQLException {
if (table instanceof SqlStatementTable || statementForReloading != null) {
try {
session.setSilent(true);
Map<String, List<Row>> rowsMap = new HashMap<String, List<Row>>();
reloadRows(inputResultSet, null, andCond, null, rowsMap, loadJob, limit, false, null, existingColumnsLowerCase);
if (rowsMap.get("") != null) {
rows.addAll(rowsMap.get(""));
}
} finally {
session.setSilent(false);
}
return;
}
List<Row> pRows = parentRows;
if (pRows == null) {
pRows = Collections.singletonList(parentRow);
} else {
pRows = new ArrayList<Row>(pRows);
}
Map<String, Row> rowSet = new HashMap<String, Row>();
loadJob.checkCancellation();
if (parentRows != null) {
beforeReload();
}
noNonDistinctRows = 0;
noDistinctRows = 0;
if (association != null && rowIdSupport.getPrimaryKey(association.source, session).getColumns().isEmpty()) {
loadRowBlocks(inputResultSet, null, andCond, rows, loadJob, limit, selectDistinct, pRows, rowSet, 1, existingColumnsLowerCase);
} else {
if (useInlineViewForResolvingAssociation(session)) {
try {
InlineViewStyle inlineViewStyle = session.getInlineViewStyle();
if (inlineViewStyle != null) {
loadRowBlocks(inputResultSet, inlineViewStyle, andCond, rows, loadJob, limit, selectDistinct, pRows, rowSet, 510, existingColumnsLowerCase);
return;
}
} catch (Throwable e) { // embedded DBMS may throw non-SQLException
Session._log.warn("failed, try another blocking-size (" + e.getMessage() + ")");
}
}
try {
loadRowBlocks(inputResultSet, null, andCond, rows, loadJob, limit, selectDistinct, pRows, rowSet, 510, existingColumnsLowerCase);
return;
} catch (Throwable e) { // embedded DBMS may throw non-SQLException
Session._log.warn("failed, try another blocking-size (" + e.getMessage() + ")");
}
try {
loadRowBlocks(inputResultSet, null, andCond, rows, loadJob, limit, selectDistinct, pRows, rowSet, 300, existingColumnsLowerCase);
return;
} catch (Throwable e) { // embedded DBMS may throw non-SQLException
Session._log.warn("failed, try another blocking-size (" + e.getMessage() + ")");
}
try {
loadRowBlocks(inputResultSet, null, andCond, rows, loadJob, limit, selectDistinct, pRows, rowSet, 100, existingColumnsLowerCase);
return;
} catch (Throwable e) { // embedded DBMS may throw non-SQLException
Session._log.warn("failed, try another blocking-size (" + e.getMessage() + ")");
}
try {
loadRowBlocks(inputResultSet, null, andCond, rows, loadJob, limit, selectDistinct, pRows, rowSet, 40, existingColumnsLowerCase);
return;
} catch (Throwable e) { // embedded DBMS may throw non-SQLException
Session._log.warn("failed, try another blocking-size (" + e.getMessage() + ")");
}
}
loadRowBlocks(inputResultSet, null, andCond, rows, loadJob, limit, selectDistinct, pRows, rowSet, 1, existingColumnsLowerCase);
}
static boolean useInlineViewForResolvingAssociation(Session session) {
return session.dbms.isUseInlineViewsInDataBrowser();
}
private void loadRowBlocks(ResultSet inputResultSet, InlineViewStyle inlineViewStyle, String andCond, final List<Row> rows, LoadJob loadJob, int limit, boolean selectDistinct, List<Row> pRows,
Map<String, Row> rowSet, int NUM_PARENTS, Set<String> existingColumnsLowerCase) throws SQLException {
List<List<Row>> parentBlocks = new ArrayList<List<Row>>();
List<Row> currentBlock = new ArrayList<Row>();
Set<String> regPRows = new HashSet<String>();
Map<Row, Integer> parentRowIndex = new IdentityHashMap<Row, Integer>();
for (int i = 0; i < pRows.size(); ++i) {
parentRowIndex.put(pRows.get(i), i);
}
parentBlocks.add(currentBlock);
BrowserContentPane parentPane = null;
if (getParentBrowser() != null) {
parentPane = getParentBrowser().browserContentPane;
}
for (boolean inClosure: new boolean[] { true, false }) {
boolean firstNonClosure = false;
for (Row pRow : pRows) {
if (parentPane != null) {
if (rowsClosure.currentClosure.contains(new Pair<BrowserContentPane, Row>(parentPane, pRow))) {
if (!inClosure) {
continue;
}
} else {
if (inClosure) {
continue;
}
}
} else if (!inClosure) {
break;
}
if (currentBlock.size() >= NUM_PARENTS || (!inClosure && !firstNonClosure)) {
if (!currentBlock.isEmpty()) {
currentBlock = new ArrayList<Row>();
parentBlocks.add(currentBlock);
}
if (!inClosure) {
firstNonClosure = true;
}
}
currentBlock.add(pRow);
}
}
int parentIndex = 0;
if (!pRows.isEmpty()) for (List<Row> pRowBlockI : parentBlocks) {
List<Row> pRowBlock = pRowBlockI;
Map<String, List<Row>> newBlockRows = new HashMap<String, List<Row>>();
boolean loaded = false;
if (pRowBlock.size() == 1 && pRowBlock.get(0) == null) {
pRowBlock = null;
}
if (session.dbms.getSqlLimitSuffix() != null) {
try {
session.setSilent(true);
reloadRows(inputResultSet, inlineViewStyle, andCond, pRowBlock, newBlockRows, loadJob, limit, false, session.dbms.getSqlLimitSuffix(), existingColumnsLowerCase);
loaded = true;
} catch (Throwable e) { // embedded DBMS may throw non-SQLException
Session._log.warn("failed, try another limit-strategy (" + e.getMessage() + ")");
} finally {
session.setSilent(false);
}
}
if (!loaded) {
try {
session.setSilent(true);
reloadRows(inputResultSet, inlineViewStyle, andCond, pRowBlock, newBlockRows, loadJob, limit, true, null, existingColumnsLowerCase);
loaded = true;
} catch (Throwable e) { // embedded DBMS may throw non-SQLException
Session._log.warn("failed, try another limit-strategy (" + e.getMessage() + ")");
} finally {
session.setSilent(false);
}
if (!loaded) {
try {
session.setSilent(true);
reloadRows(inputResultSet, inlineViewStyle, andCond, pRowBlock, newBlockRows, loadJob, limit, false, null, existingColumnsLowerCase);
} finally {
session.setSilent(false);
}
}
}
if (pRowBlock == null) {
pRowBlock = new ArrayList<Row>();
pRowBlock.add(null);
}
for (Row pRow: pRowBlock) {
loadJob.checkCancellation();
boolean dupParent = false;
if (pRow != null) {
if (regPRows.contains(pRow.nonEmptyRowId)) {
dupParent = true;
}
regPRows.add(pRow.nonEmptyRowId);
}
List<Row> newRows = new ArrayList<Row>();
String rId = pRow == null? "" : pRow.nonEmptyRowId;
if (newBlockRows.get(rId) != null) {
newRows.addAll(newBlockRows.get(rId));
}
sortNewRows(newRows);
if (parentRows != null) {
if (!newRows.isEmpty()) {
Integer i = parentRowIndex.get(pRow);
for (Row r: newRows) {
r.setParentModelIndex(i != null? i : parentIndex);
}
}
++parentIndex;
for (Row row : newRows) {
Row exRow = rowSet.get(row.nonEmptyRowId);
if (!dupParent) {
if (exRow != null) {
++noNonDistinctRows;
} else {
++noDistinctRows;
}
}
if (exRow != null && (selectDistinct || dupParent)) {
addRowToRowLink(pRow, exRow);
} else {
rows.add(row);
addRowToRowLink(pRow, row);
rowSet.put(row.nonEmptyRowId, row);
--limit;
}
}
} else {
rows.addAll(newRows);
limit -= newRows.size();
}
if (limit <= 0) {
if (parentPane != null) {
if (rowsClosure.currentClosure.contains(new Pair<BrowserContentPane, Row>(parentPane, pRow))) {
loadJob.closureLimitExceeded = true;
}
}
break;
}
}
if (limit <= 0) {
break;
}
}
}
private void sortNewRows(List<Row> newRows) {
if (rowsTable != null && rowsTable.getRowSorter() != null) {
List<? extends SortKey> sk = rowsTable.getRowSorter().getSortKeys();
final int col;
final boolean asc;
if (!sk.isEmpty()) {
col = sk.get(0).getColumn();
asc = sk.get(0).getSortOrder() == SortOrder.ASCENDING;
} else {
col = getDefaultSortColumn();
asc = true;
}
if (col >= 0) {
Collections.sort(newRows, new Comparator<Row>() {
@Override
public int compare(Row a, Row b) {
Object va = null;
if (a != null && a.values != null && a.values.length > col) {
va = a.values[col];
}
Object vb = null;
if (b != null && b.values != null && b.values.length > col) {
vb = b.values[col];
}
if (va == null && vb == null) {
return 0;
}
if (va == null) {
return -1;
}
if (vb == null) {
return 1;
}
if (va.getClass().equals(vb.getClass())) {
if (va instanceof Comparable<?>) {
int cmp = ((Comparable<Object>) va).compareTo(vb);
return asc? cmp : -cmp;
}
return 0;
}
int cmp = va.getClass().getName().compareTo(vb.getClass().getName());
return asc? cmp : -cmp;
}
});
}
}
}
/**
* Reload rows from {@link #table}.
*
* @param rows
* to put the rows into
* @param context
* cancellation context
* @param rowCache
* @param allPRows
*/
private void reloadRows(ResultSet inputResultSet, InlineViewStyle inlineViewStyle, String andCond, final List<Row> parentRows, final Map<String, List<Row>> rows, LoadJob loadJob, int limit, boolean useOLAPLimitation,
String sqlLimitSuffix, Set<String> existingColumnsLowerCase) throws SQLException {
reloadRows0(inputResultSet, inlineViewStyle, andCond, parentRows, rows, loadJob, parentRows == null? limit : Math.max(5000, limit), useOLAPLimitation, sqlLimitSuffix, existingColumnsLowerCase);
}
/**
* Gets qualified table name.
*
* @param t the table
* @return qualified name of t
*/
private String qualifiedTableName(Table t, Quoting quoting) {
String schema = t.getSchema("");
if (schema.length() == 0) {
return quoting.requote(t.getUnqualifiedName());
}
return quoting.requote(schema) + "." + quoting.requote(t.getUnqualifiedName());
}
/**
* Reload rows from {@link #table}.
*
* @param rows
* to put the rows into
* @param loadJob
* cancellation context
*/
private void reloadRows0(ResultSet inputResultSet, InlineViewStyle inlineViewStyle, String andCond, final List<Row> parentRows, final Map<String, List<Row>> rows, LoadJob loadJob, int limit, boolean useOLAPLimitation,
String sqlLimitSuffix, Set<String> existingColumnsLowerCase) throws SQLException {
String sql = "Select ";
final Quoting quoting = new Quoting(session);
final Set<String> pkColumnNames = new HashSet<String>();
final Set<String> parentPkColumnNames = new HashSet<String>();
final boolean selectParentPK = association != null && parentRows != null && parentRows.size() > 1;
final Set<Integer> unknownColumnIndexes = new HashSet<Integer>();
int numParentPKColumns = 0;
if (table instanceof SqlStatementTable || statementForReloading != null) {
sql = andCond;
if (!(table instanceof SqlStatementTable)) {
for (Column pk: rowIdSupport.getPrimaryKey(table, session).getColumns()) {
pkColumnNames.add(quoting.requote(pk.name));
}
} else {
table.setColumns(new ArrayList<Column>());
}
} else {
String olapPrefix = "Select ";
String olapSuffix = ") S Where S." + ROWNUMBERALIAS + " <= " + limit;
boolean limitSuffixInSelectClause = sqlLimitSuffix != null &&
(sqlLimitSuffix.toLowerCase().startsWith("top ") || sqlLimitSuffix.toLowerCase().startsWith("first "));
if (sqlLimitSuffix != null && limitSuffixInSelectClause) {
sql += (sqlLimitSuffix.replace("%s", Integer.toString(limit))) + " ";
}
int colI = 1;
boolean f = true;
if (selectParentPK) {
int i = 0;
for (Column column: rowIdSupport.getPrimaryKey(association.source, session).getColumns()) {
String name = quoting.requote(column.name);
sql += (!f ? ", " : "") + "B." + name + " AS B" + i;
olapPrefix += (!f ? ", " : "") + "S.B" + i;
++numParentPKColumns;
++i;
++colI;
f = false;
}
}
int i = 0;
for (Column column : rowIdSupport.getColumns(table, session)) {
String name = quoting.requote(column.name);
if (existingColumnsLowerCase != null && !rowIdSupport.isRowIdColumn(column) && !existingColumnsLowerCase.contains(quoting.unquote(name).toLowerCase())) {
sql += (!f ? ", " : "") + "'?' AS A" + i;
unknownColumnIndexes.add(colI);
} else {
sql += (!f ? ", " : "") + "A." + name + " AS A" + i;
}
olapPrefix += (!f ? ", " : "") + "S.A" + i;
++i;
++colI;
f = false;
}
f = true;
if (selectParentPK) {
int j = 0;
for (Column pk: rowIdSupport.getPrimaryKey(association.source, session).getColumns()) {
parentPkColumnNames.add(quoting.requote(pk.name));
++j;
f = false;
}
}
int j = 0;
for (Column pk: rowIdSupport.getPrimaryKey(table, session).getColumns()) {
pkColumnNames.add(quoting.requote(pk.name));
++j;
f = false;
}
if (useOLAPLimitation) {
sql += ", row_number() over(";
if (useOLAPLimitation) {
sql += "order by -1"; // + orderBy;
}
sql += ") as " + ROWNUMBERALIAS + "";
}
sql += " From ";
if (association != null) {
sql += qualifiedTableName(association.source, quoting) + " B join ";
}
sql += qualifiedTableName(table, quoting) + " A";
if (association != null) {
if (association.reversed) {
sql += " on " + association.getUnrestrictedJoinCondition();
} else {
sql += " on " + SqlUtil.reversRestrictionCondition(association.getUnrestrictedJoinCondition());
}
}
boolean whereExists = false;
if (parentRows != null && !parentRows.isEmpty()) {
if (association != null && parentRows.get(0).rowId.length() == 0) {
throw new SqlException("Missing primary key for table: \"" + Quoting.staticUnquote(association.source.getName()) + "\"\n"
+ "Resolution: define the primary key manually using the data model editor.", "", null);
}
if (parentRows.size() == 1) {
sql += " Where (" + parentRows.get(0).rowId + ")";
} else {
StringBuilder sb = new StringBuilder();
if (inlineViewStyle != null && association != null) {
sb.append(" join ");
List<String> columnNames = new ArrayList<String>();
for (Column pkColumn: rowIdSupport.getPrimaryKey(association.source, session).getColumns()) {
columnNames.add(pkColumn.name);
}
String[] columnNamesAsArray = columnNames.toArray(new String[columnNames.size()]);
sb.append(inlineViewStyle.head(columnNamesAsArray));
int rowNumber = 0;
for (Row parentRow: parentRows) {
if (rowNumber > 0) {
sb.append(inlineViewStyle.separator());
}
sb.append(inlineViewStyle.item(parentRow.primaryKey, columnNamesAsArray, rowNumber));
++rowNumber;
}
sb.append(inlineViewStyle.terminator("C", columnNamesAsArray));
sb.append(" on (");
boolean f2 = true;
for (String pkColumnName: columnNames) {
if (!f2) {
sb.append(" and ");
}
sb.append("B." + pkColumnName + " = " + "C." + pkColumnName);
f2 = false;
}
sb.append(")");
} else {
for (Row parentRow: parentRows) {
if (sb.length() == 0) {
sb.append(" Where ((");
} else {
sb.append(" or (");
}
sb.append(parentRow.rowId).append(")");
}
sb.append(")");
}
sql += sb.toString();
}
whereExists = true;
}
if (andCond.trim().length() > 0) {
sql += (whereExists ? " and" : " Where") + " (" + ConditionEditor.toMultiLine(andCond) + ")";
}
olapPrefix += " From (";
if (useOLAPLimitation) {
sql = olapPrefix + sql + olapSuffix;
}
if (sqlLimitSuffix != null && !limitSuffixInSelectClause) {
sql += " " + (sqlLimitSuffix.replace("%s", Integer.toString(limit)));
}
}
if (sql.length() > 0 || inputResultSet != null) {
final Map<Integer, Integer> pkPosToColumnPos = new HashMap<Integer, Integer>();
if (!(table instanceof SqlStatementTable) && statementForReloading == null) {
List<Column> pks = rowIdSupport.getPrimaryKey(table, session).getColumns();
List<Column> columns = rowIdSupport.getColumns(table, session);
for (int i = 0; i < columns.size(); ++i) {
Column column = columns.get(i);
for (int j = 0; j < pks.size(); ++j) {
if (column.name.equals(pks.get(j).name)) {
pkPosToColumnPos.put(j, i);
break;
}
}
}
}
final int finalNumParentPKColumns = numParentPKColumns;
AbstractResultSetReader reader = new AbstractResultSetReader() {
Map<Integer, Integer> typeCache = new HashMap<Integer, Integer>();
int rowNr = 0;
@Override
public void init(ResultSet resultSet) throws SQLException {
ResultSetMetaData metaData = getMetaData(resultSet);
int columnCount = metaData.getColumnCount();
if (table instanceof SqlStatementTable) {
for (int ci = 1; ci <= columnCount; ++ci) {
table.getColumns().add(new Column(metaData.getColumnLabel(ci), metaData.getColumnTypeName(ci), -1, -1));
}
}
int[] columnTypes = new int[columnCount];
for (int ci = 1 + finalNumParentPKColumns; ci <= columnCount; ++ci) {
if (metaData instanceof MemorizedResultSetMetaData) {
columnTypes[ci - 1 - finalNumParentPKColumns] = ((MemorizedResultSetMetaData) metaData).types[ci - 1];
} else {
columnTypes[ci - 1 - finalNumParentPKColumns] = metaData.getColumnType(ci);
}
}
browserContentCellEditor = new BrowserContentCellEditor(columnTypes);
}
@Override
public void readCurrentRow(ResultSet resultSet) throws SQLException {
int i = 1, vi = 0;
String parentRowId = "";
if (selectParentPK) {
Object v[] = new Object[rowIdSupport.getPrimaryKey(association.source, session).getColumns().size()];
for (Column column: rowIdSupport.getPrimaryKey(association.source, session).getColumns()) {
parentRowId = readRowFromResultSet(parentPkColumnNames, resultSet, i, vi, parentRowId, v, column, null, null, unknownColumnIndexes);
++i;
++vi;
}
} else {
if (parentRows != null && parentRows.size() == 1) {
parentRowId = parentRows.get(0).rowId;
}
}
Map<String, String> pkColumn = new HashMap<String, String>();
Map<String, String> pkColumnValue = new HashMap<String, String>();
Object v[] = new Object[rowIdSupport.getColumns(table, session).size()];
vi = 0;
for (Column column: rowIdSupport.getColumns(table, session)) {
readRowFromResultSet(pkColumnNames, resultSet, i, vi, "", v, column, pkColumn, pkColumnValue, unknownColumnIndexes);
++i;
++vi;
}
String rowId = "";
String[] primaryKey = null;
PrimaryKey primaryKeys = rowIdSupport.getPrimaryKey(table, session);
if (primaryKeys != null && resultSetType == null) {
int pkPos = 0;
primaryKey = new String[primaryKeys.getColumns().size()];
for (Column column : primaryKeys.getColumns()) {
if (rowId.length() > 0) {
rowId += " and ";
}
rowId += pkColumn.get(column.name);
Integer colPos = pkPosToColumnPos.get(pkPos);
if (colPos != null) {
primaryKey[pkPos] = pkColumnValue.get(column.name);
}
++pkPos;
}
} else {
rowId = Integer.toString(++rowNr);
}
List<Row> cRows = rows.get(parentRowId);
if (cRows == null) {
cRows = new ArrayList<Row>();
rows.put(parentRowId, cRows);
}
cRows.add(new Row(rowId, primaryKey, v));
}
private String readRowFromResultSet(final Set<String> pkColumnNames, ResultSet resultSet, int i, int vi, String rowId, Object[] v, Column column, Map<String, String> pkColumn, Map<String, String> pkColumnValue, Set<Integer> unknownColumnIndexes)
throws SQLException {
Object value = "";
if (unknownColumnIndexes.contains(i)) {
value = new UnknownValue() {
@Override
public String toString() {
return "?";
}
};
} else {
int type = SqlUtil.getColumnType(resultSet, getMetaData(resultSet), i, typeCache);
Object lob = null;
if (type == 0) {
lob = resultSet.getObject(i);
}
if (type == Types.BLOB || type == Types.CLOB || type == Types.NCLOB || type == Types.SQLXML
|| (type == 0 &&
(lob instanceof Blob || lob instanceof Clob || lob instanceof SQLXML)
)) {
Object object = resultSet.getObject(i);
if (object == null || resultSet.wasNull()) {
value = null;
} else {
Object lobValue = toLobRender(object);
if (lobValue != null) {
value = lobValue;
}
}
} else {
CellContentConverter cellContentConverter = getCellContentConverter(resultSet, session, session.dbms);
Object o;
try {
o = cellContentConverter.getObject(resultSet, i);
if (o instanceof byte[]) {
final long length = ((byte[]) o).length;
o = new LobValue() {
@Override
public String toString() {
return "<Blob> " + length + " bytes";
}
};
}
} catch (Throwable e) {
o = "ERROR: " + e.getClass().getName() + ": " + e.getMessage();
}
boolean isPK = false;
if (pkColumnNames.isEmpty()) {
isPK = type != Types.BLOB && type != Types.CLOB && type != Types.DATALINK && type != Types.JAVA_OBJECT && type != Types.NCLOB
&& type != Types.NULL && type != Types.OTHER && type != Types.REF && type != Types.SQLXML && type != Types.STRUCT;
}
if (pkColumnNames.contains(quoting.requote(column.name)) || isPK) {
String cVal = cellContentConverter.toSql(o);
String pkValue = "B." + quoting.requote(column.name) + ("null".equalsIgnoreCase(cVal)? " is null" : ("=" + cVal));
if (pkColumn != null) {
pkColumn.put(column.name, pkValue);
}
if (pkColumnValue != null) {
pkColumnValue.put(column.name, cVal);
}
rowId += (rowId.length() == 0 ? "" : " and ") + pkValue;
}
if (o == null || resultSet.wasNull()) {
value = null;
}
if (o != null) {
value = o;
}
}
}
v[vi] = value;
return rowId;
}
};
if (inputResultSet != null) {
reader.init(inputResultSet);
while (inputResultSet.next()) {
reader.readCurrentRow(inputResultSet);
}
inputResultSet.close();
}
else {
session.executeQuery(sql, reader, null, loadJob, limit);
}
}
}
/**
* True if row-limit is exceeded.
*/
private boolean isLimitExceeded = false;
private boolean isClosureLimitExceeded = false;
/**
* Show single row in special view?
*/
protected boolean noSingleRowDetailsView = false;
protected String singleRowDetailsViewTitel = "Single Row Details";
/**
* Parent having row-limit exceeded.
*/
private RowBrowser parentWithExceededLimit() {
RowBrowser parent = getParentBrowser();
while (parent != null) {
if (parent.browserContentPane.isLimitExceeded) {
return parent;
}
parent = parent.browserContentPane.getParentBrowser();
}
return null;
}
public static class TableModelItem {
public int blockNr;
public Object value;
@Override
public String toString() {
if (value instanceof Double) {
return SqlUtil.toString((Double) value);
}
if (value instanceof BigDecimal) {
return SqlUtil.toString((BigDecimal) value);
}
return String.valueOf(value);
}
}
private int lastLimit;
private boolean lastLimitExceeded;
private boolean lastClosureLimitExceeded;
/**
* Updates the model of the {@link #rowsTable}.
*
* @param limit
* row limit
* @param limitExceeded
*/
private void updateTableModel() {
updateTableModel(lastLimit, lastLimitExceeded, lastClosureLimitExceeded);
}
/**
* Updates the model of the {@link #rowsTable}.
*
* @param limit
* row limit
* @param limitExceeded
*/
private void updateTableModel(int limit, boolean limitExceeded, boolean closureLimitExceeded) {
lastLimit = limit;
lastLimitExceeded = limitExceeded;
lastClosureLimitExceeded = closureLimitExceeded;
pkColumns.clear();
List<Column> columns = rowIdSupport.getColumns(table, session);
String[] columnNames = new String[columns.size()];
final Set<String> pkColumnNames = new HashSet<String>();
if (rowIdSupport.getPrimaryKey(table, session) != null) {
for (Column pk : rowIdSupport.getPrimaryKey(table, session).getColumns()) {
pkColumnNames.add(pk.name);
}
}
for (int i = 0; i < columnNames.length; ++i) {
columnNames[i] = columns.get(i).name;
if ("".equals(columnNames[i])) {
columnNames[i] = " ";
}
if (pkColumnNames.contains(columnNames[i])) {
pkColumns.add(i);
}
if (columnNames[i] == null) {
if (alternativeColumnLabels != null && i < alternativeColumnLabels.length) {
columnNames[i] = alternativeColumnLabels[i];
}
}
}
fkColumns.clear();
final Set<String> fkColumnNames = new HashSet<String>();
for (Association a: table.associations) {
if (a.isInsertDestinationBeforeSource()) {
Map<Column, Column> m = a.createSourceToDestinationKeyMapping();
for (Column fkColumn: m.keySet()) {
fkColumnNames.add(fkColumn.name);
}
}
}
if (rowIdSupport.getPrimaryKey(table, session) != null) {
for (Column pk : rowIdSupport.getPrimaryKey(table, session).getColumns()) {
pkColumnNames.add(pk.name);
}
}
for (int i = 0; i < columnNames.length; ++i) {
if (fkColumnNames.contains(columnNames[i])) {
fkColumns.add(i);
}
}
DefaultTableModel dtm;
singleRowDetailsView = null;
singleRowViewScrollPaneContainer.setVisible(false);
rowsTableContainerPanel.setVisible(true);
boolean noFilter = true;
int rn = 0;
if (rows.size() != 1 || isEditMode || noSingleRowDetailsView) {
noFilter = false;
Map<String, Integer> columnNameMap = new HashMap<String, Integer>();
for (int i = 0; i < columns.size(); ++i) {
columnNameMap.put(columnNames[i], i);
}
String[] uqColumnNames = new String[columnNames.length];
for (int i = 0; i < uqColumnNames.length; ++i) {
if (columnNames[i] != null) {
uqColumnNames[i] = Quoting.staticUnquote(columnNames[i]);
}
}
dtm = new DefaultTableModel(uqColumnNames, 0) {
@Override
public boolean isCellEditable(int row, int column) {
Row r = null;
if (row < rows.size()) {
r = rows.get(row);
}
Table type = getResultSetTypeForColumn(column);
if (isEditMode && r != null && (r.rowId != null && !r.rowId.isEmpty()) && browserContentCellEditor.isEditable(type, row, column, r.values[column]) && isPKComplete(type, r)) {
return !rowIdSupport.getPrimaryKey(type, session).getColumns().isEmpty();
}
return false;
}
@Override
public void setValueAt(Object aValue, int row, int column) {
String text = aValue.toString();
Row theRow = null;
if (row < rows.size()) {
theRow = rows.get(row);
Object content = browserContentCellEditor.textToContent(row, column, text, theRow.values[column]);
if (content != BrowserContentCellEditor.INVALID) {
if (!browserContentCellEditor.cellContentToText(row, column, theRow.values[column]).equals(text)) {
Table type = getResultSetTypeForColumn(column);
if (resultSetType != null) {
theRow = createRowWithNewID(theRow, type);
}
Object oldContent = theRow.values[column];
theRow.values[column] = content;
final String updateStatement = SQLDMLBuilder.buildUpdate(type, theRow, false, column, session);
theRow.values[column] = oldContent;
updateMode("updating", null);
getRunnableQueue().add(new RunnableWithPriority() {
private Exception exception;
@Override
public void run() {
final Object context = new Object();
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
CancellationHandler.cancel(context);
}
};
cancelLoadButton.addActionListener(listener);
try {
session.execute(updateStatement, context);
} catch (Exception e) {
exception = e;
} finally {
CancellationHandler.reset(context);
cancelLoadButton.removeActionListener(listener);
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (exception != null && !(exception instanceof CancellationException)) {
UIUtil.showException(BrowserContentPane.this, "Error", exception);
updateMode("table", null);
} else {
reloadRows();
}
}
});
}
@Override
public int getPriority() {
return 50;
}
});
}
}
}
}
};
boolean stripHour[] = new boolean[columns.size()];
final String HOUR = " 00:00:00.0";
for (int i = 0; i < columns.size(); ++i) {
stripHour[i] = true;
for (Row row : rows) {
Object value = row.values[i];
if (value == null) {
continue;
}
if (!(value instanceof java.sql.Date) && !(value instanceof java.sql.Timestamp)) {
stripHour[i] = false;
break;
}
String asString = value.toString();
if (asString.endsWith(HOUR)) {
continue;
}
stripHour[i] = false;
break;
}
}
for (Row row : rows) {
Object[] rowData = new Object[columns.size()];
for (int i = 0; i < columns.size(); ++i) {
rowData[i] = row.values[i];
if (rowData[i] instanceof PObjectWrapper) {
rowData[i] = ((PObjectWrapper) rowData[i]).getValue();
}
if (rowData[i] == null) {
rowData[i] = UIUtil.NULL;
} else if (rowData[i] instanceof UnknownValue) {
rowData[i] = UNKNOWN;
}
if (stripHour[i] && (rowData[i] instanceof java.sql.Date || rowData[i] instanceof java.sql.Timestamp)) {
String asString = rowData[i].toString();
rowData[i] = asString.substring(0, asString.length() - HOUR.length());
}
}
if (tableContentViewFilter != null) {
tableContentViewFilter.filter(rowData, columnNameMap);
}
for (int i = 0; i < columns.size(); ++i) {
TableModelItem item = new TableModelItem();
item.blockNr = row.getParentModelIndex();
item.value = rowData[i];
rowData[i] = item;
}
dtm.addRow(rowData);
if (++rn >= limit) {
break;
}
}
//set the editor as default on every column
JTextField textField = new JTextField();
textField.setBorder(new LineBorder(Color.black));
DefaultCellEditor anEditor = new DefaultCellEditor(textField) {
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
if (table != rowsTable) {
column = table.convertColumnIndexToModel(column);
if (column == 0) {
return null;
}
int h = row;
row = column - 1;
column = h;
}
if (row < rows.size()) {
Row r = rows.get(rowsTable.getRowSorter().convertRowIndexToModel(row));
int convertedColumnIndex = rowsTable.convertColumnIndexToModel(column);
if (r != null) {
value = browserContentCellEditor.cellContentToText(row, convertedColumnIndex, r.values[convertedColumnIndex]);
}
}
return super.getTableCellEditorComponent(table, value, isSelected, row, column);
}
};
anEditor.setClickCountToStart(1);
for (int i = 0; i < rowsTable.getColumnCount(); i++) {
rowsTable.setDefaultEditor(rowsTable.getColumnClass(i), anEditor);
}
List<? extends SortKey> sortKeys = new ArrayList(rowsTable.getRowSorter().getSortKeys());
List<Object> filterContent = new ArrayList<Object>();
if (filterHeader != null) {
try {
for (int i = 0; i < rowsTable.getColumnCount(); ++i) {
filterContent.add(filterHeader.getFilterEditor(i).getContent());
}
} catch (Exception e) {
// ignore
}
}
rowsTable.setModel(dtm);
rowsTable.getSelectionModel().clearSelection();
rowsTable.setRowHeight(initialRowHeight);
noRowsFoundPanel.setVisible(dtm.getRowCount() == 0 && getAndConditionText().length() > 0);
final int defaultSortColumn = getDefaultSortColumn();
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(dtm) {
@Override
protected boolean useToString(int column) {
return false;
}
@Override
public void toggleSortOrder(int column) {
if (association != null && association.isInsertDestinationBeforeSource()) {
return;
}
List<? extends SortKey> sortKeys = getSortKeys();
if (sortKeys.size() > 0) {
if (sortKeys.get(0).getSortOrder() == SortOrder.DESCENDING) {
List<SortKey> sk = new ArrayList<SortKey>();
if (defaultSortColumn >= 0) {
sk.add(new SortKey(defaultSortColumn, SortOrder.ASCENDING));
}
setSortKeys(sk);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
sortChildren();
}
});
return;
}
}
super.toggleSortOrder(column);
}
@Override
public Comparator<?> getComparator(int n) {
List<? extends SortKey> sortKeys = super.getSortKeys();
final boolean desc = sortKeys.size() > 0 && sortKeys.get(0).getSortOrder() == SortOrder.DESCENDING;
return new Comparator<Object>() {
@SuppressWarnings("unchecked")
@Override
public int compare(Object o1, Object o2) {
RowSorter pSorter = null;
RowBrowser pb = getParentBrowser();
if (pb != null) {
if (pb.browserContentPane != null) {
if (pb.browserContentPane.rowsTable != null) {
pSorter = pb.browserContentPane.rowsTable.getRowSorter();
}
}
}
if (o1 instanceof TableModelItem && o2 instanceof TableModelItem) {
int b1 = ((TableModelItem) o1).blockNr;
int b2 = ((TableModelItem) o2).blockNr;
if (pSorter != null) {
int b;
b = b1 < pSorter.getModelRowCount()? pSorter.convertRowIndexToView(b1) : -1;
if (b < 0) {
b = b1 + Integer.MAX_VALUE / 2;
}
b1 = b;
b = b2 < pSorter.getModelRowCount()? pSorter.convertRowIndexToView(b2) : -1;
if (b < 0) {
b = b2 + Integer.MAX_VALUE / 2;
}
b2 = b;
}
if (b1 != b2) {
return (b1 - b2) * (desc? -1 : 1);
}
}
if (o1 instanceof TableModelItem) {
o1 = ((TableModelItem) o1).value;
}
if (o2 instanceof TableModelItem) {
o2 = ((TableModelItem) o2).value;
}
if (o1 == null && o2 == null) {
return 0;
}
if (o1 == null) {
return -1;
}
if (o2 == null) {
return 1;
}
if (o1.getClass().equals(o2.getClass())) {
if (o1 instanceof Comparable<?>) {
return ((Comparable<Object>) o1).compareTo(o2);
}
return 0;
}
return o1.getClass().getName().compareTo(o2.getClass().getName());
}
};
}
};
sorter.addRowSorterListener(new RowSorterListener() {
@Override
public void sorterChanged(RowSorterEvent e) {
if (e.getType() == RowSorterEvent.Type.SORTED) {
List<RowBrowser> chBrs = getChildBrowsers();
if (chBrs != null) {
for (RowBrowser chBr: chBrs) {
if (chBr.browserContentPane != null) {
if (chBr.browserContentPane.rowsTable != null) {
final RowSorter chSorter = chBr.browserContentPane.rowsTable.getRowSorter();
if (chSorter instanceof TableRowSorter) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
((TableRowSorter) chSorter).sort();
}
});
}
}
}
}
}
}
}
});
rowsTable.setRowSorter(sorter);
try {
if (!sortKeys.isEmpty()) {
rowsTable.getRowSorter().setSortKeys(sortKeys);
} else {
List<SortKey> sk = new ArrayList<SortKey>();
if (defaultSortColumn >= 0) {
sk.add(new SortKey(defaultSortColumn, SortOrder.ASCENDING));
}
rowsTable.getRowSorter().setSortKeys(sk);
}
if (filterHeader != null) {
for (int i = 0; i < rowsTable.getColumnCount(); ++i) {
filterHeader.getFilterEditor(i).setContent(filterContent.get(i));
}
}
} catch (Exception e) {
// ignore
}
} else {
final boolean deselect = !currentSelectedRowCondition.equals("")
&& currentSelectedRowCondition.equals(getAndConditionText())
&& rows.size() == 1;
singleRowDetailsView = new DetailsView(Collections.singletonList(rows.get(0)), 1, dataModel, BrowserContentPane.this.table, 0, null, false, false, rowIdSupport, deselect, session) {
@Override
protected void onRowChanged(int row) {
}
@Override
protected void onClose() {
}
@Override
protected void onSelectRow(Row row) {
}
};
singleRowDetailsView.setSortColumns(sortColumnsCheckBox.isSelected());
dtm = new DefaultTableModel(new String[] { singleRowDetailsViewTitel }, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
for (Row row : rows) {
dtm.addRow(new Object[] { row });
if (++rn >= limit) {
break;
}
}
rowsTable.setModel(dtm);
JPanel detailsPanel = singleRowDetailsView.getDetailsPanel();
GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.weightx = 1;
gridBagConstraints.weighty = 0;
gridBagConstraints.insets = new Insets(2, 4, 2, 4);
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
singleRowViewContainterPanel.removeAll();
singleRowViewContainterPanel.add(detailsPanel, gridBagConstraints);
singleRowViewScrollPaneContainer.setVisible(true);
rowsTableContainerPanel.setVisible(false);
deselectButton.setVisible(deselect);
}
adjustRowTableColumnsWidth();
if (sortColumnsCheckBox.isSelected()) {
TableColumnModel cm = rowsTable.getColumnModel();
for (int a = 0; a < rowsTable.getColumnCount(); ++a) {
for (int b = a + 1; b < rowsTable.getColumnCount(); ++b) {
if (cm.getColumn(a).getHeaderValue().toString().compareToIgnoreCase(cm.getColumn(b).getHeaderValue().toString()) > 0) {
cm.moveColumn(b, a);
}
}
}
}
rowsTable.setIntercellSpacing(new Dimension(0, 0));
Set<BrowserContentPane> browserInClosure = new HashSet<BrowserContentPane>();
for (Pair<BrowserContentPane, Row> rid: rowsClosure.currentClosure) {
browserInClosure.add(rid.a);
}
updateRowsCountLabel(browserInClosure);
int nndr = noNonDistinctRows;
if (noDistinctRows + noNonDistinctRows >= limit) {
--nndr;
}
selectDistinctCheckBox.setVisible(nndr > 0);
selectDistinctCheckBox.setText("select distinct (-" + nndr + " row" + (nndr == 1? "" : "s") + ")");
if (filterHeader != null) {
if (rowsTable.getRowSorter() != null && rowsTable.getRowSorter().getViewRowCount() == 0) {
filterHeader.setTable(null);
filterHeader = null;
adjustRowTableColumnsWidth();
}
}
if (isTableFilterEnabled && !noFilter) {
if (filterHeader == null) {
filterHeader = new TableFilterHeader();
filterHeader.setAutoChoices(AutoChoices.ENABLED);
filterHeader.setTable(rowsTable);
filterHeader.setMaxVisibleRows(20);
try {
for (int i = 0; i < rowsTable.getColumnCount(); ++i) {
filterHeader.getFilterEditor(i).setChoicesComparator(new Comparator<Object>() {
@SuppressWarnings("unchecked")
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof TableModelItem) {
o1 = ((TableModelItem) o1).value;
}
if (o2 instanceof TableModelItem) {
o2 = ((TableModelItem) o2).value;
}
if (o1 == null && o2 == null) {
return 0;
}
if (o1 == null) {
return -1;
}
if (o2 == null) {
return 1;
}
if (o1.getClass().equals(o2.getClass())) {
if (o1 instanceof Comparable<?>) {
return ((Comparable<Object>) o1).compareTo(o2);
}
return 0;
}
return o1.getClass().getName().compareTo(o2.getClass().getName());
}
});
}
}
catch (Exception e) {
// ignore
}
}
} else {
if (filterHeader != null) {
filterHeader.setTable(null);
filterHeader = null;
}
}
isLimitExceeded = limitExceeded;
isClosureLimitExceeded = closureLimitExceeded;
appendClosure();
}
public void updateRowsCountLabel(Set<BrowserContentPane> browserInClosure) {
int limit = lastLimit;
boolean limitExceeded = lastLimitExceeded;
boolean closureLimitExceeded = lastClosureLimitExceeded;
int size = rows.size();
if (size > limit) {
size = limit;
}
rowsCount.setText((limitExceeded ? " more than " : " ") + size + " row" + (size != 1 ? "s" : ""));
RowBrowser theParentWithExceededLimit = parentWithExceededLimit();
boolean cle = closureLimitExceeded;
boolean cleRelevant = true;
// if (theParentWithExceededLimit != null && theParentWithExceededLimit.browserContentPane.isClosureLimitExceeded) {
// cle = true;
// }
if (rowsClosure.parentPath.contains(this) || rowsClosure.currentClosureRowIDs.isEmpty()) {
cleRelevant = false;
} else if (getParentBrowser() != null) {
BrowserContentPane parent = getParentBrowser().browserContentPane;
if (!browserInClosure.contains(parent)) {
cleRelevant = false;
}
}
boolean bold = false;
if (limitExceeded || theParentWithExceededLimit != null) {
if (cle || !cleRelevant) {
rowsCount.setForeground(Color.RED);
bold = true;
} else {
rowsCount.setForeground(new Color(140, 0, 0));
}
} else {
rowsCount.setForeground(new JLabel().getForeground());
}
if (bold) {
rowsCount.setFont(rowsCount.getFont().deriveFont(rowsCount.getFont().getStyle() | Font.BOLD));
} else {
rowsCount.setFont(rowsCount.getFont().deriveFont(rowsCount.getFont().getStyle() & ~Font.BOLD));
}
if (cle && cleRelevant) {
rowsCount.setToolTipText("row selection incomplete");
} else if (!limitExceeded && theParentWithExceededLimit != null) {
rowsCount.setToolTipText("potentially incomplete because " + theParentWithExceededLimit.internalFrame.getTitle() + " exceeded row limit");
} else {
rowsCount.setToolTipText(null);
}
}
private int getDefaultSortColumn() {
if (table == null || table instanceof SqlStatementTable || getQueryBuilderDialog() == null /* SQL Console */) {
return -1;
}
if (association != null && association.isInsertDestinationBeforeSource()) {
return table.getColumns().size() - 1;
}
if (table.primaryKey.getColumns() != null && table.primaryKey.getColumns().size() > 0) {
Column pk = table.primaryKey.getColumns().get(0);
for (int i = 0; i < table.getColumns().size(); ++i) {
if (table.getColumns().get(i).equals(pk)) {
return i;
}
}
}
return 0;
}
private TableFilterHeader filterHeader;
protected Row createRowWithNewID(Row theRow, Table type) {
CellContentConverter cellContentConverter = new CellContentConverter(null, session, session.dbms);
String rowId = "";
PrimaryKey primaryKeys = type.primaryKey;
for (Column pkColumn : primaryKeys.getColumns()) {
List<Column> cols = type.getColumns();
int colSize = cols.size();
for (int i = 0; i < colSize; ++i) {
Column column = cols.get(i);
if (column != null && pkColumn.name.equals(column.name)) {
if (rowId.length() > 0) {
rowId += " and ";
}
rowId += pkColumn.name + "=" + cellContentConverter.toSql(theRow.values[i]);
break;
}
}
}
return new Row(rowId, theRow.primaryKey, theRow.values);
}
public void adjustRowTableColumnsWidth() {
DefaultTableModel dtm = (DefaultTableModel) rowsTable.getModel();
int MAXLINES = 2000;
if (rowsTable.getColumnCount() > 0) {
MAXLINES = Math.max(10 * MAXLINES / rowsTable.getColumnCount(), 10);
}
DefaultTableCellRenderer defaultTableCellRenderer = new DefaultTableCellRenderer();
for (int i = 0; i < rowsTable.getColumnCount(); i++) {
TableColumn column = rowsTable.getColumnModel().getColumn(i);
int width = ((int) (Desktop.BROWSERTABLE_DEFAULT_WIDTH * getLayoutFactor()) - 18) / rowsTable.getColumnCount();
Component comp = defaultTableCellRenderer.getTableCellRendererComponent(rowsTable, column.getHeaderValue(), false, false, 0, i);
int pw = comp.getPreferredSize().width;
if (pw < 100) {
pw = (pw * 110) / 100 + 2;
}
width = Math.max(width, pw);
int line = 0;
for (; line < rowsTable.getRowCount(); ++line) {
comp = rowsTable.getCellRenderer(line, i).getTableCellRendererComponent(rowsTable, dtm.getValueAt(line, i), false, false, line, i);
width = Math.max(width, comp.getPreferredSize().width + 24);
if (line > MAXLINES) {
break;
}
}
Object maxValue = null;
int maxValueLength = 0;
for (; line < rowsTable.getRowCount(); ++line) {
Object value = dtm.getValueAt(line, i);
if (value != null) {
int valueLength = value.toString().length();
if (maxValue == null || maxValueLength < valueLength) {
maxValue = value;
maxValueLength = valueLength;
}
}
if (line > 4 * MAXLINES) {
break;
}
}
if (maxValue != null) {
comp = rowsTable.getCellRenderer(line, i).getTableCellRendererComponent(rowsTable, maxValue, false, false, line, i);
int maxValueWidth = comp.getPreferredSize().width + 16;
if (maxValueWidth > width) {
width = maxValueWidth;
}
}
column.setPreferredWidth(width);
}
}
protected int maxColumnWidth = 400;
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed"
// <editor-fold defaultstate="collapsed"
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
andCondition = new javax.swing.JComboBox();
openEditorLabel = new javax.swing.JLabel();
pendingNonpendingPanel = new javax.swing.JPanel();
cardPanel = new javax.swing.JPanel();
tablePanel = new javax.swing.JPanel();
jLayeredPane1 = new javax.swing.JLayeredPane();
jPanel6 = new javax.swing.JPanel();
sortColumnsCheckBox = new javax.swing.JCheckBox();
rowsCount = new javax.swing.JLabel();
selectDistinctCheckBox = new javax.swing.JCheckBox();
loadingPanel = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
cancelLoadButton = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jPanel13 = new javax.swing.JPanel();
loadingCauseLabel = new javax.swing.JLabel();
loadingLabel = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
rowsTableContainerPanel = new javax.swing.JPanel();
jLayeredPane2 = new javax.swing.JLayeredPane();
rowsTableScrollPane = new javax.swing.JScrollPane();
rowsTable = new javax.swing.JTable();
noRowsFoundPanel = new javax.swing.JPanel();
jLabel9 = new javax.swing.JLabel();
removeConditionButton = new javax.swing.JButton();
singleRowViewScrollPaneContainer = new javax.swing.JPanel();
singleRowViewScrollPane = new javax.swing.JScrollPane();
singleRowViewScrollContentPanel = new javax.swing.JPanel();
singleRowViewContainterPanel = new javax.swing.JPanel();
jPanel11 = new javax.swing.JPanel();
jLabel7 = new javax.swing.JLabel();
jPanel12 = new javax.swing.JPanel();
deselectButton = new javax.swing.JButton();
jPanel5 = new javax.swing.JPanel();
jLabel10 = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
jLabel8 = new javax.swing.JLabel();
jPanel8 = new javax.swing.JPanel();
jLabel11 = new javax.swing.JLabel();
menuPanel = new javax.swing.JPanel();
jPanel7 = new javax.swing.JPanel();
loadButton = new javax.swing.JButton();
onPanel = new javax.swing.JPanel();
on = new javax.swing.JLabel();
joinPanel = new javax.swing.JPanel();
join = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jPanel10 = new javax.swing.JPanel();
from = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
andLabel = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jPanel3 = new javax.swing.JPanel();
rrPanel = new javax.swing.JPanel();
relatedRowsPanel = new javax.swing.JPanel();
relatedRowsLabel = new javax.swing.JLabel();
sqlPanel = new javax.swing.JPanel();
sqlLabel1 = new javax.swing.JLabel();
jPanel9 = new javax.swing.JPanel();
dropA = new javax.swing.JLabel();
dropB = new javax.swing.JLabel();
openEditorButton = new javax.swing.JButton();
andCondition.setEditable(true);
andCondition.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
openEditorLabel.setText(" And ");
setLayout(new java.awt.GridBagLayout());
pendingNonpendingPanel.setLayout(new java.awt.CardLayout());
cardPanel.setLayout(new java.awt.CardLayout());
tablePanel.setLayout(new java.awt.GridBagLayout());
jLayeredPane1.setLayout(new java.awt.GridBagLayout());
jPanel6.setLayout(new java.awt.GridBagLayout());
sortColumnsCheckBox.setText("sort columns ");
sortColumnsCheckBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sortColumnsCheckBoxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 0);
jPanel6.add(sortColumnsCheckBox, gridBagConstraints);
rowsCount.setText("jLabel3");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
jPanel6.add(rowsCount, gridBagConstraints);
selectDistinctCheckBox.setSelected(true);
selectDistinctCheckBox.setText("select distinct (-100 rows)");
selectDistinctCheckBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectDistinctCheckBoxActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
jPanel6.add(selectDistinctCheckBox, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTH;
jLayeredPane1.add(jPanel6, gridBagConstraints);
loadingPanel.setOpaque(false);
loadingPanel.setLayout(new java.awt.GridBagLayout());
jPanel1.setBackground(new Color(255,255,255,150));
jPanel1.setLayout(new java.awt.GridBagLayout());
cancelLoadButton.setText("Cancel");
cancelLoadButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelLoadButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jPanel1.add(cancelLoadButton, gridBagConstraints);
jLabel2.setText(" ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.weightx = 1.0;
jPanel1.add(jLabel2, gridBagConstraints);
jPanel13.setOpaque(false);
jPanel13.setLayout(new java.awt.GridBagLayout());
loadingCauseLabel.setFont(new java.awt.Font("DejaVu Sans", 0, 14)); // NOI18N
loadingCauseLabel.setForeground(new java.awt.Color(141, 16, 16));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jPanel13.add(loadingCauseLabel, gridBagConstraints);
loadingLabel.setFont(new java.awt.Font("DejaVu Sans", 1, 14)); // NOI18N
loadingLabel.setForeground(new java.awt.Color(141, 16, 16));
loadingLabel.setText("loading... ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jPanel13.add(loadingLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(8, 8, 8, 8);
jPanel1.add(jPanel13, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 2, 4);
loadingPanel.add(jPanel1, gridBagConstraints);
jLayeredPane1.setLayer(loadingPanel, javax.swing.JLayeredPane.MODAL_LAYER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridheight = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
jLayeredPane1.add(loadingPanel, gridBagConstraints);
jPanel2.setLayout(new java.awt.GridBagLayout());
rowsTableContainerPanel.setLayout(new java.awt.GridBagLayout());
jLayeredPane2.setLayout(new java.awt.GridBagLayout());
rowsTableScrollPane.setWheelScrollingEnabled(false);
rowsTable.setAutoCreateRowSorter(true);
rowsTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
rowsTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
rowsTableScrollPane.setViewportView(rowsTable);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jLayeredPane2.add(rowsTableScrollPane, gridBagConstraints);
noRowsFoundPanel.setOpaque(false);
noRowsFoundPanel.setLayout(new java.awt.GridBagLayout());
jLabel9.setText("No rows found.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTH;
gridBagConstraints.weighty = 1.0;
noRowsFoundPanel.add(jLabel9, gridBagConstraints);
removeConditionButton.setText("Remove condition");
removeConditionButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeConditionButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.weighty = 1.0;
noRowsFoundPanel.add(removeConditionButton, gridBagConstraints);
jLayeredPane2.setLayer(noRowsFoundPanel, javax.swing.JLayeredPane.PALETTE_LAYER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jLayeredPane2.add(noRowsFoundPanel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
rowsTableContainerPanel.add(jLayeredPane2, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jPanel2.add(rowsTableContainerPanel, gridBagConstraints);
singleRowViewScrollPaneContainer.setLayout(new java.awt.GridBagLayout());
singleRowViewScrollPane.setWheelScrollingEnabled(false);
singleRowViewScrollContentPanel.setLayout(new java.awt.GridBagLayout());
singleRowViewContainterPanel.setBackground(java.awt.Color.white);
singleRowViewContainterPanel.setBorder(new javax.swing.border.LineBorder(java.awt.Color.gray, 1, true));
singleRowViewContainterPanel.setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.weightx = 1.0;
singleRowViewScrollContentPanel.add(singleRowViewContainterPanel, gridBagConstraints);
jPanel11.setBackground(new java.awt.Color(228, 228, 232));
jPanel11.setLayout(new java.awt.GridBagLayout());
jLabel7.setBackground(new java.awt.Color(200, 200, 200));
jLabel7.setForeground(new java.awt.Color(1, 0, 0));
jLabel7.setText(" Single Row Details ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
jPanel11.add(jLabel7, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
singleRowViewScrollContentPanel.add(jPanel11, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.weighty = 1.0;
singleRowViewScrollContentPanel.add(jPanel12, gridBagConstraints);
deselectButton.setText("Deselect Row");
deselectButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deselectButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
singleRowViewScrollContentPanel.add(deselectButton, gridBagConstraints);
singleRowViewScrollPane.setViewportView(singleRowViewScrollContentPanel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
singleRowViewScrollPaneContainer.add(singleRowViewScrollPane, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jPanel2.add(singleRowViewScrollPaneContainer, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jLayeredPane1.add(jPanel2, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
tablePanel.add(jLayeredPane1, gridBagConstraints);
cardPanel.add(tablePanel, "table");
jPanel5.setLayout(new java.awt.GridBagLayout());
jLabel10.setFont(new java.awt.Font("DejaVu Sans", 1, 14)); // NOI18N
jLabel10.setForeground(new java.awt.Color(141, 16, 16));
jLabel10.setText("Error");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(8, 8, 8, 0);
jPanel5.add(jLabel10, gridBagConstraints);
cardPanel.add(jPanel5, "error");
jPanel4.setLayout(new java.awt.GridBagLayout());
jLabel8.setFont(new java.awt.Font("DejaVu Sans", 1, 14)); // NOI18N
jLabel8.setForeground(new java.awt.Color(141, 16, 16));
jLabel8.setText("Cancelled");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(8, 8, 8, 0);
jPanel4.add(jLabel8, gridBagConstraints);
cardPanel.add(jPanel4, "cancelled");
pendingNonpendingPanel.add(cardPanel, "nonpending");
jPanel8.setLayout(new java.awt.GridBagLayout());
jLabel11.setFont(new java.awt.Font("DejaVu Sans", 1, 14)); // NOI18N
jLabel11.setForeground(new java.awt.Color(141, 16, 16));
jLabel11.setText("pending...");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(8, 8, 8, 0);
jPanel8.add(jLabel11, gridBagConstraints);
pendingNonpendingPanel.add(jPanel8, "pending");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(pendingNonpendingPanel, gridBagConstraints);
menuPanel.setLayout(new java.awt.GridBagLayout());
jPanel7.setLayout(new java.awt.GridBagLayout());
loadButton.setText(" Reload ");
loadButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
loadButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
jPanel7.add(loadButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 8;
gridBagConstraints.gridwidth = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
menuPanel.add(jPanel7, gridBagConstraints);
onPanel.setMinimumSize(new java.awt.Dimension(66, 17));
onPanel.setLayout(new java.awt.BorderLayout());
on.setFont(new java.awt.Font("DejaVu Sans", 0, 13)); // NOI18N
on.setText("jLabel3");
onPanel.add(on, java.awt.BorderLayout.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 6;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHWEST;
gridBagConstraints.weightx = 1.0;
menuPanel.add(onPanel, gridBagConstraints);
joinPanel.setMinimumSize(new java.awt.Dimension(66, 17));
joinPanel.setLayout(new java.awt.GridBagLayout());
join.setFont(new java.awt.Font("DejaVu Sans", 0, 13)); // NOI18N
join.setText("jLabel3");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
joinPanel.add(join, gridBagConstraints);
jLabel6.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
jLabel6.setText(" as B ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
joinPanel.add(jLabel6, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHWEST;
gridBagConstraints.weightx = 1.0;
menuPanel.add(joinPanel, gridBagConstraints);
jPanel10.setMinimumSize(new java.awt.Dimension(66, 17));
jPanel10.setLayout(new java.awt.GridBagLayout());
from.setFont(new java.awt.Font("DejaVu Sans", 0, 13)); // NOI18N
from.setText("jLabel3");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
jPanel10.add(from, gridBagConstraints);
jLabel5.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel5.setText(" as A");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
jPanel10.add(jLabel5, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
menuPanel.add(jPanel10, gridBagConstraints);
jLabel1.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
jLabel1.setText(" Join ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 5;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
menuPanel.add(jLabel1, gridBagConstraints);
jLabel4.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
jLabel4.setText(" On ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 6;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
menuPanel.add(jLabel4, gridBagConstraints);
andLabel.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
andLabel.setText(" Where ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 8;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
menuPanel.add(andLabel, gridBagConstraints);
jLabel3.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
jLabel3.setText(" From ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
menuPanel.add(jLabel3, gridBagConstraints);
jPanel3.setLayout(new javax.swing.BoxLayout(jPanel3, javax.swing.BoxLayout.LINE_AXIS));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 9;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
menuPanel.add(jPanel3, gridBagConstraints);
rrPanel.setLayout(new java.awt.GridBagLayout());
relatedRowsPanel.setBackground(new java.awt.Color(224, 240, 255));
relatedRowsPanel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
relatedRowsPanel.setLayout(new java.awt.GridBagLayout());
relatedRowsLabel.setBackground(new java.awt.Color(224, 240, 255));
relatedRowsLabel.setText(" Related Rows ");
relatedRowsLabel.setOpaque(true);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
relatedRowsPanel.add(relatedRowsLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 7;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(2, 0, 4, 0);
rrPanel.add(relatedRowsPanel, gridBagConstraints);
sqlPanel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
sqlPanel.setLayout(new javax.swing.BoxLayout(sqlPanel, javax.swing.BoxLayout.LINE_AXIS));
sqlLabel1.setText(" Menu ");
sqlPanel.add(sqlLabel1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 8;
gridBagConstraints.gridy = 5;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
rrPanel.add(sqlPanel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 7;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.gridheight = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2);
menuPanel.add(rrPanel, gridBagConstraints);
jPanel9.setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 5;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 8, 0, 0);
menuPanel.add(jPanel9, gridBagConstraints);
dropA.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
dropA.setText("drop");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 4;
menuPanel.add(dropA, gridBagConstraints);
dropB.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
dropB.setText("drop");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 5;
menuPanel.add(dropB, gridBagConstraints);
openEditorButton.setText("jButton1");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 8;
menuPanel.add(openEditorButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
add(menuPanel, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
private void cancelLoadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelLoadButtonActionPerformed
cancelLoadJob(false);
updateMode("cancelled", null);
}//GEN-LAST:event_cancelLoadButtonActionPerformed
private void selectDistinctCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectDistinctCheckBoxActionPerformed
reloadRows();
}//GEN-LAST:event_selectDistinctCheckBoxActionPerformed
private void sortColumnsCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sortColumnsCheckBoxActionPerformed
updateTableModel();
}//GEN-LAST:event_sortColumnsCheckBoxActionPerformed
private void deselectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deselectButtonActionPerformed
andCondition.setSelectedItem("");
}//GEN-LAST:event_deselectButtonActionPerformed
private void removeConditionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeConditionButtonActionPerformed
andCondition.setSelectedItem("");
}//GEN-LAST:event_removeConditionButtonActionPerformed
private void loadButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_loadButtonActionPerformed
if (System.currentTimeMillis() - lastReloadTS > 200) {
reloadRows();
}
}// GEN-LAST:event_loadButtonActionPerformed
private void limitBoxItemStateChanged(java.awt.event.ItemEvent evt) {// GEN-FIRST:event_limitBoxItemStateChanged
if (evt.getStateChange() == ItemEvent.SELECTED) {
reloadRows();
}
}// GEN-LAST:event_limitBoxItemStateChanged
void openQueryBuilder(boolean openSQLConsole) {
openQueryBuilder(openSQLConsole, null);
}
void openQueryBuilder(boolean openSQLConsole, String alternativeWhere) {
QueryBuilderDialog.Relationship root = createQBRelations(true);
if (root != null) {
if (alternativeWhere != null) {
root.whereClause = alternativeWhere;
}
root.selectColumns = true;
getQueryBuilderDialog().buildQuery(table, root, dataModel, session, getMetaDataSource(), openSQLConsole);
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JComboBox andCondition;
javax.swing.JLabel andLabel;
private javax.swing.JButton cancelLoadButton;
private javax.swing.JPanel cardPanel;
private javax.swing.JButton deselectButton;
private javax.swing.JLabel dropA;
private javax.swing.JLabel dropB;
private javax.swing.JLabel from;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JLayeredPane jLayeredPane1;
private javax.swing.JLayeredPane jLayeredPane2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel10;
private javax.swing.JPanel jPanel11;
private javax.swing.JPanel jPanel12;
private javax.swing.JPanel jPanel13;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JPanel jPanel9;
private javax.swing.JLabel join;
private javax.swing.JPanel joinPanel;
public javax.swing.JButton loadButton;
private javax.swing.JLabel loadingCauseLabel;
private javax.swing.JLabel loadingLabel;
private javax.swing.JPanel loadingPanel;
javax.swing.JPanel menuPanel;
private javax.swing.JPanel noRowsFoundPanel;
private javax.swing.JLabel on;
private javax.swing.JPanel onPanel;
private javax.swing.JButton openEditorButton;
private javax.swing.JLabel openEditorLabel;
private javax.swing.JPanel pendingNonpendingPanel;
private javax.swing.JLabel relatedRowsLabel;
javax.swing.JPanel relatedRowsPanel;
private javax.swing.JButton removeConditionButton;
public javax.swing.JLabel rowsCount;
public javax.swing.JTable rowsTable;
private javax.swing.JPanel rowsTableContainerPanel;
protected javax.swing.JScrollPane rowsTableScrollPane;
private javax.swing.JPanel rrPanel;
javax.swing.JCheckBox selectDistinctCheckBox;
private javax.swing.JPanel singleRowViewContainterPanel;
private javax.swing.JPanel singleRowViewScrollContentPanel;
javax.swing.JScrollPane singleRowViewScrollPane;
private javax.swing.JPanel singleRowViewScrollPaneContainer;
public javax.swing.JCheckBox sortColumnsCheckBox;
private javax.swing.JLabel sqlLabel1;
javax.swing.JPanel sqlPanel;
private javax.swing.JPanel tablePanel;
// End of variables declaration//GEN-END:variables
JPanel thumbnail;
private ConditionEditor andConditionEditor;
private ImageIcon conditionEditorIcon;
private Icon conditionEditorSelectedIcon;
{
String dir = "/net/sf/jailer/ui/resource";
// load images
try {
conditionEditorIcon = new ImageIcon(getClass().getResource(dir + "/edit.png"));
} catch (Exception e) {
e.printStackTrace();
}
try {
conditionEditorSelectedIcon = new ImageIcon(getClass().getResource(dir + "/edit_s.png"));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Cancels current load job.
* @param propagate
*/
public void cancelLoadJob(boolean propagate) {
LoadJob cLoadJob;
synchronized (this) {
cLoadJob = currentLoadJob;
}
if (cLoadJob != null) {
cLoadJob.cancel();
}
if (propagate) {
for (RowBrowser child: getChildBrowsers()) {
child.browserContentPane.cancelLoadJob(propagate);
}
}
}
private void updateMode(String mode, String cause) {
String suffix;
if (cause != null) {
suffix = cause;
} else {
suffix = "";
}
loadingCauseLabel.setVisible(false);
if ("table".equals(mode)) {
loadingPanel.setVisible(false);
rowsTable.setEnabled(true);
} else if ("loading".equals(mode)) {
mode = "table";
loadingPanel.setVisible(true);
loadingLabel.setText("loading...");
loadingCauseLabel.setText(suffix);
loadingCauseLabel.setVisible(true);
cancelLoadButton.setVisible(true);
rowsTable.setEnabled(false);
} else if ("pending".equals(mode)) {
mode = "table";
loadingPanel.setVisible(true);
loadingLabel.setText("pending...");
cancelLoadButton.setVisible(false);
rowsTable.setEnabled(false);
} else if ("updating".equals(mode)) {
mode = "table";
loadingPanel.setVisible(true);
loadingLabel.setText("updating...");
cancelLoadButton.setVisible(true);
rowsTable.setEnabled(false);
}
((CardLayout) cardPanel.getLayout()).show(cardPanel, mode);
}
/**
* Opens a drop-down box which allows the user to select columns for restriction definitions.
*/
private void openColumnDropDownBox(JLabel label, String alias, Table table) {
JPopupMenu popup = new JScrollPopupMenu();
List<String> columns = new ArrayList<String>();
for (Column c: table.getColumns()) {
columns.add(alias + "." + c.name);
}
for (final String c: columns) {
if (c.equals("")) {
popup.add(new JSeparator());
continue;
}
JMenuItem m = new JMenuItem(c);
m.addActionListener(new ActionListener () {
@Override
public void actionPerformed(ActionEvent e) {
if (andCondition.isEnabled()) {
if (andCondition.isEditable()) {
if (andCondition.getEditor() != null && (andCondition.getEditor().getEditorComponent() instanceof JTextField)) {
JTextField f = ((JTextField) andCondition.getEditor().getEditorComponent());
int pos = f.getCaretPosition();
String current = f.getText();
if (pos < 0 || pos >= current.length()) {
setAndCondition(current + c, false);
} else {
setAndCondition(current.substring(0, pos) + c + current.substring(pos), false);
f.setCaretPosition(pos + c.length());
}
}
andCondition.grabFocus();
}
}
}
});
popup.add(m);
}
UIUtil.fit(popup);
UIUtil.showPopup(label, 0, label.getHeight(), popup);
}
/**
* Creates new row. Fills in foreign key.
*
* @param parentrow row holding the primary key
* @param table the table of the new row
* @return new row of table
*/
private Row createNewRow(Row parentrow, Table table, Association association) {
try {
if (parentrow != null && association != null && !association.isInsertDestinationBeforeSource()) {
Map<Column, Column> sToDMap = association.createSourceToDestinationKeyMapping();
if (!sToDMap.isEmpty()) {
Row row = new Row("", null, new Object[association.destination.getColumns().size()]);
for (Map.Entry<Column, Column> e: sToDMap.entrySet()) {
int iS = -1;
for (int i = 0; i < table.getColumns().size(); ++i) {
if (Quoting.equalsIgnoreQuotingAndCase(e.getKey().name, table.getColumns().get(i).name)) {
iS = i;
break;
}
}
int iD = -1;
for (int i = 0; i < association.destination.getColumns().size(); ++i) {
if (Quoting.equalsIgnoreQuotingAndCase(e.getValue().name, association.destination.getColumns().get(i).name)) {
iD = i;
break;
}
}
if (iS >= 0 && iD >= 0) {
row.values[iD] = parentrow.values[iS];
} else {
return null;
}
}
return row;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected abstract RowBrowser navigateTo(Association association, int rowIndex, Row row);
protected abstract void onContentChange(List<Row> rows, boolean reloadChildren);
protected abstract void onRedraw();
protected abstract void onHide();
protected abstract void beforeReload();
protected abstract QueryBuilderDialog.Relationship createQBRelations(boolean withParents);
protected abstract List<QueryBuilderDialog.Relationship> createQBChildrenRelations(RowBrowser tabu, boolean all);
protected abstract void addRowToRowLink(Row pRow, Row exRow);
protected abstract JFrame getOwner();
protected abstract void findClosure(Row row);
protected abstract void findClosure(Row row, Set<Pair<BrowserContentPane, Row>> closure, boolean forward);
protected abstract QueryBuilderDialog getQueryBuilderDialog();
protected abstract void openSchemaMappingDialog();
protected abstract void openSchemaAnalyzer();
protected abstract DbConnectionDialog getDbConnectionDialog();
protected abstract double getLayoutFactor();
protected abstract List<RowBrowser> getChildBrowsers();
protected abstract RowBrowser getParentBrowser();
protected abstract List<RowBrowser> getTableBrowser();
protected abstract void unhide();
protected abstract void close();
protected abstract void showInNewWindow();
protected abstract void appendLayout();
protected abstract void adjustClosure(BrowserContentPane tabu, BrowserContentPane thisOne);
protected abstract void reloadDataModel() throws Exception;
protected abstract MetaDataSource getMetaDataSource();
protected abstract void deselectChildrenIfNeededWithoutReload();
protected abstract int getReloadLimit();
public interface RunnableWithPriority extends Runnable {
int getPriority();
};
protected abstract PriorityBlockingQueue<RunnableWithPriority> getRunnableQueue();
/**
* Collect layout of tables in a extraction model.
*
* @param positions to put positions into
*/
protected abstract void collectPositions(Map<String, Map<String, double[]>> positions);
private void openDetails(final int x, final int y) {
final JDialog d = new JDialog(getOwner(), (table instanceof SqlStatementTable)? "" : dataModel.getDisplayName(table), true);
final boolean deselect = !currentSelectedRowCondition.equals("")
&& currentSelectedRowCondition.equals(getAndConditionText())
&& rows.size() == 1;
d.getContentPane().add(new DetailsView(rows, rowsTable.getRowCount(), dataModel, table, 0, rowsTable.getRowSorter(), true, getQueryBuilderDialog() != null, rowIdSupport, deselect, session) {
@Override
protected void onRowChanged(int row) {
setCurrentRowSelectionAndReloadChildrenIfLimitIsExceeded(row);
}
@Override
protected void onClose() {
d.setVisible(false);
}
@Override
protected void onSelectRow(Row row) {
d.setVisible(false);
if (deselect) {
andCondition.setSelectedItem("");
} else {
selectRow(row);
}
}
});
d.pack();
d.setLocation(x, y);
d.setSize(400, d.getHeight() + 20);
UIUtil.fit(d);
d.setVisible(true);
setCurrentRowSelectionAndReloadChildrenIfLimitIsExceeded(-1);
onRedraw();
}
private void updateWhereField() {
if (association != null) {
if (parentRow == null && parentRows != null && parentRows.size() > 0) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < parentRows.size(); ++i) {
if (i > 0) {
sb.append(" or\n");
}
sb.append(parentRows.get(i).rowId);
if (i > 50) {
sb.append("\n...");
break;
}
}
String currentCond = getAndConditionText().trim();
String toolTip;
if (currentCond.length() > 0) {
toolTip = currentCond + "\nand (\n" + sb + ")";
} else {
toolTip = sb.toString();
}
andLabel.setToolTipText(UIUtil.toHTML(toolTip, 0));
} else {
andLabel.setToolTipText(null);
}
} else {
andLabel.setToolTipText(null);
}
}
public void convertToRoot() {
association = null;
parentRow = null;
parentRows = null;
rowsClosure.currentClosureRowIDs.clear();
adjustGui();
reloadRows();
}
public void openDetailsView(int rowIndex, int x, int y) {
final JDialog d = new JDialog(getOwner(), (table instanceof SqlStatementTable)? "" : dataModel.getDisplayName(table), true);
final boolean deselect = !currentSelectedRowCondition.equals("")
&& currentSelectedRowCondition.equals(getAndConditionText())
&& rows.size() == 1;
d.getContentPane().add(new DetailsView(rows, rowsTable.getRowCount(), dataModel, table, rowIndex, rowsTable.getRowSorter(), true, getQueryBuilderDialog() != null, rowIdSupport, deselect, session) {
@Override
protected void onRowChanged(int row) {
setCurrentRowSelectionAndReloadChildrenIfLimitIsExceeded(row);
}
@Override
protected void onClose() {
d.setVisible(false);
}
@Override
protected void onSelectRow(Row row) {
d.setVisible(false);
if (deselect) {
andCondition.setSelectedItem("");
} else {
selectRow(row);
}
}
});
d.pack();
d.setLocation(x, y);
d.setSize(400, d.getHeight() + 20);
int h = d.getHeight();
UIUtil.fit(d);
if (d.getHeight() < h) {
y = Math.max(y - Math.min(h - d.getHeight(), Math.max(400 - d.getHeight(), 0)), 20);
d.pack();
d.setLocation(x, y);
d.setSize(400, d.getHeight() + 20);
UIUtil.fit(d);
}
d.setVisible(true);
setCurrentRowSelectionAndReloadChildrenIfLimitIsExceeded(-1);
onRedraw();
}
public void updateSingleRowDetailsView() {
if (singleRowDetailsView != null) {
if (rowsClosure != null && rowsClosure.currentClosureRowIDs != null) {
singleRowDetailsView.updateInClosureState(rows.size() == 1 && rowsClosure.currentClosureRowIDs.contains(new Pair<BrowserContentPane, String>(this, rows.get(0).nonEmptyRowId)));
}
}
}
private static TableContentViewFilter tableContentViewFilter = TableContentViewFilter.create();
private Icon dropDownIcon;
private ImageIcon relatedRowsIcon;
private ImageIcon redDotIcon;
private ImageIcon blueDotIcon;
private ImageIcon greenDotIcon;
private ImageIcon greyDotIcon;
{
String dir = "/net/sf/jailer/ui/resource";
// load images
try {
dropDownIcon = new ImageIcon(getClass().getResource(dir + "/dropdown.png"));
relatedRowsIcon = new ImageIcon(getClass().getResource(dir + "/right.png"));
redDotIcon = new ImageIcon(getClass().getResource(dir + "/reddot.gif"));
blueDotIcon = new ImageIcon(getClass().getResource(dir + "/bluedot.gif"));
greenDotIcon = new ImageIcon(getClass().getResource(dir + "/greendot.gif"));
greyDotIcon = new ImageIcon(getClass().getResource(dir + "/greydot.gif"));
} catch (Exception e) {
e.printStackTrace();
}
}
public void resetRowsTableContainer() {
cardPanel.setVisible(true);
}
public JComponent getRowsTableContainer() {
return cardPanel;
}
public JTable getRowsTable() {
return rowsTable;
}
public LoadJob newLoadJob(ResultSet resultSet, Integer limit) {
return new LoadJob(resultSet, limit == null? Integer.MAX_VALUE : limit);
}
public boolean isEditMode() {
return isEditMode;
}
public void setEditMode(boolean isEditMode) {
this.isEditMode = isEditMode;
}
private String statementForReloading;
public synchronized void setStatementForReloading(String statementForReloading) {
this.statementForReloading = statementForReloading;
}
/**
* Type of result set for in-place editing of query result.
*/
private List<Table> resultSetType;
/**
* Sets type of result set for in-place editing of query result.
*
* @param resultSetType the type
*/
public void setResultSetType(List<Table> resultSetType) {
this.resultSetType = resultSetType;
}
/**
* Gets a table from {@link #resultSetType} where a given column is defined.
*
* @param column the column
* @return suitable table for column or {@link #table}
*/
private Table getResultSetTypeForColumn(int column) {
if (resultSetType == null) {
return table;
}
if (typePerColumn.containsKey(column)) {
return typePerColumn.get(column);
}
for (Table type: resultSetType) {
if (type.getColumns().size() > column) {
Column col = type.getColumns().get(column);
if (col != null && col.name != null) {
typePerColumn.put(column, type);
return type;
}
}
}
typePerColumn.put(column, table);
return table;
}
private boolean isPKComplete(Table type, Row r) {
if (type.primaryKey == null) {
return false;
}
int[] indexes = pkColumnIndexes.get(type);
if (indexes == null) {
indexes = new int[type.primaryKey.getColumns().size()];
int ii = 0;
for (Column pk: type.primaryKey.getColumns()) {
Integer index = null;
int i = 0;
for (Column c: type.getColumns()) {
if (c.name != null && c.name.equals(pk.name)) {
index = i;
break;
}
++i;
}
if (index == null) {
return false;
}
indexes[ii++] = index;
}
pkColumnIndexes.put(type, indexes);
}
for (int i: indexes) {
if (i >= r.values.length) {
return false;
}
Object content = r.values[i];
if (content == null || content instanceof TableModelItem && (((TableModelItem) content).value == UIUtil.NULL || ((TableModelItem) content).value == null)) {
return false;
}
}
return true;
}
private Map<Integer, Table> typePerColumn = new HashMap<Integer, Table>();
private Map<Table, int[]> pkColumnIndexes = new HashMap<Table, int[]>();
private String[] alternativeColumnLabels;
public void setAlternativeColumnLabels(String[] columnLabels) {
this.alternativeColumnLabels = columnLabels;
}
private void selectRow(final Row row) {
if (row.rowId.isEmpty()) {
return;
}
for (int i = 0; i < rows.size(); ++i) {
if (row.rowId.equals(rows.get(i).rowId)) {
setCurrentRowSelection(i);
currentRowSelection = -1;
break;
}
}
deselectChildrenIfNeededWithoutReload();
String cond = SqlUtil.replaceAliases(row.rowId, "A", "A");
String currentCond = getAndConditionText().trim();
if (currentCond.length() > 0) {
cond = "(" + cond + ") and (" + currentCond + ")";
}
andCondition.setSelectedItem(cond);
currentSelectedRowCondition = cond;
}
protected void deselectIfNeededWithoutReload() {
if (rows.size() == 1) {
String rowId = rows.get(0).rowId;
if (rowId != null && !rowId.isEmpty()) {
String cond = SqlUtil.replaceAliases(rowId, "A", "A");
String currentCond = getAndConditionText().trim();
if (cond.equals(currentCond)) {
boolean isSingleRowNotInClosure = false;
if (rowsClosure != null && rowsClosure.currentClosureRowIDs != null) {
isSingleRowNotInClosure = !rowsClosure.currentClosureRowIDs.contains(new Pair<BrowserContentPane, String>(this, rowId));
}
if (isSingleRowNotInClosure) {
try {
suppessReloadOnAndConditionAction = true;
andCondition.setSelectedItem("");
} finally {
suppessReloadOnAndConditionAction = false;
}
}
}
}
}
}
private static String readCharacterStream(final Reader reader)
throws IOException {
final StringBuilder sb = new StringBuilder();
final BufferedReader br = new BufferedReader(reader);
int b;
while(-1 != (b = br.read()))
{
sb.append((char)b);
if (sb.length() > MAXLOBLENGTH) {
sb.append("...");
break;
}
}
br.close();
return sb.toString();
}
private List<Row> sortedAndFiltered(List<Row> rows) {
RowSorter<? extends TableModel> sorter = rowsTable.getRowSorter();
if (sorter != null) {
List<Row> result = new ArrayList<Row>();
for (int i = 0; i < sorter.getViewRowCount(); ++i) {
result.add(rows.get(sorter.convertRowIndexToModel(i)));
}
return result;
}
return rows;
}
private void sortChildren() {
((TableRowSorter) rowsTable.getRowSorter()).sort();
for (RowBrowser ch: getChildBrowsers()) {
if (ch.browserContentPane != null) {
ch.browserContentPane.sortChildren();
}
}
}
private static String readClob(Clob clob) throws SQLException, IOException {
return readCharacterStream(clob.getCharacterStream());
}
private static String readSQLXML(SQLXML xml) throws SQLException, IOException {
return readCharacterStream(xml.getCharacterStream());
}
public static Object toLobRender(Object object) {
Object value = null;
if (object instanceof Blob) {
try {
final long length = ((Blob) object).length();
value = new LobValue() {
@Override
public String toString() {
return "<Blob> " + length + " bytes";
}
};
} catch (Exception e) {
value = new LobValue() {
@Override
public String toString() {
return "<Blob>";
}
};
}
}
if (object instanceof Clob) {
try {
final String content = readClob((Clob) object);
value = new LobValue() {
@Override
public String toString() {
return content;
}
};
} catch (Exception e) {
value = new LobValue() {
@Override
public String toString() {
return "<Clob>";
}
};e.printStackTrace();
}
}
if (object instanceof SQLXML) {
try {
final String content = readSQLXML((SQLXML) object);
value = new LobValue() {
@Override
public String toString() {
return content;
}
};
} catch (Exception e) {
value = new LobValue() {
@Override
public String toString() {
return "<XML>";
}
};
e.printStackTrace();
}
}
return value;
}
}
| Always work with the current session | src/main/gui/net/sf/jailer/ui/databrowser/BrowserContentPane.java | Always work with the current session | |
Java | apache-2.0 | fad8bf3dd788677fc3a149eeb4ee4248d921ba4d | 0 | capergroup/bayou,capergroup/bayou,capergroup/bayou | /*
Copyright 2017 Rice University
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 edu.rice.cs.caper.bayou.core.synthesizer;
import java.util.*;
/**
* A scope of variables for the synthesizer to work with
*/
public class Scope {
/**
* The set of variables in the scope
*/
private Set<Variable> variables;
/**
* The set of phantom variables in the scope. Phantom variables are those
* that cannot be referenced during synthesis because they don't appear in
* the current scope. But they need to be added to the method's variable
* declarations because they're used in some inner scope.
*/
private Set<Variable> phantomVariables;
/**
* Initializes the scope
*
* @param variables variables present in the scope
*/
public Scope(List<Variable> variables) {
this.variables = new HashSet<>(variables);
this.phantomVariables = new HashSet<>();
}
/**
* Initializes the scope from another scope
*
* @param scope scope whose variables are used for initialization
*/
public Scope(Scope scope) {
this.variables = new HashSet<>(scope.variables);
this.phantomVariables = new HashSet<>(scope.phantomVariables);
}
/**
* Gets the set of variables in the current scope
*
* @return set of variables
*/
public Set<Variable> getVariables() {
return variables;
}
/**
* Gets the set of phantom variables in the current scope
*
* @return set of phantom variables
*/
public Set<Variable> getPhantomVariables() {
return phantomVariables;
}
/**
* Adds the given variable, whose properties must already be set, to the current scope
*
* @param var the variable to be added
*/
public void addVariable(Variable var) {
String uniqueName = makeUnique(var.getName());
var.refactor(uniqueName);
variables.add(var);
}
/**
* Adds a variable with the given type and properties to the current scope
*
* @param type variable type, from which a variable name will be derived
* @param properties variable properties
* @return a TypedExpression with a simple name (variable name) and variable type
*/
public Variable addVariable(Type type, VariableProperties properties) {
// construct a nice name for the variable
String name = createNameFromType(type);
// add variable to scope and return it
String uniqueName = makeUnique(name);
Variable var = new Variable(uniqueName, type, properties);
variables.add(var);
return var;
}
/**
* Creates a pretty name from a type
*
* @param type type from which name is created
* @return the pretty name
*/
private String createNameFromType(Type type) {
String name = type.C().getCanonicalName();
StringBuilder sb = new StringBuilder();
for (char c : name.toCharArray())
if (Character.isUpperCase(c))
sb.append(c);
String prettyName = sb.toString().toLowerCase();
return prettyName.equals("")? name.substring(0, 1) : prettyName;
}
/**
* Make a given name unique in the current scope by appending an incrementing id to it
*
* @param name name that has to be made unique
* @return the unique name
*/
private String makeUnique(String name) {
Set<String> existingNames = new HashSet<>();
for (Variable var : variables)
existingNames.add(var.getName());
for (Variable var : phantomVariables)
existingNames.add(var.getName());
int i;
for (i = 1; i < 9999; i++)
if (!existingNames.contains(name + i))
return name + i;
return null;
}
/**
* Join a list of sub-scopes into this scope.
* In the join operation, variables declared in ALL sub-scopes will be added to this scope.
* Variables declared only in some sub-scopes will be added as phantom variables to this scope.
* Variables that have their "join" flag set to false (e.g., catch clause vars) will be discarded.
* Finally, variables will be refactored if necessary.
*
* @param subScopes list of sub-scopes that have to be joined into this scope
*/
public void join(List<Scope> subScopes) {
Set<Variable> common = new HashSet<>(subScopes.get(0).getVariables());
for (Scope subScope : subScopes)
common.retainAll(subScope.getVariables());
common.removeAll(variables);
for (Variable var : common)
if (var.isJoinVar())
variables.add(var);
Set<String> varNames = new HashSet<>();
Set<Variable> toRefactor = new HashSet<>();
for (Scope subScope : subScopes) {
Set<Variable> uncommon = subScope.getVariables();
uncommon.removeAll(variables);
uncommon.removeAll(common);
for (Variable var : uncommon) {
if (!var.isJoinVar())
continue;
// Check if another scope added a variable with the same name, and refactor if so.
// Note: if the other variable also had the same type (which is fine), it would've
// been added to "common" above, and then to the current variables in scope.
if (varNames.contains(var.getName()))
toRefactor.add(var);
varNames.add(var.getName());
phantomVariables.add(var);
}
for (Variable var : subScope.getPhantomVariables()) {
if (phantomVariables.contains(var))
continue;
if (varNames.contains(var.getName()))
toRefactor.add(var);
varNames.add(var.getName());
phantomVariables.add(var);
}
}
for (Variable var : toRefactor)
var.refactor(makeUnique(var.getName()));
}
}
| src/main/java/edu/rice/cs/caper/bayou/core/synthesizer/Scope.java | /*
Copyright 2017 Rice University
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 edu.rice.cs.caper.bayou.core.synthesizer;
import java.util.*;
/**
* A scope of variables for the synthesizer to work with
*/
public class Scope {
/**
* The set of variables in the scope
*/
private Set<Variable> variables;
/**
* The set of phantom variables in the scope. Phantom variables are those
* that cannot be referenced during synthesis because they don't appear in
* the current scope. But they need to be added to the method's variable
* declarations because they're used in some inner scope.
*/
private Set<Variable> phantomVariables;
/**
* Initializes the scope
*
* @param variables variables present in the scope
*/
public Scope(List<Variable> variables) {
this.variables = new HashSet<>(variables);
this.phantomVariables = new HashSet<>();
}
/**
* Initializes the scope from another scope
*
* @param scope scope whose variables are used for initialization
*/
public Scope(Scope scope) {
this.variables = new HashSet<>(scope.variables);
this.phantomVariables = new HashSet<>(scope.phantomVariables);
}
/**
* Gets the set of variables in the current scope
*
* @return set of variables
*/
public Set<Variable> getVariables() {
return variables;
}
/**
* Gets the set of phantom variables in the current scope
*
* @return set of phantom variables
*/
public Set<Variable> getPhantomVariables() {
return phantomVariables;
}
/**
* Adds the given variable, whose properties must already be set, to the current scope
*
* @param var the variable to be added
*/
public void addVariable(Variable var) {
String uniqueName = makeUnique(var.getName());
var.refactor(uniqueName);
variables.add(var);
}
/**
* Adds a variable with the given type and properties to the current scope
*
* @param type variable type, from which a variable name will be derived
* @param properties variable properties
* @return a TypedExpression with a simple name (variable name) and variable type
*/
public Variable addVariable(Type type, VariableProperties properties) {
// construct a nice name for the variable
String name = createNameFromType(type);
// add variable to scope and return it
String uniqueName = makeUnique(name);
Variable var = new Variable(uniqueName, type, properties);
variables.add(var);
return var;
}
/**
* Creates a pretty name from a type
*
* @param type type from which name is created
* @return the pretty name
*/
private String createNameFromType(Type type) {
String name = type.C().getCanonicalName();
StringBuilder sb = new StringBuilder();
for (char c : name.toCharArray())
if (Character.isUpperCase(c))
sb.append(c);
String prettyName = sb.toString().toLowerCase();
return prettyName.equals("")? name.substring(0, 1) : prettyName;
}
/**
* Make a given name unique in the current scope by appending an incrementing id to it
*
* @param name name that has to be made unique
* @return the unique name
*/
private String makeUnique(String name) {
Set<String> existingNames = new HashSet<>();
for (Variable var : variables)
existingNames.add(var.getName());
for (Variable var : phantomVariables)
existingNames.add(var.getName());
if (!existingNames.contains(name))
return name;
int i;
for (i = 1; i < 9999; i++)
if (!existingNames.contains(name + i))
return name + i;
return null;
}
/**
* Join a list of sub-scopes into this scope.
* In the join operation, variables declared in ALL sub-scopes will be added to this scope.
* Variables declared only in some sub-scopes will be added as phantom variables to this scope.
* Variables that have their "join" flag set to false (e.g., catch clause vars) will be discarded.
* Finally, variables will be refactored if necessary.
*
* @param subScopes list of sub-scopes that have to be joined into this scope
*/
public void join(List<Scope> subScopes) {
Set<Variable> common = new HashSet<>(subScopes.get(0).getVariables());
for (Scope subScope : subScopes)
common.retainAll(subScope.getVariables());
common.removeAll(variables);
for (Variable var : common)
if (var.isJoinVar())
variables.add(var);
Set<String> varNames = new HashSet<>();
Set<Variable> toRefactor = new HashSet<>();
for (Scope subScope : subScopes) {
Set<Variable> uncommon = subScope.getVariables();
uncommon.removeAll(variables);
uncommon.removeAll(common);
for (Variable var : uncommon) {
if (!var.isJoinVar())
continue;
// Check if another scope added a variable with the same name, and refactor if so.
// Note: if the other variable also had the same type (which is fine), it would've
// been added to "common" above, and then to the current variables in scope.
if (varNames.contains(var.getName()))
toRefactor.add(var);
varNames.add(var.getName());
phantomVariables.add(var);
}
for (Variable var : subScope.getPhantomVariables()) {
if (phantomVariables.contains(var))
continue;
if (varNames.contains(var.getName()))
toRefactor.add(var);
varNames.add(var.getName());
phantomVariables.add(var);
}
}
for (Variable var : toRefactor)
var.refactor(makeUnique(var.getName()));
}
}
| Fix issue with pretty variable names
Pretty variable names could previously become Java reserved ids (if, do,
etc.) which caused an exception. This commit fixes it.
| src/main/java/edu/rice/cs/caper/bayou/core/synthesizer/Scope.java | Fix issue with pretty variable names | |
Java | apache-2.0 | 1fcabd69a8708c724b047d2920cf2bee5ee5c556 | 0 | tomgibara/streams | /*
* Copyright 2015 Tom Gibara
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.tomgibara.streams;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
/**
* <p>
* Main entry point for the streams API.
*
* <p>
* The class provides static methods for creating {@link ReadStream} and
* {@link WriteStream} instances, together with methods to create
* {@link StreamBytes}.
*
* @author Tom Gibara
*
*/
public final class Streams {
private static final int DEFAULT_INITIAL_CAPACITY = 32;
private static final int DEFAULT_MAXIMUM_CAPACITY = Integer.MAX_VALUE;
private static byte[] array(int capacity) {
if (capacity < 0) throw new IllegalArgumentException("capacity non-positive");
return new byte[capacity];
}
/**
* Creates a new {@link StreamBytes} to accumulate bytes written via a
* {@link WriteStream}.
*
* @return new bytes with default initial capacity and an unlimited maximum
* capacity
*/
public static StreamBytes bytes() {
return new StreamBytes(new byte[DEFAULT_INITIAL_CAPACITY], 0, DEFAULT_MAXIMUM_CAPACITY);
}
/**
* Creates a new {@link StreamBytes} to accumulate bytes written via a
* {@link WriteStream}.
*
* @param initialCapacity
* the initial capacity of the byte store
* @return new bytes with the specified initial capacity and an unlimited
* maximum capacity
*/
public static StreamBytes bytes(int initialCapacity) {
return new StreamBytes(array(initialCapacity), 0, DEFAULT_MAXIMUM_CAPACITY);
}
/**
* Creates a new {@link StreamBytes} to accumulate bytes written via a
* {@link WriteStream}.
*
* @param initialCapacity
* the initial capacity of the byte store
* @param maximumCapacity
* the maximum capacity to which the byte store may grow
* @return new bytes with the specified capacities
*/
public static StreamBytes bytes(int initialCapacity, int maximumCapacity) {
if (maximumCapacity < 0L) throw new IllegalArgumentException("negative maximumCapacity");
if (initialCapacity > maximumCapacity) throw new IllegalArgumentException("initialCapacity exceeds maximumCapacity");
return new StreamBytes(array(initialCapacity), 0, maximumCapacity);
}
/**
* Creates a new {@link StreamBytes} to expose bytes through a
* {@link ReadStream} or accumulate bytes through a {@link WriteStream}. If
* a reader is attached to the returned object before a writer is attached,
* all bytes in the array will be readable.
*
* @param bytes
* a byte array containing the data to be read/overwritten
* @return new bytes with an unlimited maximum capacity
*/
public static StreamBytes bytes(byte[] bytes) {
return new StreamBytes(bytes, bytes.length, DEFAULT_MAXIMUM_CAPACITY);
}
/**
* Creates a new {@link StreamBytes} to expose bytes through a
* {@link ReadStream} or accumulate bytes through a {@link WriteStream}.
*
* @param bytes
* a byte array containing the data to be read/overwritten
* @param length
* the number of readable bytes in the supplied array
* @return new bytes with an unlimited maximum capacity
*/
public static StreamBytes bytes(byte[] bytes, int length) {
if (length < 0L) throw new IllegalArgumentException("negative length");
return new StreamBytes(bytes, length, DEFAULT_MAXIMUM_CAPACITY);
}
/**
* Creates a new {@link StreamBytes} to expose bytes through a
* {@link ReadStream} or accumulate bytes through a {@link WriteStream}.
*
* @param bytes
* a byte array containing the data to be read/overwritten
* @param length
* the number of readable bytes in the supplied array
* @param maximumCapacity
* the maximum capacity to which the byte store may grow
* @return new bytes the specified maximum capacity
*/
public static StreamBytes bytes(byte[] bytes, int length, int maximumCapacity) {
if (length < 0L) throw new IllegalArgumentException("negative length");
if (maximumCapacity < 0L) throw new IllegalArgumentException("negative maximumCapacity");
if (bytes.length > maximumCapacity) throw new IllegalArgumentException("initial capacity exceeds maximumCapacity");
return new StreamBytes(bytes, length, maximumCapacity);
}
/**
* <p>
* Creates a stream that reads from the supplied channel. Bytes will be read
* starting from the current channel position.
*
* <p>
* Any {@link IOException} encountered by this class is wrapped as
* {@link StreamException} and rethrown. Any end-of-stream condition is
* signalled with an {@link EndOfStreamException} except when encountered
* during a call to {@link #fillBuffer(ByteBuffer)}, in that case, an EOS
* condition is identified by <code>buffer.hasRemaining()</code> returning
* true. Note that modifying the channel while accessing it via a stream is
* likely to produce inconsistencies.
*
* @param channel
* a byte channel
*
* @see EndOfStreamException#EOS
*/
public static ReadStream streamReadable(ReadableByteChannel channel) {
if (channel == null) throw new IllegalArgumentException("null channel");
return new ChannelReadStream(channel);
}
/**
* <p>
* Creates a stream that writes to the supplied channel. Bytes will be
* written starting from the current channel position.
*
* <p>
* Any {@link IOException} encountered by the stream is wrapped as a
* {@link StreamException} and rethrown. Any end-of-stream condition is
* signalled with an {@link EndOfStreamException} except when encountered
* during a call to {@link #fillBuffer(ByteBuffer)}, in that case, an EOS
* condition is identified by <code>buffer.hasRemaining()</code> returning
* true. Note that modifying the channel while accessing it via a stream is
* likely to produce inconsistencies.
*
* @param channel
* a byte channel
*
* @see EndOfStreamException#EOS
*/
public static WriteStream streamWritable(WritableByteChannel channel) {
if (channel == null) throw new IllegalArgumentException("null channel");
return new ChannelWriteStream(channel);
}
/**
* <p>
* Creates a new stream which obtains bytes data from an underlying
* {@link InputStream}
*
* <p>
* Any {@link IOException} encountered by this class is wrapped as
* {@link StreamException} and rethrown. Any end-of-stream condition is
* signalled with an {@link EndOfStreamException}.
*
* @param in
* an input stream from which bytes should be read
*
* @see EndOfStreamException#EOS
*/
public static ReadStream streamInput(InputStream in) {
if (in == null) throw new IllegalArgumentException("null in");
return new InputReadStream(in);
}
/**
* <p>
* Creates a new stream which writes to an underlying {@link OutputStream}.
*
* <p>
* Any {@link IOException} encountered by this class is wrapped as
* {@link StreamException} and rethrown.
*
* @param out
* an output stream to which bytes should be written
*/
public static WriteStream streamOutput(OutputStream out) {
if (out == null) throw new IllegalArgumentException("null out");
return new OutputWriteStream(out);
}
private Streams() { }
}
| src/main/java/com/tomgibara/streams/Streams.java | /*
* Copyright 2015 Tom Gibara
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.tomgibara.streams;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.security.MessageDigest;
/**
* <p>
* Main entry point for the streams API.
*
* <p>
* The class provides static methods for creating {@link ReadStream} and
* {@link WriteStream} instances, together with methods to create
* {@link StreamBytes}.
*
* @author Tom Gibara
*
*/
public final class Streams {
private static final int DEFAULT_INITIAL_CAPACITY = 32;
private static final int DEFAULT_MAXIMUM_CAPACITY = Integer.MAX_VALUE;
private static byte[] array(int capacity) {
if (capacity < 0) throw new IllegalArgumentException("capacity non-positive");
return new byte[capacity];
}
/**
* Creates a new {@link StreamBytes} to accumulate bytes written via a
* {@link WriteStream}.
*
* @return new bytes with default initial capacity and an unlimited maximum
* capacity
*/
public static StreamBytes bytes() {
return new StreamBytes(new byte[DEFAULT_INITIAL_CAPACITY], 0, DEFAULT_MAXIMUM_CAPACITY);
}
/**
* Creates a new {@link StreamBytes} to accumulate bytes written via a
* {@link WriteStream}.
*
* @param initialCapacity
* the initial capacity of the byte store
* @return new bytes with the specified initial capacity and an unlimited
* maximum capacity
*/
public static StreamBytes bytes(int initialCapacity) {
return new StreamBytes(array(initialCapacity), 0, DEFAULT_MAXIMUM_CAPACITY);
}
/**
* Creates a new {@link StreamBytes} to accumulate bytes written via a
* {@link WriteStream}.
*
* @param initialCapacity
* the initial capacity of the byte store
* @param maximumCapacity
* the maximum capacity to which the byte store may grow
* @return new bytes with the specified capacities
*/
public static StreamBytes bytes(int initialCapacity, int maximumCapacity) {
if (maximumCapacity < 0L) throw new IllegalArgumentException("negative maximumCapacity");
if (initialCapacity > maximumCapacity) throw new IllegalArgumentException("initialCapacity exceeds maximumCapacity");
return new StreamBytes(array(initialCapacity), 0, maximumCapacity);
}
/**
* Creates a new {@link StreamBytes} to expose bytes through a
* {@link ReadStream} or accumulate bytes through a {@link WriteStream}. If
* a reader is attached to the returned object before a writer is attached,
* all bytes in the array will be readable.
*
* @param bytes
* a byte array containing the data to be read/overwritten
* @return new bytes with an unlimited maximum capacity
*/
public static StreamBytes bytes(byte[] bytes) {
return new StreamBytes(bytes, bytes.length, DEFAULT_MAXIMUM_CAPACITY);
}
/**
* Creates a new {@link StreamBytes} to expose bytes through a
* {@link ReadStream} or accumulate bytes through a {@link WriteStream}.
*
* @param bytes
* a byte array containing the data to be read/overwritten
* @param length
* the number of readable bytes in the supplied array
* @return new bytes with an unlimited maximum capacity
*/
public static StreamBytes bytes(byte[] bytes, int length) {
if (length < 0L) throw new IllegalArgumentException("negative length");
return new StreamBytes(bytes, length, DEFAULT_MAXIMUM_CAPACITY);
}
/**
* Creates a new {@link StreamBytes} to expose bytes through a
* {@link ReadStream} or accumulate bytes through a {@link WriteStream}.
*
* @param bytes
* a byte array containing the data to be read/overwritten
* @param length
* the number of readable bytes in the supplied array
* @param maximumCapacity
* the maximum capacity to which the byte store may grow
* @return new bytes the specified maximum capacity
*/
public static StreamBytes bytes(byte[] bytes, int length, int maximumCapacity) {
if (length < 0L) throw new IllegalArgumentException("negative length");
if (maximumCapacity < 0L) throw new IllegalArgumentException("negative maximumCapacity");
if (bytes.length > maximumCapacity) throw new IllegalArgumentException("initial capacity exceeds maximumCapacity");
return new StreamBytes(bytes, length, maximumCapacity);
}
/**
* <p>
* Creates a stream that reads from the supplied channel. Bytes will be read
* starting from the current channel position.
*
* <p>
* Any {@link IOException} encountered by this class is wrapped as
* {@link StreamException} and rethrown. Any end-of-stream condition is
* signalled with an {@link EndOfStreamException} except when encountered
* during a call to {@link #fillBuffer(ByteBuffer)}, in that case, an EOS
* condition is identified by <code>buffer.hasRemaining()</code> returning
* true. Note that modifying the channel while accessing it via a stream is
* likely to produce inconsistencies.
*
* @param channel
* a byte channel
*
* @see EndOfStreamException#EOS
*/
public static ReadStream streamReadable(ReadableByteChannel channel) {
if (channel == null) throw new IllegalArgumentException("null channel");
return new ChannelReadStream(channel);
}
/**
* <p>
* Creates a stream that writes to the supplied channel. Bytes will be
* written starting from the current channel position.
*
* <p>
* Any {@link IOException} encountered by the stream is wrapped as a
* {@link StreamException} and rethrown. Any end-of-stream condition is
* signalled with an {@link EndOfStreamException} except when encountered
* during a call to {@link #fillBuffer(ByteBuffer)}, in that case, an EOS
* condition is identified by <code>buffer.hasRemaining()</code> returning
* true. Note that modifying the channel while accessing it via a stream is
* likely to produce inconsistencies.
*
* @param channel
* a byte channel
*
* @see EndOfStreamException#EOS
*/
public static WriteStream streamWritable(WritableByteChannel channel) {
if (channel == null) throw new IllegalArgumentException("null channel");
return new ChannelWriteStream(channel);
}
/**
* <p>
* Creates a new stream which obtains bytes data from an underlying
* {@link InputStream}
*
* <p>
* Any {@link IOException} encountered by this class is wrapped as
* {@link StreamException} and rethrown. Any end-of-stream condition is
* signalled with an {@link EndOfStreamException}.
*
* @param in
* an input stream from which bytes should be read
*
* @see EndOfStreamException#EOS
*/
public static ReadStream streamInput(InputStream in) {
if (in == null) throw new IllegalArgumentException("null in");
return new InputReadStream(in);
}
/**
* <p>
* Creates a new stream which writes to an underlying {@link OutputStream}.
*
* <p>
* Any {@link IOException} encountered by this class is wrapped as
* {@link StreamException} and rethrown.
*
* @param out
* an output stream to which bytes should be written
*/
public static WriteStream streamOutput(OutputStream out) {
if (out == null) throw new IllegalArgumentException("null out");
return new OutputWriteStream(out);
}
private Streams() { }
}
| Removes import.
| src/main/java/com/tomgibara/streams/Streams.java | Removes import. | |
Java | apache-2.0 | 2c38372cc71944f6834259ac5c1d1cdd45d3107f | 0 | saltares/libgdx,SidneyXu/libgdx,czyzby/libgdx,Xhanim/libgdx,zhimaijoy/libgdx,srwonka/libGdx,Heart2009/libgdx,collinsmith/libgdx,codepoke/libgdx,FyiurAmron/libgdx,bladecoder/libgdx,petugez/libgdx,MetSystem/libgdx,ThiagoGarciaAlves/libgdx,andyvand/libgdx,collinsmith/libgdx,luischavez/libgdx,petugez/libgdx,titovmaxim/libgdx,1yvT0s/libgdx,sinistersnare/libgdx,ttencate/libgdx,xpenatan/libgdx-LWJGL3,saqsun/libgdx,bgroenks96/libgdx,youprofit/libgdx,andyvand/libgdx,del-sol/libgdx,toa5/libgdx,EsikAntony/libgdx,cypherdare/libgdx,1yvT0s/libgdx,Thotep/libgdx,js78/libgdx,saqsun/libgdx,sjosegarcia/libgdx,kagehak/libgdx,bladecoder/libgdx,firefly2442/libgdx,xoppa/libgdx,Wisienkas/libgdx,hyvas/libgdx,sjosegarcia/libgdx,TheAks999/libgdx,josephknight/libgdx,katiepino/libgdx,youprofit/libgdx,stickyd/libgdx,designcrumble/libgdx,Zomby2D/libgdx,Gliby/libgdx,sarkanyi/libgdx,sjosegarcia/libgdx,antag99/libgdx,bgroenks96/libgdx,gf11speed/libgdx,realitix/libgdx,zhimaijoy/libgdx,yangweigbh/libgdx,samskivert/libgdx,ThiagoGarciaAlves/libgdx,Deftwun/libgdx,Badazdz/libgdx,gouessej/libgdx,toa5/libgdx,gf11speed/libgdx,Wisienkas/libgdx,309746069/libgdx,djom20/libgdx,anserran/libgdx,del-sol/libgdx,sjosegarcia/libgdx,Wisienkas/libgdx,PedroRomanoBarbosa/libgdx,gouessej/libgdx,Zonglin-Li6565/libgdx,flaiker/libgdx,cypherdare/libgdx,Wisienkas/libgdx,basherone/libgdxcn,Zomby2D/libgdx,Badazdz/libgdx,snovak/libgdx,mumer92/libgdx,revo09/libgdx,copystudy/libgdx,Heart2009/libgdx,JFixby/libgdx,ninoalma/libgdx,revo09/libgdx,Deftwun/libgdx,saqsun/libgdx,nooone/libgdx,kagehak/libgdx,kotcrab/libgdx,bsmr-java/libgdx,ninoalma/libgdx,Wisienkas/libgdx,kagehak/libgdx,fwolff/libgdx,alireza-hosseini/libgdx,azakhary/libgdx,collinsmith/libgdx,noelsison2/libgdx,junkdog/libgdx,copystudy/libgdx,nrallakis/libgdx,fiesensee/libgdx,curtiszimmerman/libgdx,jsjolund/libgdx,ninoalma/libgdx,libgdx/libgdx,SidneyXu/libgdx,FyiurAmron/libgdx,thepullman/libgdx,xranby/libgdx,ztv/libgdx,davebaol/libgdx,sinistersnare/libgdx,nooone/libgdx,UnluckyNinja/libgdx,JDReutt/libgdx,Wisienkas/libgdx,andyvand/libgdx,tommycli/libgdx,gf11speed/libgdx,NathanSweet/libgdx,MadcowD/libgdx,cypherdare/libgdx,stinsonga/libgdx,stinsonga/libgdx,Senth/libgdx,MikkelTAndersen/libgdx,gouessej/libgdx,luischavez/libgdx,alex-dorokhov/libgdx,alireza-hosseini/libgdx,anserran/libgdx,nave966/libgdx,saqsun/libgdx,stickyd/libgdx,GreenLightning/libgdx,copystudy/libgdx,samskivert/libgdx,xranby/libgdx,bgroenks96/libgdx,Gliby/libgdx,saltares/libgdx,bgroenks96/libgdx,del-sol/libgdx,jasonwee/libgdx,katiepino/libgdx,toloudis/libgdx,nudelchef/libgdx,Dzamir/libgdx,KrisLee/libgdx,copystudy/libgdx,FyiurAmron/libgdx,MovingBlocks/libgdx,designcrumble/libgdx,designcrumble/libgdx,mumer92/libgdx,thepullman/libgdx,katiepino/libgdx,nudelchef/libgdx,srwonka/libGdx,UnluckyNinja/libgdx,FredGithub/libgdx,fiesensee/libgdx,Deftwun/libgdx,billgame/libgdx,yangweigbh/libgdx,curtiszimmerman/libgdx,mumer92/libgdx,ztv/libgdx,ya7lelkom/libgdx,MadcowD/libgdx,fwolff/libgdx,sinistersnare/libgdx,alireza-hosseini/libgdx,saqsun/libgdx,MetSystem/libgdx,anserran/libgdx,zommuter/libgdx,alireza-hosseini/libgdx,KrisLee/libgdx,zommuter/libgdx,JFixby/libgdx,stickyd/libgdx,del-sol/libgdx,1yvT0s/libgdx,kagehak/libgdx,nave966/libgdx,andyvand/libgdx,ricardorigodon/libgdx,MovingBlocks/libgdx,fiesensee/libgdx,lordjone/libgdx,Dzamir/libgdx,SidneyXu/libgdx,ttencate/libgdx,antag99/libgdx,saltares/libgdx,FyiurAmron/libgdx,ya7lelkom/libgdx,ricardorigodon/libgdx,Deftwun/libgdx,Xhanim/libgdx,xoppa/libgdx,realitix/libgdx,Heart2009/libgdx,KrisLee/libgdx,alireza-hosseini/libgdx,tommyettinger/libgdx,PedroRomanoBarbosa/libgdx,xoppa/libgdx,nrallakis/libgdx,kotcrab/libgdx,andyvand/libgdx,bsmr-java/libgdx,lordjone/libgdx,petugez/libgdx,gouessej/libgdx,codepoke/libgdx,djom20/libgdx,junkdog/libgdx,lordjone/libgdx,MetSystem/libgdx,luischavez/libgdx,realitix/libgdx,azakhary/libgdx,fwolff/libgdx,katiepino/libgdx,tommycli/libgdx,titovmaxim/libgdx,thepullman/libgdx,ricardorigodon/libgdx,BlueRiverInteractive/libgdx,309746069/libgdx,mumer92/libgdx,Zonglin-Li6565/libgdx,NathanSweet/libgdx,petugez/libgdx,nave966/libgdx,hyvas/libgdx,davebaol/libgdx,Xhanim/libgdx,alex-dorokhov/libgdx,stickyd/libgdx,titovmaxim/libgdx,tell10glu/libgdx,azakhary/libgdx,cypherdare/libgdx,zommuter/libgdx,curtiszimmerman/libgdx,libgdx/libgdx,ztv/libgdx,gdos/libgdx,josephknight/libgdx,gf11speed/libgdx,shiweihappy/libgdx,Thotep/libgdx,MovingBlocks/libgdx,jasonwee/libgdx,ninoalma/libgdx,jasonwee/libgdx,ztv/libgdx,srwonka/libGdx,alex-dorokhov/libgdx,gdos/libgdx,1yvT0s/libgdx,stickyd/libgdx,kagehak/libgdx,Zonglin-Li6565/libgdx,alireza-hosseini/libgdx,UnluckyNinja/libgdx,firefly2442/libgdx,antag99/libgdx,Wisienkas/libgdx,gdos/libgdx,billgame/libgdx,jberberick/libgdx,lordjone/libgdx,bladecoder/libgdx,mumer92/libgdx,fiesensee/libgdx,basherone/libgdxcn,nooone/libgdx,del-sol/libgdx,tommyettinger/libgdx,collinsmith/libgdx,MikkelTAndersen/libgdx,MovingBlocks/libgdx,SidneyXu/libgdx,thepullman/libgdx,sarkanyi/libgdx,ThiagoGarciaAlves/libgdx,GreenLightning/libgdx,ztv/libgdx,nelsonsilva/libgdx,haedri/libgdx-1,titovmaxim/libgdx,zhimaijoy/libgdx,katiepino/libgdx,Thotep/libgdx,1yvT0s/libgdx,billgame/libgdx,MikkelTAndersen/libgdx,Badazdz/libgdx,UnluckyNinja/libgdx,xpenatan/libgdx-LWJGL3,xranby/libgdx,andyvand/libgdx,MikkelTAndersen/libgdx,gf11speed/libgdx,codepoke/libgdx,jberberick/libgdx,nudelchef/libgdx,jberberick/libgdx,JFixby/libgdx,Gliby/libgdx,djom20/libgdx,zommuter/libgdx,bsmr-java/libgdx,FyiurAmron/libgdx,flaiker/libgdx,1yvT0s/libgdx,realitix/libgdx,gouessej/libgdx,copystudy/libgdx,billgame/libgdx,js78/libgdx,ttencate/libgdx,del-sol/libgdx,saqsun/libgdx,FredGithub/libgdx,MovingBlocks/libgdx,BlueRiverInteractive/libgdx,xpenatan/libgdx-LWJGL3,ricardorigodon/libgdx,sarkanyi/libgdx,nrallakis/libgdx,Gliby/libgdx,basherone/libgdxcn,MadcowD/libgdx,curtiszimmerman/libgdx,sarkanyi/libgdx,ttencate/libgdx,sinistersnare/libgdx,kotcrab/libgdx,petugez/libgdx,alireza-hosseini/libgdx,alex-dorokhov/libgdx,PedroRomanoBarbosa/libgdx,toloudis/libgdx,josephknight/libgdx,nrallakis/libgdx,KrisLee/libgdx,Dzamir/libgdx,alireza-hosseini/libgdx,js78/libgdx,kagehak/libgdx,del-sol/libgdx,titovmaxim/libgdx,youprofit/libgdx,ThiagoGarciaAlves/libgdx,Zonglin-Li6565/libgdx,noelsison2/libgdx,jasonwee/libgdx,Heart2009/libgdx,Thotep/libgdx,antag99/libgdx,Senth/libgdx,GreenLightning/libgdx,flaiker/libgdx,youprofit/libgdx,SidneyXu/libgdx,snovak/libgdx,PedroRomanoBarbosa/libgdx,SidneyXu/libgdx,jsjolund/libgdx,zommuter/libgdx,EsikAntony/libgdx,PedroRomanoBarbosa/libgdx,samskivert/libgdx,Badazdz/libgdx,FyiurAmron/libgdx,kotcrab/libgdx,JFixby/libgdx,yangweigbh/libgdx,nelsonsilva/libgdx,nelsonsilva/libgdx,firefly2442/libgdx,gdos/libgdx,josephknight/libgdx,fwolff/libgdx,FredGithub/libgdx,samskivert/libgdx,Arcnor/libgdx,noelsison2/libgdx,MetSystem/libgdx,nooone/libgdx,fiesensee/libgdx,BlueRiverInteractive/libgdx,js78/libgdx,BlueRiverInteractive/libgdx,MikkelTAndersen/libgdx,realitix/libgdx,zhimaijoy/libgdx,FredGithub/libgdx,ttencate/libgdx,toa5/libgdx,Xhanim/libgdx,saltares/libgdx,GreenLightning/libgdx,gdos/libgdx,davebaol/libgdx,czyzby/libgdx,PedroRomanoBarbosa/libgdx,stinsonga/libgdx,samskivert/libgdx,MetSystem/libgdx,basherone/libgdxcn,czyzby/libgdx,Xhanim/libgdx,toa5/libgdx,jsjolund/libgdx,antag99/libgdx,noelsison2/libgdx,mumer92/libgdx,JDReutt/libgdx,nave966/libgdx,xoppa/libgdx,davebaol/libgdx,czyzby/libgdx,junkdog/libgdx,firefly2442/libgdx,Deftwun/libgdx,shiweihappy/libgdx,flaiker/libgdx,nrallakis/libgdx,gouessej/libgdx,tell10glu/libgdx,gf11speed/libgdx,Senth/libgdx,gouessej/libgdx,ThiagoGarciaAlves/libgdx,JDReutt/libgdx,tommyettinger/libgdx,josephknight/libgdx,sarkanyi/libgdx,SidneyXu/libgdx,ninoalma/libgdx,haedri/libgdx-1,Senth/libgdx,lordjone/libgdx,youprofit/libgdx,xpenatan/libgdx-LWJGL3,KrisLee/libgdx,sarkanyi/libgdx,ya7lelkom/libgdx,sarkanyi/libgdx,Thotep/libgdx,petugez/libgdx,hyvas/libgdx,tell10glu/libgdx,curtiszimmerman/libgdx,sjosegarcia/libgdx,PedroRomanoBarbosa/libgdx,ninoalma/libgdx,Dzamir/libgdx,xpenatan/libgdx-LWJGL3,Arcnor/libgdx,sinistersnare/libgdx,saqsun/libgdx,zommuter/libgdx,TheAks999/libgdx,bsmr-java/libgdx,ya7lelkom/libgdx,tell10glu/libgdx,ya7lelkom/libgdx,Dzamir/libgdx,nooone/libgdx,toloudis/libgdx,js78/libgdx,Badazdz/libgdx,toa5/libgdx,xpenatan/libgdx-LWJGL3,MikkelTAndersen/libgdx,Zomby2D/libgdx,revo09/libgdx,MovingBlocks/libgdx,noelsison2/libgdx,samskivert/libgdx,toloudis/libgdx,MetSystem/libgdx,JFixby/libgdx,firefly2442/libgdx,junkdog/libgdx,antag99/libgdx,TheAks999/libgdx,ninoalma/libgdx,junkdog/libgdx,libgdx/libgdx,stinsonga/libgdx,JFixby/libgdx,yangweigbh/libgdx,jberberick/libgdx,309746069/libgdx,azakhary/libgdx,MadcowD/libgdx,Gliby/libgdx,firefly2442/libgdx,josephknight/libgdx,designcrumble/libgdx,PedroRomanoBarbosa/libgdx,jsjolund/libgdx,toa5/libgdx,tommycli/libgdx,309746069/libgdx,tell10glu/libgdx,tommyettinger/libgdx,kagehak/libgdx,xoppa/libgdx,hyvas/libgdx,zhimaijoy/libgdx,Thotep/libgdx,JFixby/libgdx,ya7lelkom/libgdx,thepullman/libgdx,bsmr-java/libgdx,junkdog/libgdx,lordjone/libgdx,thepullman/libgdx,xpenatan/libgdx-LWJGL3,tommycli/libgdx,stickyd/libgdx,toa5/libgdx,toloudis/libgdx,saltares/libgdx,alex-dorokhov/libgdx,Heart2009/libgdx,djom20/libgdx,antag99/libgdx,josephknight/libgdx,kotcrab/libgdx,czyzby/libgdx,xranby/libgdx,309746069/libgdx,gdos/libgdx,anserran/libgdx,czyzby/libgdx,designcrumble/libgdx,libgdx/libgdx,ztv/libgdx,petugez/libgdx,hyvas/libgdx,billgame/libgdx,andyvand/libgdx,stickyd/libgdx,curtiszimmerman/libgdx,hyvas/libgdx,Wisienkas/libgdx,titovmaxim/libgdx,nelsonsilva/libgdx,designcrumble/libgdx,haedri/libgdx-1,Zomby2D/libgdx,sjosegarcia/libgdx,gouessej/libgdx,309746069/libgdx,revo09/libgdx,SidneyXu/libgdx,luischavez/libgdx,Zonglin-Li6565/libgdx,jberberick/libgdx,alex-dorokhov/libgdx,junkdog/libgdx,hyvas/libgdx,Arcnor/libgdx,UnluckyNinja/libgdx,FyiurAmron/libgdx,bladecoder/libgdx,nrallakis/libgdx,BlueRiverInteractive/libgdx,toloudis/libgdx,sinistersnare/libgdx,junkdog/libgdx,EsikAntony/libgdx,tommycli/libgdx,tommycli/libgdx,haedri/libgdx-1,gdos/libgdx,NathanSweet/libgdx,jsjolund/libgdx,cypherdare/libgdx,Gliby/libgdx,FredGithub/libgdx,kagehak/libgdx,luischavez/libgdx,revo09/libgdx,309746069/libgdx,Deftwun/libgdx,flaiker/libgdx,Deftwun/libgdx,snovak/libgdx,srwonka/libGdx,haedri/libgdx-1,EsikAntony/libgdx,anserran/libgdx,nudelchef/libgdx,Senth/libgdx,billgame/libgdx,codepoke/libgdx,KrisLee/libgdx,Senth/libgdx,mumer92/libgdx,ztv/libgdx,shiweihappy/libgdx,EsikAntony/libgdx,jsjolund/libgdx,UnluckyNinja/libgdx,ninoalma/libgdx,alex-dorokhov/libgdx,ricardorigodon/libgdx,tommycli/libgdx,UnluckyNinja/libgdx,firefly2442/libgdx,GreenLightning/libgdx,bgroenks96/libgdx,mumer92/libgdx,titovmaxim/libgdx,alex-dorokhov/libgdx,luischavez/libgdx,GreenLightning/libgdx,Heart2009/libgdx,FyiurAmron/libgdx,katiepino/libgdx,nooone/libgdx,shiweihappy/libgdx,GreenLightning/libgdx,djom20/libgdx,josephknight/libgdx,Badazdz/libgdx,JDReutt/libgdx,nelsonsilva/libgdx,jasonwee/libgdx,azakhary/libgdx,nudelchef/libgdx,ttencate/libgdx,KrisLee/libgdx,copystudy/libgdx,sjosegarcia/libgdx,curtiszimmerman/libgdx,copystudy/libgdx,titovmaxim/libgdx,flaiker/libgdx,UnluckyNinja/libgdx,noelsison2/libgdx,Senth/libgdx,haedri/libgdx-1,stickyd/libgdx,FredGithub/libgdx,xranby/libgdx,jsjolund/libgdx,thepullman/libgdx,ztv/libgdx,zommuter/libgdx,MovingBlocks/libgdx,EsikAntony/libgdx,jberberick/libgdx,kotcrab/libgdx,zommuter/libgdx,nave966/libgdx,yangweigbh/libgdx,zhimaijoy/libgdx,samskivert/libgdx,collinsmith/libgdx,Gliby/libgdx,snovak/libgdx,Dzamir/libgdx,MetSystem/libgdx,saltares/libgdx,TheAks999/libgdx,basherone/libgdxcn,xoppa/libgdx,TheAks999/libgdx,bgroenks96/libgdx,shiweihappy/libgdx,codepoke/libgdx,TheAks999/libgdx,JDReutt/libgdx,srwonka/libGdx,Heart2009/libgdx,copystudy/libgdx,BlueRiverInteractive/libgdx,nelsonsilva/libgdx,TheAks999/libgdx,jasonwee/libgdx,tell10glu/libgdx,BlueRiverInteractive/libgdx,JDReutt/libgdx,309746069/libgdx,MovingBlocks/libgdx,fwolff/libgdx,revo09/libgdx,BlueRiverInteractive/libgdx,TheAks999/libgdx,yangweigbh/libgdx,hyvas/libgdx,js78/libgdx,anserran/libgdx,xoppa/libgdx,bsmr-java/libgdx,FredGithub/libgdx,nrallakis/libgdx,jsjolund/libgdx,fwolff/libgdx,KrisLee/libgdx,tell10glu/libgdx,nudelchef/libgdx,tommycli/libgdx,bladecoder/libgdx,shiweihappy/libgdx,gf11speed/libgdx,MikkelTAndersen/libgdx,xranby/libgdx,codepoke/libgdx,jberberick/libgdx,Zonglin-Li6565/libgdx,xranby/libgdx,MadcowD/libgdx,EsikAntony/libgdx,czyzby/libgdx,shiweihappy/libgdx,antag99/libgdx,flaiker/libgdx,nudelchef/libgdx,toa5/libgdx,snovak/libgdx,ricardorigodon/libgdx,realitix/libgdx,collinsmith/libgdx,del-sol/libgdx,fiesensee/libgdx,shiweihappy/libgdx,ya7lelkom/libgdx,JDReutt/libgdx,youprofit/libgdx,ThiagoGarciaAlves/libgdx,snovak/libgdx,JFixby/libgdx,ricardorigodon/libgdx,Gliby/libgdx,zhimaijoy/libgdx,zhimaijoy/libgdx,1yvT0s/libgdx,Arcnor/libgdx,czyzby/libgdx,yangweigbh/libgdx,fiesensee/libgdx,billgame/libgdx,Zonglin-Li6565/libgdx,andyvand/libgdx,JDReutt/libgdx,anserran/libgdx,saltares/libgdx,lordjone/libgdx,Dzamir/libgdx,EsikAntony/libgdx,Xhanim/libgdx,lordjone/libgdx,djom20/libgdx,davebaol/libgdx,luischavez/libgdx,xoppa/libgdx,ThiagoGarciaAlves/libgdx,collinsmith/libgdx,bsmr-java/libgdx,Thotep/libgdx,codepoke/libgdx,tell10glu/libgdx,Senth/libgdx,youprofit/libgdx,anserran/libgdx,Heart2009/libgdx,nave966/libgdx,libgdx/libgdx,ricardorigodon/libgdx,bsmr-java/libgdx,1yvT0s/libgdx,sjosegarcia/libgdx,sarkanyi/libgdx,stinsonga/libgdx,Zomby2D/libgdx,nrallakis/libgdx,realitix/libgdx,djom20/libgdx,ThiagoGarciaAlves/libgdx,srwonka/libGdx,xranby/libgdx,srwonka/libGdx,js78/libgdx,youprofit/libgdx,nave966/libgdx,basherone/libgdxcn,realitix/libgdx,katiepino/libgdx,toloudis/libgdx,toloudis/libgdx,MadcowD/libgdx,js78/libgdx,Badazdz/libgdx,katiepino/libgdx,collinsmith/libgdx,tommyettinger/libgdx,revo09/libgdx,haedri/libgdx-1,jberberick/libgdx,FredGithub/libgdx,saqsun/libgdx,ttencate/libgdx,kotcrab/libgdx,firefly2442/libgdx,Arcnor/libgdx,gdos/libgdx,Thotep/libgdx,MetSystem/libgdx,ttencate/libgdx,haedri/libgdx-1,bgroenks96/libgdx,noelsison2/libgdx,fwolff/libgdx,yangweigbh/libgdx,snovak/libgdx,Arcnor/libgdx,Dzamir/libgdx,curtiszimmerman/libgdx,nudelchef/libgdx,gf11speed/libgdx,ya7lelkom/libgdx,Xhanim/libgdx,samskivert/libgdx,noelsison2/libgdx,snovak/libgdx,djom20/libgdx,MadcowD/libgdx,Xhanim/libgdx,luischavez/libgdx,petugez/libgdx,srwonka/libGdx,NathanSweet/libgdx,saltares/libgdx,revo09/libgdx,davebaol/libgdx,flaiker/libgdx,xpenatan/libgdx-LWJGL3,jasonwee/libgdx,fwolff/libgdx,Deftwun/libgdx,NathanSweet/libgdx,kotcrab/libgdx,Badazdz/libgdx,billgame/libgdx,GreenLightning/libgdx,fiesensee/libgdx,azakhary/libgdx,nave966/libgdx,bgroenks96/libgdx,designcrumble/libgdx,designcrumble/libgdx,MadcowD/libgdx,codepoke/libgdx,Zonglin-Li6565/libgdx,thepullman/libgdx,jasonwee/libgdx,MikkelTAndersen/libgdx | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.math;
import com.badlogic.gdx.utils.FloatArray;
import com.badlogic.gdx.utils.IntArray;
import com.badlogic.gdx.utils.ShortArray;
/** Computes the convex hull of a set of points using the monotone chain convex hull algorithm (aka Andrew's algorithm).
* @author Nathan Sweet */
public class ConvexHull {
private final IntArray quicksortStack = new IntArray();
private float[] sortedPoints;
private final FloatArray hull = new FloatArray();
private final IntArray indices = new IntArray();
private final ShortArray originalIndices = new ShortArray(false, 0);
/** @see #computePolygon(float[], int, int, boolean) */
public FloatArray computePolygon (FloatArray points, boolean sorted) {
return computePolygon(points.items, 0, points.size, sorted);
}
/** @see #computePolygon(float[], int, int, boolean) */
public FloatArray computePolygon (float[] polygon, boolean sorted) {
return computePolygon(polygon, 0, polygon.length, sorted);
}
/** Returns a list of points on the convex hull in counter-clockwise order. Note: the last point in the returned list is the
* same as the first one. */
/** Returns the convex hull polygon for the given point cloud.
* @param points x,y pairs describing points. Duplicate points will result in undefined behavior.
* @param sorted If false, the points will be sorted by the x coordinate then the y coordinate, which is required by the convex
* hull algorithm. If sorting is done the input array is not modified and count additional working memory is needed.
* @return pairs of coordinates that describe the convex hull polygon in counterclockwise order. Note the returned array is
* reused for later calls to the same method. */
public FloatArray computePolygon (float[] points, int offset, int count, boolean sorted) {
int end = offset + count;
if (!sorted) {
if (sortedPoints == null || sortedPoints.length < count) sortedPoints = new float[count];
System.arraycopy(points, offset, sortedPoints, 0, count);
points = sortedPoints;
offset = 0;
sort(points, count);
}
FloatArray hull = this.hull;
hull.clear();
// Lower hull.
for (int i = offset; i < end; i += 2) {
float x = points[i];
float y = points[i + 1];
while (hull.size >= 4 && ccw(x, y) <= 0)
hull.size -= 2;
hull.add(x);
hull.add(y);
}
// Upper hull.
for (int i = end - 4, t = hull.size + 2; i >= offset; i -= 2) {
float x = points[i];
float y = points[i + 1];
while (hull.size >= t && ccw(x, y) <= 0)
hull.size -= 2;
hull.add(x);
hull.add(y);
}
return hull;
}
/** @see #computeIndices(float[], int, int, boolean, boolean) */
public IntArray computeIndices (FloatArray points, boolean sorted, boolean yDown) {
return computeIndices(points.items, 0, points.size, sorted, yDown);
}
/** @see #computeIndices(float[], int, int, boolean, boolean) */
public IntArray computeIndices (float[] polygon, boolean sorted, boolean yDown) {
return computeIndices(polygon, 0, polygon.length, sorted, yDown);
}
/** Computes a hull the same as {@link #computePolygon(float[], int, int, boolean)} but returns indices of the specified points. */
public IntArray computeIndices (float[] points, int offset, int count, boolean sorted, boolean yDown) {
int end = offset + count;
if (!sorted) {
if (sortedPoints == null || sortedPoints.length < count) sortedPoints = new float[count];
System.arraycopy(points, offset, sortedPoints, 0, count);
points = sortedPoints;
offset = 0;
sortWithIndices(points, count, yDown);
}
IntArray indices = this.indices;
indices.clear();
FloatArray hull = this.hull;
hull.clear();
// Lower hull.
for (int i = offset, index = i / 2; i < end; i += 2, index++) {
float x = points[i];
float y = points[i + 1];
while (hull.size >= 4 && ccw(x, y) <= 0) {
hull.size -= 2;
indices.size--;
}
hull.add(x);
hull.add(y);
indices.add(index);
}
// Upper hull.
for (int i = end - 4, index = i / 2, t = hull.size + 2; i >= offset; i -= 2, index--) {
float x = points[i];
float y = points[i + 1];
while (hull.size >= t && ccw(x, y) <= 0) {
hull.size -= 2;
indices.size--;
}
hull.add(x);
hull.add(y);
indices.add(index);
}
// Convert sorted to unsorted indices.
if (!sorted) {
short[] originalIndicesArray = originalIndices.items;
int[] indicesArray = indices.items;
for (int i = 0, n = indices.size; i < n; i++)
indicesArray[i] = originalIndicesArray[indicesArray[i]];
}
return indices;
}
/** Returns > 0 if the points are a counterclockwise turn, < 0 if clockwise, and 0 if colinear. */
private float ccw (float p3x, float p3y) {
FloatArray hull = this.hull;
int size = hull.size;
float p1x = hull.get(size - 4);
float p1y = hull.get(size - 3);
float p2x = hull.get(size - 2);
float p2y = hull.peek();
return (p2x - p1x) * (p3y - p1y) - (p2y - p1y) * (p3x - p1x);
}
/** Sorts x,y pairs of values by the x value, then the y value.
* @param count Number of indices, must be even. */
private void sort (float[] values, int count) {
int lower = 0;
int upper = count - 1;
IntArray stack = quicksortStack;
stack.add(lower);
stack.add(upper - 1);
while (stack.size > 0) {
upper = stack.pop();
lower = stack.pop();
if (upper <= lower) continue;
int i = quicksortPartition(values, lower, upper);
if (i - lower > upper - i) {
stack.add(lower);
stack.add(i - 2);
}
stack.add(i + 2);
stack.add(upper);
if (upper - i >= i - lower) {
stack.add(lower);
stack.add(i - 2);
}
}
}
private int quicksortPartition (final float[] values, int lower, int upper) {
float x = values[lower];
float y = values[lower + 1];
int up = upper;
int down = lower;
float temp;
short tempIndex;
while (down < up) {
while (down < up && values[down] <= x)
down = down + 2;
while (values[up] > x || (values[up] == x && values[up + 1] < y))
up = up - 2;
if (down < up) {
temp = values[down];
values[down] = values[up];
values[up] = temp;
temp = values[down + 1];
values[down + 1] = values[up + 1];
values[up + 1] = temp;
}
}
values[lower] = values[up];
values[up] = x;
values[lower + 1] = values[up + 1];
values[up + 1] = y;
return up;
}
/** Sorts x,y pairs of values by the x value, then the y value and stores unsorted original indices.
* @param count Number of indices, must be even. */
private void sortWithIndices (float[] values, int count, boolean yDown) {
int pointCount = count / 2;
originalIndices.clear();
originalIndices.ensureCapacity(pointCount);
short[] originalIndicesArray = originalIndices.items;
for (short i = 0; i < pointCount; i++)
originalIndicesArray[i] = i;
int lower = 0;
int upper = count - 1;
IntArray stack = quicksortStack;
stack.add(lower);
stack.add(upper - 1);
while (stack.size > 0) {
upper = stack.pop();
lower = stack.pop();
if (upper <= lower) continue;
int i = quicksortPartitionWithIndices(values, lower, upper, yDown, originalIndicesArray);
if (i - lower > upper - i) {
stack.add(lower);
stack.add(i - 2);
}
stack.add(i + 2);
stack.add(upper);
if (upper - i >= i - lower) {
stack.add(lower);
stack.add(i - 2);
}
}
}
private int quicksortPartitionWithIndices (final float[] values, int lower, int upper, boolean yDown, short[] originalIndices) {
float x = values[lower];
float y = values[lower + 1];
int up = upper;
int down = lower;
float temp;
short tempIndex;
while (down < up) {
while (down < up && values[down] <= x)
down = down + 2;
if (yDown) {
while (values[up] > x || (values[up] == x && values[up + 1] < y))
up = up - 2;
} else {
while (values[up] > x || (values[up] == x && values[up + 1] > y))
up = up - 2;
}
if (down < up) {
temp = values[down];
values[down] = values[up];
values[up] = temp;
temp = values[down + 1];
values[down + 1] = values[up + 1];
values[up + 1] = temp;
tempIndex = originalIndices[down / 2];
originalIndices[down / 2] = originalIndices[up / 2];
originalIndices[up / 2] = tempIndex;
}
}
values[lower] = values[up];
values[up] = x;
values[lower + 1] = values[up + 1];
values[up + 1] = y;
tempIndex = originalIndices[lower / 2];
originalIndices[lower / 2] = originalIndices[up / 2];
originalIndices[up / 2] = tempIndex;
return up;
}
}
| gdx/src/com/badlogic/gdx/math/ConvexHull.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.math;
import com.badlogic.gdx.utils.FloatArray;
import com.badlogic.gdx.utils.IntArray;
import com.badlogic.gdx.utils.ShortArray;
/** Computes the convex hull of a set of points using the monotone chain convex hull algorithm (aka Andrew's algorithm).
* @author Nathan Sweet */
public class ConvexHull {
private final IntArray quicksortStack = new IntArray();
private float[] sortedPoints;
private final FloatArray hull = new FloatArray();
private final IntArray indices = new IntArray();
private final ShortArray originalIndices = new ShortArray(false, 0);
/** @see #computePolygon(float[], int, int, boolean, boolean) */
public FloatArray computePolygon (FloatArray points, boolean sorted, boolean yDown) {
return computePolygon(points.items, 0, points.size, sorted, yDown);
}
/** @see #computePolygon(float[], int, int, boolean, boolean) */
public FloatArray computePolygon (float[] polygon, boolean sorted, boolean yDown) {
return computePolygon(polygon, 0, polygon.length, sorted, yDown);
}
/** Returns a list of points on the convex hull in counter-clockwise order. Note: the last point in the returned list is the
* same as the first one. */
/** Returns the convex hull polygon for the given point cloud.
* @param points x,y pairs describing points. Duplicate points will result in undefined behavior.
* @param sorted If false, the points will be sorted by the x coordinate then the y coordinate, which is required by the convex
* hull algorithm. If sorting is done the input array is not modified and count additional working memory is needed.
* @param yDown Determines the direction of the y axis for sorting.
* @return pairs of coordinates that describe the convex hull polygon in counterclockwise order. Note the returned array is
* reused for later calls to the same method. */
public FloatArray computePolygon (float[] points, int offset, int count, boolean sorted, boolean yDown) {
int end = offset + count;
if (!sorted) {
if (sortedPoints == null || sortedPoints.length < count) sortedPoints = new float[count];
System.arraycopy(points, offset, sortedPoints, 0, count);
points = sortedPoints;
offset = 0;
sort(points, count, yDown);
}
FloatArray hull = this.hull;
hull.clear();
// Lower hull.
for (int i = offset; i < end; i += 2) {
float x = points[i];
float y = points[i + 1];
while (hull.size >= 4 && ccw(x, y) <= 0)
hull.size -= 2;
hull.add(x);
hull.add(y);
}
// Upper hull.
for (int i = end - 4, t = hull.size + 2; i >= offset; i -= 2) {
float x = points[i];
float y = points[i + 1];
while (hull.size >= t && ccw(x, y) <= 0)
hull.size -= 2;
hull.add(x);
hull.add(y);
}
return hull;
}
/** @see #computeIndices(float[], int, int, boolean, boolean) */
public IntArray computeIndices (FloatArray points, boolean sorted, boolean yDown) {
return computeIndices(points.items, 0, points.size, sorted, yDown);
}
/** @see #computeIndices(float[], int, int, boolean, boolean) */
public IntArray computeIndices (float[] polygon, boolean sorted, boolean yDown) {
return computeIndices(polygon, 0, polygon.length, sorted, yDown);
}
/** Computes a hull the same as {@link #computePolygon(float[], int, int, boolean, boolean)} but returns indices of the
* specified points. */
public IntArray computeIndices (float[] points, int offset, int count, boolean sorted, boolean yDown) {
int end = offset + count;
if (!sorted) {
if (sortedPoints == null || sortedPoints.length < count) sortedPoints = new float[count];
System.arraycopy(points, offset, sortedPoints, 0, count);
points = sortedPoints;
offset = 0;
sortWithIndices(points, count, yDown);
}
IntArray indices = this.indices;
indices.clear();
FloatArray hull = this.hull;
hull.clear();
// Lower hull.
for (int i = offset, index = i / 2; i < end; i += 2, index++) {
float x = points[i];
float y = points[i + 1];
while (hull.size >= 4 && ccw(x, y) <= 0) {
hull.size -= 2;
indices.size--;
}
hull.add(x);
hull.add(y);
indices.add(index);
}
// Upper hull.
for (int i = end - 4, index = i / 2, t = hull.size + 2; i >= offset; i -= 2, index--) {
float x = points[i];
float y = points[i + 1];
while (hull.size >= t && ccw(x, y) <= 0) {
hull.size -= 2;
indices.size--;
}
hull.add(x);
hull.add(y);
indices.add(index);
}
// Convert sorted to unsorted indices.
if (!sorted) {
short[] originalIndicesArray = originalIndices.items;
int[] indicesArray = indices.items;
for (int i = 0, n = indices.size; i < n; i++)
indicesArray[i] = originalIndicesArray[indicesArray[i]];
}
return indices;
}
/** Returns > 0 if the points are a counterclockwise turn, < 0 if clockwise, and 0 if colinear. */
private float ccw (float p3x, float p3y) {
FloatArray hull = this.hull;
int size = hull.size;
float p1x = hull.get(size - 4);
float p1y = hull.get(size - 3);
float p2x = hull.get(size - 2);
float p2y = hull.peek();
return (p2x - p1x) * (p3y - p1y) - (p2y - p1y) * (p3x - p1x);
}
/** Sorts x,y pairs of values by the x value, then the y value.
* @param count Number of indices, must be even. */
private void sort (float[] values, int count, boolean yDown) {
int lower = 0;
int upper = count - 1;
IntArray stack = quicksortStack;
stack.add(lower);
stack.add(upper - 1);
while (stack.size > 0) {
upper = stack.pop();
lower = stack.pop();
if (upper <= lower) continue;
int i = quicksortPartition(values, lower, upper, yDown);
if (i - lower > upper - i) {
stack.add(lower);
stack.add(i - 2);
}
stack.add(i + 2);
stack.add(upper);
if (upper - i >= i - lower) {
stack.add(lower);
stack.add(i - 2);
}
}
}
private int quicksortPartition (final float[] values, int lower, int upper, boolean yDown) {
float x = values[lower];
float y = values[lower + 1];
int up = upper;
int down = lower;
float temp;
short tempIndex;
while (down < up) {
while (down < up && values[down] <= x)
down = down + 2;
if (yDown) {
while (values[up] > x || (values[up] == x && values[up + 1] < y))
up = up - 2;
} else {
while (values[up] > x || (values[up] == x && values[up + 1] > y))
up = up - 2;
}
if (down < up) {
temp = values[down];
values[down] = values[up];
values[up] = temp;
temp = values[down + 1];
values[down + 1] = values[up + 1];
values[up + 1] = temp;
}
}
values[lower] = values[up];
values[up] = x;
values[lower + 1] = values[up + 1];
values[up + 1] = y;
return up;
}
/** Sorts x,y pairs of values by the x value, then the y value and stores unsorted original indices.
* @param count Number of indices, must be even. */
private void sortWithIndices (float[] values, int count, boolean yDown) {
int pointCount = count / 2;
originalIndices.clear();
originalIndices.ensureCapacity(pointCount);
short[] originalIndicesArray = originalIndices.items;
for (short i = 0; i < pointCount; i++)
originalIndicesArray[i] = i;
int lower = 0;
int upper = count - 1;
IntArray stack = quicksortStack;
stack.add(lower);
stack.add(upper - 1);
while (stack.size > 0) {
upper = stack.pop();
lower = stack.pop();
if (upper <= lower) continue;
int i = quicksortPartitionWithIndices(values, lower, upper, yDown, originalIndicesArray);
if (i - lower > upper - i) {
stack.add(lower);
stack.add(i - 2);
}
stack.add(i + 2);
stack.add(upper);
if (upper - i >= i - lower) {
stack.add(lower);
stack.add(i - 2);
}
}
}
private int quicksortPartitionWithIndices (final float[] values, int lower, int upper, boolean yDown, short[] originalIndices) {
float x = values[lower];
float y = values[lower + 1];
int up = upper;
int down = lower;
float temp;
short tempIndex;
while (down < up) {
while (down < up && values[down] <= x)
down = down + 2;
if (yDown) {
while (values[up] > x || (values[up] == x && values[up + 1] < y))
up = up - 2;
} else {
while (values[up] > x || (values[up] == x && values[up + 1] > y))
up = up - 2;
}
if (down < up) {
temp = values[down];
values[down] = values[up];
values[up] = temp;
temp = values[down + 1];
values[down + 1] = values[up + 1];
values[up + 1] = temp;
tempIndex = originalIndices[down / 2];
originalIndices[down / 2] = originalIndices[up / 2];
originalIndices[up / 2] = tempIndex;
}
}
values[lower] = values[up];
values[up] = x;
values[lower + 1] = values[up + 1];
values[up + 1] = y;
tempIndex = originalIndices[lower / 2];
originalIndices[lower / 2] = originalIndices[up / 2];
originalIndices[up / 2] = tempIndex;
return up;
}
}
| It appears sorting based on y up/down is not necessary.
It gives incorrect results with clockwise, colinear points.
| gdx/src/com/badlogic/gdx/math/ConvexHull.java | It appears sorting based on y up/down is not necessary. | |
Java | apache-2.0 | b1d16e3fe831d816ca565b227b1711c69bcf793a | 0 | tudelft-atlarge/graphalytics-platforms-graphlab,tudelft-atlarge/graphalytics-platforms-graphlab,tudelft-atlarge/graphalytics-platforms-graphlab | package nl.tudelft.graphalytics.graphlab;
import nl.tudelft.graphalytics.PlatformExecutionException;
import nl.tudelft.graphalytics.domain.Algorithm;
import nl.tudelft.graphalytics.domain.Graph;
import nl.tudelft.graphalytics.domain.GraphFormat;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.PumpStreamHandler;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Template Test class for a GraphLab algorithm.
* @author Jorai Rijsdijk
*/
public abstract class AlgorithmTest {
protected static GraphLabPlatform graphLab = new GraphLabPlatform();
private static final String BASE_PATH = AlgorithmTest.class.getResource("/").getPath();
protected void performTest(Algorithm algorithm, String prefix, String algorithmFile, Object parameters, boolean directed, boolean edgeBased) {
graphLab.setSaveGraphResult(true);
String graphFile = "test-examples/" + prefix + "-input";
Graph graph = new Graph(prefix + "-input", graphFile, new GraphFormat(directed, edgeBased));
try {
graphLab.uploadGraph(graph, BASE_PATH + graphFile);
} catch (Exception e) {
fail("Unable to upload graph" + (e.getMessage() != null ? ": " + e.getMessage() : ""));
e.printStackTrace();
}
try {
graphLab.executeAlgorithmOnGraph(algorithm, graph, parameters);
} catch (PlatformExecutionException e) {
fail("Algorithm execution failed" + (e.getMessage() != null ? ": " + e.getMessage() : ""));
e.printStackTrace();
}
File testScriptFile = new File(BASE_PATH, "nl/tudelft/graphalytics/graphlab/" + algorithmFile);
assertTrue(executeTestScript(testScriptFile, "target/" + algorithm.toString().toLowerCase() + "_" + graph.getName(), BASE_PATH + "test-examples/" + prefix + "-output"));
}
protected boolean executeTestScript(File scriptFile, String graphFile, String outputFile) {
if (!scriptFile.exists()) {
throw new IllegalArgumentException("Cannot find GraphLab Test script: " + scriptFile.getAbsolutePath());
}
CommandLine commandLine = new CommandLine("python2");
commandLine.addArgument(scriptFile.getAbsolutePath());
commandLine.addArgument(graphFile);
commandLine.addArgument(outputFile);
// Set the executor of the command, if desired this can be changed to a custom implementation
DefaultExecutor executor = new DefaultExecutor();
// Set the OutputStream to enable printing the output of the algorithm
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
executor.setStreamHandler(new PumpStreamHandler(outputStream));
try {
// Execute the actual command and store the return code
executor.execute(commandLine);
// Print the command output
System.out.println(outputStream.toString());
return true;
} catch (IOException e) {
// Catch the exception thrown when the process exits with result != 0 or another IOException occurs
System.out.println(outputStream.toString());
return false;
}
}
}
| src/test/java/nl.tudelft.graphalytics.graphlab/AlgorithmTest.java | package nl.tudelft.graphalytics.graphlab;
import nl.tudelft.graphalytics.PlatformExecutionException;
import nl.tudelft.graphalytics.domain.Algorithm;
import nl.tudelft.graphalytics.domain.Graph;
import nl.tudelft.graphalytics.domain.GraphFormat;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.PumpStreamHandler;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Template Test class for a GraphLab algorithm.
* @author Jorai Rijsdijk
*/
public abstract class AlgorithmTest {
protected static GraphLabPlatform graphLab = new GraphLabPlatform();
private static final String BASE_PATH = AlgorithmTest.class.getResource("/").getPath();
protected void performTest(Algorithm algorithm, String prefix, String algorithmFile, Object parameters, boolean directed, boolean edgeBased) {
graphLab.setSaveGraphResult(true);
String graphFile = "test-examples/" + prefix + "-input";
Graph graph = new Graph(prefix + "-input", graphFile, new GraphFormat(directed, edgeBased));
try {
graphLab.uploadGraph(graph, BASE_PATH + graphFile);
} catch (Exception e) {
fail("Unable to upload graph" + (e.getMessage() != null ? ": " + e.getMessage() : ""));
e.printStackTrace();
}
try {
graphLab.executeAlgorithmOnGraph(algorithm, graph, parameters);
} catch (PlatformExecutionException e) {
fail("Algorithm execution failed" + (e.getMessage() != null ? ": " + e.getMessage() : ""));
e.printStackTrace();
}
File testScriptFile = new File(BASE_PATH, "nl/tudelft/graphalytics/graphlab/" + algorithmFile);
assertTrue(executeTestScript(testScriptFile, "target/" + algorithm.toString().toLowerCase() + "_" + graph.getName(), BASE_PATH + "test-examples/" + prefix + "-output"));
}
protected boolean executeTestScript(File scriptFile, String graphFile, String outputFile) {
if (!scriptFile.exists()) {
throw new IllegalArgumentException("Cannot find GraphLab Test script: " + scriptFile.getAbsolutePath());
}
CommandLine commandLine = new CommandLine("python");
commandLine.addArgument(scriptFile.getAbsolutePath());
commandLine.addArgument(graphFile);
commandLine.addArgument(outputFile);
// Set the executor of the command, if desired this can be changed to a custom implementation
DefaultExecutor executor = new DefaultExecutor();
// Set the OutputStream to enable printing the output of the algorithm
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
executor.setStreamHandler(new PumpStreamHandler(outputStream));
try {
// Execute the actual command and store the return code
executor.execute(commandLine);
// Print the command output
System.out.println(outputStream.toString());
return true;
} catch (IOException e) {
// Catch the exception thrown when the process exits with result != 0 or another IOException occurs
System.out.println(outputStream.toString());
return false;
}
}
}
| [GraphLab] Change test python executable from python to python2
| src/test/java/nl.tudelft.graphalytics.graphlab/AlgorithmTest.java | [GraphLab] Change test python executable from python to python2 | |
Java | apache-2.0 | d9afae8be99350880a3e50c02853ef4de10b4ff6 | 0 | UweTrottmann/SeriesGuide,artemnikitin/SeriesGuide,UweTrottmann/SeriesGuide,r00t-user/SeriesGuide,hoanganhx86/SeriesGuide,epiphany27/SeriesGuide,0359xiaodong/SeriesGuide | /*
* Copyright 2014 Uwe Trottmann
*
* 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.battlelancer.seriesguide.ui;
import android.app.ActionBar;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.view.MenuItem;
import android.view.View;
import com.battlelancer.seriesguide.R;
public class PeopleActivity extends BaseActivity implements PeopleFragment.OnShowPersonListener {
private boolean mTwoPane;
public interface InitBundle {
String MEDIA_TYPE = "media_title";
String ITEM_TMDB_ID = "item_tmdb_id";
String PEOPLE_TYPE = "people_type";
}
public enum MediaType {
SHOW("SHOW"),
MOVIE("MOVIE");
private final String mValue;
private MediaType(String value) {
mValue = value;
}
@Override
public String toString() {
return mValue;
}
}
public enum PeopleType {
CAST("CAST"),
CREW("CREW");
private final String mValue;
private PeopleType(String value) {
mValue = value;
}
@Override
public String toString() {
return mValue;
}
}
public static final int PEOPLE_LOADER_ID = 100;
public static final int PERSON_LOADER_ID = 101;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_people);
setupActionBar();
if (findViewById(R.id.containerPeoplePerson) != null) {
mTwoPane = true;
}
if (savedInstanceState == null) {
// check if we should directly show a person
int personTmdbId = getIntent().getIntExtra(PersonFragment.InitBundle.PERSON_TMDB_ID, -1);
if (personTmdbId != -1) {
showPerson(null, personTmdbId);
// if this is not a dual pane layout, remove ourselves from back stack
if (!mTwoPane) {
finish();
return;
}
}
PeopleFragment f = new PeopleFragment();
f.setArguments(getIntent().getExtras());
// in two-pane mode, list items should be activated when touched
if (mTwoPane) {
f.setActivateOnItemClick(true);
}
getSupportFragmentManager().beginTransaction()
.add(R.id.containerPeople, f, "people-list")
.commit();
}
}
private void setupActionBar() {
final ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
PeopleType peopleType = PeopleType.valueOf(
getIntent().getStringExtra(InitBundle.PEOPLE_TYPE));
actionBar.setTitle(
peopleType == PeopleType.CAST ? R.string.movie_cast : R.string.movie_crew);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == android.R.id.home) {
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void showPerson(View view, int tmdbId) {
if (mTwoPane) {
// show inline
PersonFragment f = PersonFragment.newInstance(tmdbId);
getSupportFragmentManager().beginTransaction()
.replace(R.id.containerPeoplePerson, f)
.commit();
} else {
// start new activity
Intent i = new Intent(this, PersonActivity.class);
i.putExtra(PersonFragment.InitBundle.PERSON_TMDB_ID, tmdbId);
if (view != null) {
ActivityCompat.startActivity(this, i,
ActivityOptionsCompat
.makeScaleUpAnimation(view, 0, 0, view.getWidth(), view.getHeight())
.toBundle()
);
} else {
startActivity(i);
}
}
}
}
| SeriesGuide/src/main/java/com/battlelancer/seriesguide/ui/PeopleActivity.java | /*
* Copyright 2014 Uwe Trottmann
*
* 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.battlelancer.seriesguide.ui;
import android.app.ActionBar;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.view.MenuItem;
import android.view.View;
import com.battlelancer.seriesguide.R;
public class PeopleActivity extends BaseActivity implements PeopleFragment.OnShowPersonListener {
private boolean mTwoPane;
public interface InitBundle {
String MEDIA_TYPE = "media_title";
String ITEM_TMDB_ID = "item_tmdb_id";
String PEOPLE_TYPE = "people_type";
}
public enum MediaType {
SHOW("SHOW"),
MOVIE("MOVIE");
private final String mValue;
private MediaType(String value) {
mValue = value;
}
@Override
public String toString() {
return mValue;
}
}
public enum PeopleType {
CAST("CAST"),
CREW("CREW");
private final String mValue;
private PeopleType(String value) {
mValue = value;
}
@Override
public String toString() {
return mValue;
}
}
public static final int PEOPLE_LOADER_ID = 100;
public static final int PERSON_LOADER_ID = 101;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_people);
setupActionBar();
if (findViewById(R.id.containerPeoplePerson) != null) {
mTwoPane = true;
}
if (savedInstanceState == null) {
// check if we should directly show a person
int personTmdbId = getIntent().getIntExtra(PersonFragment.InitBundle.PERSON_TMDB_ID, -1);
if (personTmdbId != -1) {
showPerson(null, personTmdbId);
// if this is not a dual pane layout, remove ourselves from back stack
if (!mTwoPane) {
finish();
return;
}
}
PeopleFragment f = new PeopleFragment();
f.setArguments(getIntent().getExtras());
// in two-pane mode, list items should be activated when touched
if (mTwoPane) {
f.setActivateOnItemClick(true);
}
getSupportFragmentManager().beginTransaction()
.add(R.id.containerPeople, f, "people-list")
.commit();
}
}
private void setupActionBar() {
final ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
PeopleType peopleType = PeopleType.valueOf(
getIntent().getStringExtra(InitBundle.PEOPLE_TYPE));
actionBar.setTitle(
peopleType == PeopleType.CAST ? R.string.movie_cast : R.string.movie_crew);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == android.R.id.home) {
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void showPerson(View view, int tmdbId) {
if (mTwoPane) {
// show inline
PersonFragment f = PersonFragment.newInstance(tmdbId);
getSupportFragmentManager().beginTransaction()
.replace(R.id.containerPeoplePerson, f)
.commit();
} else {
// start new activity
Intent i = new Intent(this, PersonActivity.class);
i.putExtra(PersonFragment.InitBundle.PERSON_TMDB_ID, tmdbId);
ActivityCompat.startActivity(this, i,
ActivityOptionsCompat
.makeScaleUpAnimation(view, 0, 0, view.getWidth(), view.getHeight())
.toBundle()
);
}
}
}
| Forgot null check when animating PersonActivity in.
| SeriesGuide/src/main/java/com/battlelancer/seriesguide/ui/PeopleActivity.java | Forgot null check when animating PersonActivity in. | |
Java | apache-2.0 | ccd9f6acbcabe67b56b811954183e57d5304db49 | 0 | apache/commons-digester,apache/commons-digester,mohanaraosv/commons-digester,callMeDimit/commons-digester,apache/commons-digester,callMeDimit/commons-digester,mohanaraosv/commons-digester,mohanaraosv/commons-digester,callMeDimit/commons-digester | package org.apache.commons.digester3.plugins;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/**
* Thrown when an error occurs due to the way the calling application uses the plugins module. Because the pre-existing
* Digester API doesn't provide any option for throwing checked exceptions at some points where Plugins can potentially
* fail, this exception extends RuntimeException so that it can "tunnel" through these points.
*
* @since 1.6
*/
public class PluginConfigurationException
extends RuntimeException
{
private static final long serialVersionUID = 1L;
/**
* Constructs a new exception with the specified cause.
*
* @param cause underlying exception that caused this to be thrown
*/
public PluginConfigurationException( Throwable cause )
{
super( cause );
}
/**
* Constructs a new exception with the specified detail message.
*
* @param msg describes the reason this exception is being thrown.
*/
public PluginConfigurationException( String msg )
{
super( msg );
}
/**
* Constructs a new exception with the specified detail message and cause.
*
* @param msg describes the reason this exception is being thrown.
* @param cause underlying exception that caused this to be thrown
*/
public PluginConfigurationException( String msg, Throwable cause )
{
super( msg, cause );
}
}
| src/main/java/org/apache/commons/digester3/plugins/PluginConfigurationException.java | package org.apache.commons.digester3.plugins;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/**
* Thrown when an error occurs due to the way the calling application uses the plugins module. Because the pre-existing
* Digester API doesn't provide any option for throwing checked exceptions at some points where Plugins can potentially
* fail, this exception extends RuntimeException so that it can "tunnel" through these points.
*
* @since 1.6
*/
public class PluginConfigurationException
extends RuntimeException
{
private static final long serialVersionUID = 1L;
private Throwable cause = null;
/**
* @param cause underlying exception that caused this to be thrown
*/
public PluginConfigurationException( Throwable cause )
{
this( cause.getMessage() );
this.cause = cause;
}
/**
* @param msg describes the reason this exception is being thrown.
*/
public PluginConfigurationException( String msg )
{
super( msg );
}
/**
* @param msg describes the reason this exception is being thrown.
* @param cause underlying exception that caused this to be thrown
*/
public PluginConfigurationException( String msg, Throwable cause )
{
this( msg );
this.cause = cause;
}
/**
* Return the cause of this exception (if any) as specified in the exception constructor.
*
* @since 1.8
*/
@Override
public Throwable getCause()
{
return cause;
}
}
| same as for PluginAssertionFailure, no needs to store the cause, reused Exception default behavior
added missing descriptions on javadoc
git-svn-id: c3d1f7498fb08a2885afe49e111c402c6cd8f5f6@1129344 13f79535-47bb-0310-9956-ffa450edef68
| src/main/java/org/apache/commons/digester3/plugins/PluginConfigurationException.java | same as for PluginAssertionFailure, no needs to store the cause, reused Exception default behavior added missing descriptions on javadoc | |
Java | apache-2.0 | 831a44ab1f079bc7b7362b63efd65805e333a36d | 0 | Esri/arcgis-runtime-samples-java | /*
* Copyright 2016 Esri.
*
* 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.esri.samples.na.closest_facility;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import javafx.application.Application;
import javafx.geometry.Point2D;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.SpatialReference;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.Viewpoint;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.PictureMarkerSymbol;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;
import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol;
import com.esri.arcgisruntime.tasks.networkanalysis.ClosestFacilityParameters;
import com.esri.arcgisruntime.tasks.networkanalysis.ClosestFacilityResult;
import com.esri.arcgisruntime.tasks.networkanalysis.ClosestFacilityRoute;
import com.esri.arcgisruntime.tasks.networkanalysis.ClosestFacilityTask;
import com.esri.arcgisruntime.tasks.networkanalysis.Facility;
import com.esri.arcgisruntime.tasks.networkanalysis.Incident;
public class ClosestFacilitySample extends Application {
// black cross were user clicked
private Point incidentPoint;
private GraphicsOverlay graphicsOverlay;
// holds locations of hospitals around San Diego
private List<Facility> facilities;
private MapView mapView;
// solves task to find closest route between an incident and a facility
private ClosestFacilityTask task;
// parameters needed to solve for route
private ClosestFacilityParameters facilityParameters;
// used to display route between incident and facility to mapview
private SimpleLineSymbol routeSymbol;
// same spatial reference of the map
private SpatialReference spatialReference = SpatialReferences.getWebMercator();
@Override
public void start(Stage stage) throws Exception {
// pane will hold mapview to be displayed on application
StackPane stackPane = new StackPane();
Scene scene = new Scene(stackPane);
// set title, size, and add scene to stage
stage.setTitle("Closest Facility Sample");
stage.setWidth(800);
stage.setHeight(700);
stage.setScene(scene);
stage.show();
try {
// create a map with streets basemap and add to view
ArcGISMap map = new ArcGISMap(Basemap.createStreets());
mapView = new MapView();
mapView.setMap(map);
// add the mapview to stack pane
stackPane.getChildren().addAll(mapView);
// set view to be over San Diego
mapView.setViewpoint(new Viewpoint(32.727, -117.1750, 40000));
graphicsOverlay = new GraphicsOverlay();
createFacilitiesAndGraphics();
// to load graphics faster, add graphics overlay to view once all graphics are in graphics overlay
mapView.getGraphicsOverlays().add(graphicsOverlay);
// task to find the closest route between an incident and a facility
final String sanDiegoRegion =
"http://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/ClosestFacility";
task = new ClosestFacilityTask(sanDiegoRegion);
task.addDoneLoadingListener(() -> {
try {
facilityParameters = task.createDefaultParametersAsync().get();
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
});
task.loadAsync();
// symbols that display incident(black cross) and route(blue line) to view
SimpleMarkerSymbol incidentSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CROSS, 0xFF000000, 20);
routeSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFF0000FF, 2.0f);
// place incident were user clicks and display route to closest facility
mapView.setOnMouseClicked(e -> {
// check that the primary mouse button was clicked
if (e.getButton() == MouseButton.PRIMARY && e.isStillSincePress()) {
// show incident to the mapview
Point mapPoint = mapView.screenToLocation(new Point2D(e.getX(), e.getY()));
incidentPoint = new Point(mapPoint.getX(), mapPoint.getY(), spatialReference);
Graphic graphic = new Graphic(incidentPoint, incidentSymbol);
graphicsOverlay.getGraphics().add(graphic);
populateParametersAndSolveRoute();
}
});
} catch (Exception e) {
// on any error, display the stack trace.
e.printStackTrace();
}
}
/**
* Creates facilities around the San Diego region.
* <p>
* Facilities are created using point geometry which is then used to make graphics for the graphics overlay.
*/
private void createFacilitiesAndGraphics() {
// List of facilities to be placed around San Diego area
facilities = Arrays.asList(
new Facility(new Point(-1.3042129900625112E7, 3860127.9479775648, spatialReference)),
new Facility(new Point(-1.3042193400557665E7, 3862448.873041752, spatialReference)),
new Facility(new Point(-1.3046882875518233E7, 3862704.9896770366, spatialReference)),
new Facility(new Point(-1.3040539754780494E7, 3862924.5938606677, spatialReference)),
new Facility(new Point(-1.3042571225655518E7, 3858981.773018156, spatialReference)),
new Facility(new Point(-1.3039784633928463E7, 3856692.5980474586, spatialReference)),
new Facility(new Point(-1.3049023883956768E7, 3861993.789732541, spatialReference)));
// image for displaying facility
String facilityUrl = "http://static.arcgis.com/images/Symbols/SafetyHealth/Hospital.png";
PictureMarkerSymbol facilitySymbol = new PictureMarkerSymbol(facilityUrl);
facilitySymbol.setHeight(30);
facilitySymbol.setWidth(30);
// for each facility, create a graphic and add to graphics overlay
facilities.stream().map(f -> new Graphic(f.getGeometry(), facilitySymbol))
.collect(Collectors.toCollection(() -> graphicsOverlay.getGraphics()));
}
/**
* Adds facilities(hospitals) and user's incident(black cross) to closest facility parameters which will be used to
* display the closest route from the user's incident to its' nearest facility.
*/
private void populateParametersAndSolveRoute() {
// clear any parameters that were set
facilityParameters.clearFacilities();
facilityParameters.clearIncidents();
// set new parameters to find route
facilityParameters.setFacilities(facilities);
facilityParameters.setIncidents(Arrays.asList(new Incident(incidentPoint)));
// find closest route using parameters from above
ListenableFuture<ClosestFacilityResult> result = task.solveClosestFacilityAsync(facilityParameters);
result.addDoneListener(() -> {
try {
ClosestFacilityResult facilityResult = result.get();
// a list of closest facilities based on users incident
List<Integer> rankedList = facilityResult.getRankedFacilities(0);
// get the index of the closest facility to incident
int closestFacility = rankedList.get(0);
// get route from incident to closest facility and display to mapview
ClosestFacilityRoute route = facilityResult.getRoute(closestFacility, 0);
graphicsOverlay.getGraphics().add(new Graphic(route.getRouteGeometry(), routeSymbol));
} catch (ExecutionException e) {
if (e.getMessage().contains("Unable to complete operation")) {
Alert dialog = new Alert(AlertType.WARNING);
dialog.setHeaderText(null);
dialog.setTitle("Route Error");
dialog.setContentText("Incident not within San Diego area!");
dialog.showAndWait();
} else {
e.printStackTrace();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
/**
* Stops and releases all resources used in application.
*/
@Override
public void stop() throws Exception {
if (mapView != null) {
mapView.dispose();
}
}
/**
* Opens and runs application.
*
* @param args arguments passed to this application
*/
public static void main(String[] args) {
Application.launch(args);
}
}
| src/main/java/com/esri/samples/na/closest_facility/ClosestFacilitySample.java | /*
* Copyright 2016 Esri.
*
* 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.esri.samples.na.closest_facility;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import javafx.application.Application;
import javafx.geometry.Point2D;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.SpatialReference;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.Viewpoint;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.PictureMarkerSymbol;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;
import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol;
import com.esri.arcgisruntime.tasks.networkanalysis.ClosestFacilityParameters;
import com.esri.arcgisruntime.tasks.networkanalysis.ClosestFacilityResult;
import com.esri.arcgisruntime.tasks.networkanalysis.ClosestFacilityRoute;
import com.esri.arcgisruntime.tasks.networkanalysis.ClosestFacilityTask;
import com.esri.arcgisruntime.tasks.networkanalysis.Facility;
import com.esri.arcgisruntime.tasks.networkanalysis.Incident;
public class ClosestFacilitySample extends Application {
// black cross were user clicked
private Point incidentPoint;
private GraphicsOverlay graphicsOverlay;
// holds locations of hospitals around San Diego
private List<Facility> facilities;
private MapView mapView;
// solves task to find closest route between a incident and a facility
private ClosestFacilityTask task;
// parameters needed to slove for route
private ClosestFacilityParameters facilityParameters;
// used to display route between incident and facility to mapview
private SimpleLineSymbol routeSymbol;
// same spatial reference of the map
private SpatialReference spatialReference = SpatialReferences.getWebMercator();
@Override
public void start(Stage stage) throws Exception {
// pane will hold mapview to be displayed on application
StackPane stackPane = new StackPane();
Scene scene = new Scene(stackPane);
// set title, size, and add scene to stage
stage.setTitle("Closest Facility Sample");
stage.setWidth(800);
stage.setHeight(700);
stage.setScene(scene);
stage.show();
try {
// create a map with streets basemap and add to view
ArcGISMap map = new ArcGISMap(Basemap.createStreets());
mapView = new MapView();
mapView.setMap(map);
// add the mapview to stack pane
stackPane.getChildren().addAll(mapView);
// set view to be over San Diego
mapView.setViewpoint(new Viewpoint(32.727, -117.1750, 40000));
graphicsOverlay = new GraphicsOverlay();
createFacilitiesAndGraphics();
// to load graphics faster, add graphics overlay to view once all graphics are in graphics overlay
mapView.getGraphicsOverlays().add(graphicsOverlay);
// task to find the closest route between an incident and a facility
final String sanDiegoRegion =
"http://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/ClosestFacility";
task = new ClosestFacilityTask(sanDiegoRegion);
task.loadAsync();
// get default parameters used to find closest facility to incident
ListenableFuture<ClosestFacilityParameters> parameters = task.createDefaultParametersAsync();
parameters.addDoneListener(() -> {
try {
facilityParameters = parameters.get();
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
});
// symbols that display incident(black cross) and route(blue line) to view
SimpleMarkerSymbol incidentSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CROSS, 0xFF000000, 20);
routeSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFF0000FF, 2.0f);
// place incident were user clicks and display route to closest facility
mapView.setOnMouseClicked(e -> {
// check that the primary mouse button was clicked
if (e.getButton() == MouseButton.PRIMARY && e.isStillSincePress()) {
// show incident to the mapview
Point mapPoint = mapView.screenToLocation(new Point2D(e.getX(), e.getY()));
incidentPoint = new Point(mapPoint.getX(), mapPoint.getY(), spatialReference);
Graphic graphic = new Graphic(incidentPoint, incidentSymbol);
graphicsOverlay.getGraphics().add(graphic);
populateParametersAndSolveRoute();
}
});
} catch (Exception e) {
// on any error, display the stack trace.
e.printStackTrace();
}
}
/**
* Creates facilities around the San Diego region.
* <p>
* Facilities are created using point geometry which is then used to make graphics for the graphics overlay.
*/
private void createFacilitiesAndGraphics() {
// List of facilities to be placed around San Diego area
facilities = Arrays.asList(
new Facility(new Point(-1.3042129900625112E7, 3860127.9479775648, spatialReference)),
new Facility(new Point(-1.3042193400557665E7, 3862448.873041752, spatialReference)),
new Facility(new Point(-1.3046882875518233E7, 3862704.9896770366, spatialReference)),
new Facility(new Point(-1.3040539754780494E7, 3862924.5938606677, spatialReference)),
new Facility(new Point(-1.3042571225655518E7, 3858981.773018156, spatialReference)),
new Facility(new Point(-1.3039784633928463E7, 3856692.5980474586, spatialReference)),
new Facility(new Point(-1.3049023883956768E7, 3861993.789732541, spatialReference)));
// image for displaying facility
String facilityUrl = "http://static.arcgis.com/images/Symbols/SafetyHealth/Hospital.png";
PictureMarkerSymbol facilitySymbol = new PictureMarkerSymbol(facilityUrl);
facilitySymbol.setHeight(30);
facilitySymbol.setWidth(30);
// for each facility, create a graphic and add to graphics overlay
facilities.stream().map(f -> new Graphic(f.getGeometry(), facilitySymbol))
.collect(Collectors.toCollection(() -> graphicsOverlay.getGraphics()));
}
/**
* Adds facilities(hospitals) and user's incident(black cross) to closest facility parameters which will be used to
* display the closest route from the user's incident to its' nearest facility.
*/
private void populateParametersAndSolveRoute() {
// clear any parameters that were set
facilityParameters.getFacilities().clear();
facilityParameters.getIncidents().clear();
// set new parameters to find route
facilityParameters.getFacilities().addAll(facilities);
facilityParameters.getIncidents().add(new Incident(incidentPoint));
// find closest route using parameters from above
ListenableFuture<ClosestFacilityResult> result = task.solveClosestFacilityAsync(facilityParameters);
result.addDoneListener(() -> {
try {
ClosestFacilityResult facilityResult = result.get();
// a list of closest facilities based on users incident
List<Integer> rankedList = facilityResult.getRankedFacilities(0);
// get the index of the closest facility to incident
int closestFacility = rankedList.get(0);
// get route from incident to closest facility and display to mapview
ClosestFacilityRoute route = facilityResult.getRoute(closestFacility, 0);
graphicsOverlay.getGraphics().add(new Graphic(route.getRouteGeometry(), routeSymbol));
} catch (ExecutionException e) {
if (e.getMessage().contains("Unable to complete operation")) {
Alert dialog = new Alert(AlertType.WARNING);
dialog.setHeaderText(null);
dialog.setTitle("Route Error");
dialog.setContentText("Incident not within San Diego area!");
dialog.showAndWait();
} else {
e.printStackTrace();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
/**
* Stops and releases all resources used in application.
*/
@Override
public void stop() throws Exception {
if (mapView != null) {
mapView.dispose();
}
}
/**
* Opens and runs application.
*
* @param args arguments passed to this application
*/
public static void main(String[] args) {
Application.launch(args);
}
}
| Done updating closest facility sample | src/main/java/com/esri/samples/na/closest_facility/ClosestFacilitySample.java | Done updating closest facility sample | |
Java | apache-2.0 | 07ca3304ba8f689962ac73bd6220632784eb229d | 0 | GerritCodeReview/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,WANdisco/gerrit,gerrit-review/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,gerrit-review/gerrit,gerrit-review/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,gerrit-review/gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,gerrit-review/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,gerrit-review/gerrit,gerrit-review/gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit | // Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.group;
import com.google.common.base.Strings;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.extensions.restapi.DefaultInput;
import com.google.gerrit.extensions.restapi.MethodNotAllowedException;
import com.google.gerrit.extensions.restapi.ResourceNotFoundException;
import com.google.gerrit.extensions.restapi.Response;
import com.google.gerrit.extensions.restapi.RestModifyView;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.group.PutDescription.Input;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import java.io.IOException;
import java.util.Objects;
import java.util.Optional;
@Singleton
public class PutDescription implements RestModifyView<GroupResource, Input> {
public static class Input {
@DefaultInput public String description;
}
private final Provider<ReviewDb> db;
private final Provider<GroupsUpdate> groupsUpdateProvider;
@Inject
PutDescription(
Provider<ReviewDb> db, @UserInitiated Provider<GroupsUpdate> groupsUpdateProvider) {
this.db = db;
this.groupsUpdateProvider = groupsUpdateProvider;
}
@Override
public Response<String> apply(GroupResource resource, Input input)
throws AuthException, MethodNotAllowedException, ResourceNotFoundException, OrmException,
IOException {
if (input == null) {
input = new Input(); // Delete would set description to null.
}
AccountGroup accountGroup = resource.toAccountGroup();
if (accountGroup == null) {
throw new MethodNotAllowedException();
} else if (!resource.getControl().isOwner()) {
throw new AuthException("Not group owner");
}
String newDescription = Strings.emptyToNull(input.description);
if (!Objects.equals(accountGroup.getDescription(), newDescription)) {
Optional<AccountGroup> updatedGroup =
groupsUpdateProvider
.get()
.updateGroup(
db.get(), resource.getGroupUUID(), group -> group.setDescription(newDescription));
if (!updatedGroup.isPresent()) {
throw new ResourceNotFoundException();
}
}
return Strings.isNullOrEmpty(input.description)
? Response.<String>none()
: Response.ok(input.description);
}
}
| gerrit-server/src/main/java/com/google/gerrit/server/group/PutDescription.java | // Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.group;
import com.google.common.base.Strings;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.extensions.restapi.DefaultInput;
import com.google.gerrit.extensions.restapi.MethodNotAllowedException;
import com.google.gerrit.extensions.restapi.ResourceNotFoundException;
import com.google.gerrit.extensions.restapi.Response;
import com.google.gerrit.extensions.restapi.RestModifyView;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.account.GroupCache;
import com.google.gerrit.server.group.PutDescription.Input;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import java.io.IOException;
import java.util.Collections;
@Singleton
public class PutDescription implements RestModifyView<GroupResource, Input> {
public static class Input {
@DefaultInput public String description;
}
private final GroupCache groupCache;
private final Provider<ReviewDb> db;
@Inject
PutDescription(GroupCache groupCache, Provider<ReviewDb> db) {
this.groupCache = groupCache;
this.db = db;
}
@Override
public Response<String> apply(GroupResource resource, Input input)
throws AuthException, MethodNotAllowedException, ResourceNotFoundException, OrmException,
IOException {
if (input == null) {
input = new Input(); // Delete would set description to null.
}
if (resource.toAccountGroup() == null) {
throw new MethodNotAllowedException();
} else if (!resource.getControl().isOwner()) {
throw new AuthException("Not group owner");
}
AccountGroup group = db.get().accountGroups().get(resource.toAccountGroup().getId());
if (group == null) {
throw new ResourceNotFoundException();
}
group.setDescription(Strings.emptyToNull(input.description));
db.get().accountGroups().update(Collections.singleton(group));
groupCache.evict(group);
return Strings.isNullOrEmpty(input.description)
? Response.<String>none()
: Response.ok(input.description);
}
}
| Remove access of groups related db tables from PutDescription
Change-Id: If59145f875c1ee1efa7614e11763716d14e61172
| gerrit-server/src/main/java/com/google/gerrit/server/group/PutDescription.java | Remove access of groups related db tables from PutDescription | |
Java | apache-2.0 | e895fcb104fe51a894fd969aad49690a8a50880b | 0 | HubSpot/Singularity,hs-jenkins-bot/Singularity,hs-jenkins-bot/Singularity,HubSpot/Singularity,hs-jenkins-bot/Singularity,hs-jenkins-bot/Singularity,HubSpot/Singularity,HubSpot/Singularity,HubSpot/Singularity,hs-jenkins-bot/Singularity | package com.hubspot.singularity.data;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.utils.ZKPaths;
import com.codahale.metrics.MetricRegistry;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.inject.Inject;
import com.hubspot.singularity.config.SingularityConfiguration;
public class NotificationsManager extends CuratorManager {
private static final String NOTIFICATIONS_ROOT = "/notifications";
private static final String BLACKLIST_ROOT = NOTIFICATIONS_ROOT + "/blacklist";
LoadingCache<String, List<String>> cache;
@Inject
public NotificationsManager(CuratorFramework curator, SingularityConfiguration configuration, MetricRegistry metricRegistry) {
super(curator, configuration, metricRegistry);
cache = CacheBuilder.newBuilder()
.expireAfterWrite(5, TimeUnit.MINUTES)
.build(
new CacheLoader<String, List<String>>() {
@Override public List<String> load(String key) throws Exception {
return getChildren(key);
}
}
);
}
public void addToBlacklist(String email) {
create(getEmailPath(email));
cache.invalidate(BLACKLIST_ROOT);
}
public void removeFromBlacklist(String email) {
delete(getEmailPath(email));
cache.invalidate(BLACKLIST_ROOT);
}
public List<String> getBlacklist() {
return cache.getUnchecked(BLACKLIST_ROOT);
}
private String getEmailPath(String email) {
return ZKPaths.makePath(BLACKLIST_ROOT, email);
}
}
| SingularityService/src/main/java/com/hubspot/singularity/data/NotificationsManager.java | package com.hubspot.singularity.data;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.utils.ZKPaths;
import org.jetbrains.annotations.NotNull;
import com.codahale.metrics.MetricRegistry;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.inject.Inject;
import com.hubspot.singularity.config.SingularityConfiguration;
public class NotificationsManager extends CuratorManager {
private static final String NOTIFICATIONS_ROOT = "/notifications";
private static final String BLACKLIST_ROOT = NOTIFICATIONS_ROOT + "/blacklist";
LoadingCache<String, List<String>> cache;
@Inject
public NotificationsManager(CuratorFramework curator, SingularityConfiguration configuration, MetricRegistry metricRegistry) {
super(curator, configuration, metricRegistry);
cache = CacheBuilder.newBuilder()
.expireAfterWrite(5, TimeUnit.MINUTES)
.build(
new CacheLoader<String, List<String>>() {
@Override public List<String> load(String key) throws Exception {
return getChildren(key);
}
}
);
}
public void addToBlacklist(String email) {
create(getEmailPath(email));
cache.invalidate(BLACKLIST_ROOT);
}
public void removeFromBlacklist(String email) {
delete(getEmailPath(email));
cache.invalidate(BLACKLIST_ROOT);
}
public List<String> getBlacklist() {
return cache.getUnchecked(BLACKLIST_ROOT);
}
@NotNull private String getEmailPath(String email) {
return ZKPaths.makePath(BLACKLIST_ROOT, email);
}
}
| Fix build
| SingularityService/src/main/java/com/hubspot/singularity/data/NotificationsManager.java | Fix build | |
Java | apache-2.0 | 668f3122750bb7c7641e71aee86048c7551c470d | 0 | miviclin/droidengine2d | package com.miviclin.droidengine2d;
import android.annotation.TargetApi;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import com.miviclin.droidengine2d.graphics.GLView;
/**
* EngineActivity manages the life cycle of the Engine.
*
* @author Miguel Vicente Linares
*
*/
public abstract class EngineActivity extends FragmentActivity {
private Engine engine;
private Game game;
private boolean prepared;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setWindowFlags();
setContentView(getContentViewId());
final GLView glView = (GLView) findViewById(getGLViewId());
engine = createEngine(glView);
game = engine.getGame();
engine.startGame();
// GLView.getWidth() and GLView.getHeight() return 0 before the view is rendered on screen for the first time,
// so we have to wait until the view is rendered for the first time before initializing the Engine
glView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@SuppressWarnings("deprecation")
@Override
public void onGlobalLayout() {
if (getResources().getConfiguration().orientation != getOrientation()) {
return;
}
// Ensure that game initialization is run only once
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
glView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
glView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
if (!prepared) {
prepared = true;
game.prepare();
}
}
});
}
@Override
public void onPause() {
super.onPause();
if (engine != null) {
engine.onPause();
}
}
@Override
public void onResume() {
super.onResume();
if (engine != null) {
engine.onResume();
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (engine != null) {
engine.onDestroy();
}
}
@Override
public void onBackPressed() {
if (engine != null) {
engine.onBackPressed();
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (engine != null) {
onConfigurationChanged();
}
}
/**
* This method is called from {@link #onConfigurationChanged(Configuration)} if the Engine has been initialized.
*/
public void onConfigurationChanged() {
setContentView(getContentViewId());
engine.setGLView((GLView) findViewById(getGLViewId()));
}
/**
* Sets Window flags.<br>
* This method is called from {@link EngineActivity#onCreate(Bundle)}
*/
public void setWindowFlags() {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
/**
* Returns the Engine.
*
* @return Engine
*/
protected Engine getEngine() {
return engine;
}
/**
* Returns the Game.
*
* @return Game
*/
protected Game getGame() {
return game;
}
/**
* Creates an Engine and returns it.<br>
* The Engine object returned by this method is the Engine that will be managed by this Activity.<br>
* This method is called from {@link EngineActivity#onCreate(Bundle)}
*
* @param glView GLView used to render the game
* @return Engine
*/
public abstract Engine createEngine(GLView glView);
/**
* Returns the content view ID.<br>
* This method must return the ID of the layout used for this activity.
*
* @return Content View ID
*/
public abstract int getContentViewId();
/**
* Returns the ID of the GLView (defined in the layout xml file) where the game will be rendered.
*
* @return GLView ID
*/
public abstract int getGLViewId();
/**
* Returns the orientation of the activity.<br>
* This method must return the same orientation defined in AndroidManifest.xml for this activity.
*
* @return {@link Configuration#ORIENTATION_LANDSCAPE} or {@link Configuration#ORIENTATION_PORTRAIT}
*/
public abstract int getOrientation();
}
| src/com/miviclin/droidengine2d/EngineActivity.java | package com.miviclin.droidengine2d;
import android.annotation.TargetApi;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import com.miviclin.droidengine2d.graphics.GLView;
/**
* EngineActivity manages the life cycle of the Engine.
*
* @author Miguel Vicente Linares
*
*/
public abstract class EngineActivity extends FragmentActivity {
private Engine engine;
private Game game;
private boolean prepared;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setWindowFlags();
setContentView(getContentViewID());
final GLView glView = (GLView) findViewById(getGLViewID());
engine = createEngine(glView);
game = engine.getGame();
engine.startGame();
// GLView.getWidth() and GLView.getHeight() return 0 before the view is rendered on screen for the first time,
// so we have to wait until the view is rendered for the first time before initializing the Engine
glView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@SuppressWarnings("deprecation")
@Override
public void onGlobalLayout() {
if (getResources().getConfiguration().orientation != getOrientation()) {
return;
}
// Ensure that game initialization is run only once
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
glView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
glView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
if (!prepared) {
prepared = true;
game.prepare();
}
}
});
}
@Override
public void onPause() {
super.onPause();
if (engine != null) {
engine.onPause();
}
}
@Override
public void onResume() {
super.onResume();
if (engine != null) {
engine.onResume();
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (engine != null) {
engine.onDestroy();
}
}
@Override
public void onBackPressed() {
if (engine != null) {
engine.onBackPressed();
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (engine != null) {
onConfigurationChanged();
}
}
/**
* This method is called from {@link #onConfigurationChanged(Configuration)} if the Engine has been initialized.
*/
public void onConfigurationChanged() {
setContentView(getContentViewID());
engine.setGLView((GLView) findViewById(getGLViewID()));
}
/**
* Sets Window flags.<br>
* This method is called from {@link EngineActivity#onCreate(Bundle)}
*/
public void setWindowFlags() {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
/**
* Returns the Engine.
*
* @return Engine
*/
protected Engine getEngine() {
return engine;
}
/**
* Returns the Game.
*
* @return Game
*/
protected Game getGame() {
return game;
}
/**
* Creates an Engine and returns it.<br>
* The Engine object returned by this method is the Engine that will be managed by this Activity.<br>
* This method is called from {@link EngineActivity#onCreate(Bundle)}
*
* @param glView GLView used to render the game
* @return Engine
*/
public abstract Engine createEngine(GLView glView);
/**
* Returns the content view ID.<br>
* This method must return the ID of the layout used for this activity.
*
* @return Content View ID
*/
public abstract int getContentViewID();
/**
* Returns the ID of the GLView (defined in the layout xml file) where the game will be rendered.
*
* @return GLView ID
*/
public abstract int getGLViewID();
/**
* Returns the orientation of the activity.<br>
* This method must return the same orientation defined in AndroidManifest.xml for this activity.
*
* @return {@link Configuration#ORIENTATION_LANDSCAPE} or {@link Configuration#ORIENTATION_PORTRAIT}
*/
public abstract int getOrientation();
}
| Replace ID with Id in EngineActivity to keep naming conventions consistent
| src/com/miviclin/droidengine2d/EngineActivity.java | Replace ID with Id in EngineActivity to keep naming conventions consistent | |
Java | apache-2.0 | 69edae982caa94decc87d4d7a2132c0acea5a878 | 0 | erdemolkun/instant-rates | package dynoapps.exchange_rates.provider;
import android.os.Handler;
import android.os.Looper;
import java.util.concurrent.atomic.AtomicBoolean;
import dynoapps.exchange_rates.time.TimeIntervalManager;
/**
* Created by erdemmac on 25/11/2016.
* todo add is enabled state
*/
public abstract class BasePoolingDataProvider<T> implements IPollingSource, Runnable {
private static final int NEXT_FETCH_ON_ERROR = 4000;
private SourceCallback<T> callback;
private int error_count = 0;
private int success_count = 0;
BasePoolingDataProvider(SourceCallback<T> callback) {
this.callback = callback;
}
private Handler handler;
private Handler getHandler() {
if (handler == null) {
handler = new Handler(Looper.getMainLooper());
}
return handler;
}
private AtomicBoolean isWorking = new AtomicBoolean(false);
@Override
public void run() {
logDurationStart();
}
@Override
public void start() {
if (isWorking.get()) return;
getHandler().post(this);
isWorking.set(true);
}
void fetchAgain(boolean wasError) {
long interval_value = TimeIntervalManager.getIntervalInMiliseconds();
if (wasError) {
/**
* Calculate error interval in logarithmic.
* */
float ratio = (error_count / (float) (success_count <= 0 ? 1 : success_count));
interval_value = (int) (NEXT_FETCH_ON_ERROR + Math.log(ratio) * NEXT_FETCH_ON_ERROR);
}
isWorking.set(true);
getHandler().postDelayed(this, interval_value);
}
public void refreshForIntervals() {
getHandler().removeCallbacks(this);
if (isWorking.get()) {
getHandler().postDelayed(this, TimeIntervalManager.getIntervalInMiliseconds());
}
}
@Override
public void stop() {
getHandler().removeCallbacks(this);
cancel();
isWorking.set(false);
}
private long last_call_start_milis = -1;
private int average_duration = 0;
private void logDurationSuccess() {
if (last_call_start_milis < 0) return;
long current_milis = System.currentTimeMillis();
average_duration = (int)
(average_duration * success_count + (current_milis - last_call_start_milis)) / (success_count + 1);
}
private void logDurationStart() {
last_call_start_milis = System.currentTimeMillis();
}
void notifyValue(T value) {
logDurationSuccess();
success_count++;
if (!isWorking.get()) return;
if (callback != null) {
callback.onResult(value);
}
}
void notifyError() {
last_call_start_milis = -1;
error_count++;
if (callback != null) {
callback.onError();
}
}
}
| app/src/main/java/dynoapps/exchange_rates/provider/BasePoolingDataProvider.java | package dynoapps.exchange_rates.provider;
import android.os.Handler;
import android.os.Looper;
import java.util.concurrent.atomic.AtomicBoolean;
import dynoapps.exchange_rates.time.TimeIntervalManager;
/**
* Created by erdemmac on 25/11/2016.
*/
public abstract class BasePoolingDataProvider<T> implements IPollingSource, Runnable {
private static final int NEXT_FETCH_ON_ERROR = 4000;
private SourceCallback<T> callback;
private int error_count = 0;
private int success_count = 0;
BasePoolingDataProvider(SourceCallback<T> callback) {
this.callback = callback;
}
private Handler handler;
private Handler getHandler() {
if (handler == null) {
handler = new Handler(Looper.getMainLooper());
}
return handler;
}
private AtomicBoolean isWorking = new AtomicBoolean(false);
@Override
public void run() {
logDurationStart();
}
@Override
public void start() {
if (isWorking.get()) return;
getHandler().post(this);
isWorking.set(true);
}
void fetchAgain(boolean wasError) {
long interval_value = TimeIntervalManager.getIntervalInMiliseconds();
if (wasError) {
/**
* Calculate error interval in logarithmic.
* */
float ratio = (error_count / (float) (success_count <= 0 ? 1 : success_count));
interval_value = (int) (NEXT_FETCH_ON_ERROR + Math.log(ratio) * NEXT_FETCH_ON_ERROR);
}
getHandler().postDelayed(this, interval_value);
}
public void refreshForIntervals() {
getHandler().removeCallbacks(this);
getHandler().postDelayed(this, TimeIntervalManager.getIntervalInMiliseconds());
}
@Override
public void stop() {
getHandler().removeCallbacks(this);
cancel();
isWorking.set(false);
}
private long last_call_start_milis = -1;
private int average_duration = 0;
private void logDurationSuccess() {
if (last_call_start_milis < 0) return;
long current_milis = System.currentTimeMillis();
average_duration = (int)
(average_duration * success_count + (current_milis - last_call_start_milis)) / (success_count + 1);
}
private void logDurationStart() {
last_call_start_milis = System.currentTimeMillis();
}
void notifyValue(T value) {
logDurationSuccess();
success_count++;
if (!isWorking.get()) return;
if (callback != null) {
callback.onResult(value);
}
}
void notifyError() {
last_call_start_milis = -1;
error_count++;
if (callback != null) {
callback.onError();
}
}
}
| Fix multiple handler posted after interval update.
| app/src/main/java/dynoapps/exchange_rates/provider/BasePoolingDataProvider.java | Fix multiple handler posted after interval update. | |
Java | apache-2.0 | 64b31c5f04f81551b0df8a0caad5a29678eae082 | 0 | MariaKepa/WyszukiwaczDuplikatow | package com.zaliczenie.projekt;
import org.junit.Test;
import java.io.File;
import java.net.URL;
import java.util.List;
import static org.junit.Assert.*;
/**
* Created by mk on 2016-02-02.
*/
public class ImageDuplicateFinderTest {
URL pathToResources = ImageDuplicateCheckerTest.class.getClassLoader().getResource("images/");
ImageDuplicateFinder duplicateFinder = new ImageDuplicateFinder(new MockImageDuplicateChecker());
@Test
public void testGetAllFiles() throws Exception {
List<File> files = duplicateFinder.GetAllFiles(new File(pathToResources.toURI()));
assertEquals(13, files.size());
}
@Test
public void testFindDuplicates_for_3_koalas() throws Exception {
List<File> files = duplicateFinder.findDuplicates(new File(pathToResources.toURI() + "/Koala.jpg"), new File(pathToResources.toURI()));
assertEquals(3, files.size());
}
@Test
public void testFindDuplicates_for_2_chryzantenium() throws Exception {
List<File> files = duplicateFinder.findDuplicates(new File(pathToResources.toURI() + "/Chrysanthemum.jpg"), new File(pathToResources.toURI()));
assertEquals(2, files.size());
}
}
| src/test/java/com/zaliczenie/projekt/ImageDuplicateFinderTest.java | package com.zaliczenie.projekt;a
import org.junit.Test;
import java.io.File;
import java.net.URL;
import java.util.List;
import static org.junit.Assert.*;
/**
* Created by mk on 2016-02-02.
*/
public class ImageDuplicateFinderTest {
URL pathToResources = ImageDuplicateCheckerTest.class.getClassLoader().getResource("images/");
ImageDuplicateFinder duplicateFinder = new ImageDuplicateFinder(new MockImageDuplicateChecker());
@Test
public void testGetAllFiles() throws Exception {
List<File> files = duplicateFinder.GetAllFiles(new File(pathToResources.toURI()));
assertEquals(13, files.size());
}
@Test
public void testFindDuplicates_for_3_koalas() throws Exception {
List<File> files = duplicateFinder.findDuplicates(new File(pathToResources.toURI() + "/Koala.jpg"), new File(pathToResources.toURI()));
assertEquals(3, files.size());
}
@Test
public void testFindDuplicates_for_2_chryzantenium() throws Exception {
List<File> files = duplicateFinder.findDuplicates(new File(pathToResources.toURI() + "/Chrysanthemum.jpg"), new File(pathToResources.toURI()));
assertEquals(2, files.size());
}
}
| Update ImageDuplicateFinderTest.java | src/test/java/com/zaliczenie/projekt/ImageDuplicateFinderTest.java | Update ImageDuplicateFinderTest.java | |
Java | apache-2.0 | 92fdb51f942b350b5dd4f3aa3fdb00749f947ed0 | 0 | graphhopper/jsprit | /*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH licenses this file to you 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.graphhopper.jsprit.core.algorithm;
import com.graphhopper.jsprit.core.algorithm.recreate.listener.InsertionEndsListener;
import com.graphhopper.jsprit.core.problem.job.Job;
import com.graphhopper.jsprit.core.problem.solution.route.VehicleRoute;
import com.graphhopper.jsprit.core.problem.vehicle.VehicleFleetManager;
import java.util.Collection;
import java.util.Iterator;
public class RemoveEmptyVehicles implements InsertionEndsListener {
private VehicleFleetManager fleetManager;
public RemoveEmptyVehicles(VehicleFleetManager fleetManager) {
super();
this.fleetManager = fleetManager;
}
@Override
public String toString() {
return "[name=removeEmptyVehicles]";
}
@Override
public void informInsertionEnds(Collection<VehicleRoute> vehicleRoutes, Collection<Job> badJobs) {
for (Iterator<VehicleRoute> iterator = vehicleRoutes.iterator(); iterator.hasNext(); ) {
VehicleRoute route = iterator.next();
if (route.isEmpty()) {
fleetManager.unlock(route.getVehicle());
iterator.remove();
}
}
}
}
| jsprit-core/src/main/java/com/graphhopper/jsprit/core/algorithm/RemoveEmptyVehicles.java | /*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH licenses this file to you 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.graphhopper.jsprit.core.algorithm;
import com.graphhopper.jsprit.core.algorithm.recreate.listener.InsertionEndsListener;
import com.graphhopper.jsprit.core.problem.job.Job;
import com.graphhopper.jsprit.core.problem.solution.route.VehicleRoute;
import com.graphhopper.jsprit.core.problem.vehicle.VehicleFleetManager;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class RemoveEmptyVehicles implements InsertionEndsListener {
private VehicleFleetManager fleetManager;
public RemoveEmptyVehicles(VehicleFleetManager fleetManager) {
super();
this.fleetManager = fleetManager;
}
@Override
public String toString() {
return "[name=removeEmptyVehicles]";
}
@Override
public void informInsertionEnds(Collection<VehicleRoute> vehicleRoutes, Collection<Job> badJobs) {
List<VehicleRoute> routes = new ArrayList<>(vehicleRoutes);
for (VehicleRoute route : routes) {
if (route.isEmpty()) {
fleetManager.unlock(route.getVehicle());
vehicleRoutes.remove(route);
}
}
}
}
| fix #452
| jsprit-core/src/main/java/com/graphhopper/jsprit/core/algorithm/RemoveEmptyVehicles.java | fix #452 | |
Java | apache-2.0 | 9a851eb54b774c3c326aa5bf1223ab6d12d94646 | 0 | androidx/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,aosp-mirror/platform_frameworks_support,aosp-mirror/platform_frameworks_support,androidx/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,aosp-mirror/platform_frameworks_support,aosp-mirror/platform_frameworks_support,androidx/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.slidingpanelayout.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.accessibility.AccessibilityEvent;
import androidx.annotation.ColorInt;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.Px;
import androidx.core.content.ContextCompat;
import androidx.core.view.AccessibilityDelegateCompat;
import androidx.core.view.ViewCompat;
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
import androidx.customview.view.AbsSavedState;
import androidx.customview.widget.ViewDragHelper;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
/**
* SlidingPaneLayout provides a horizontal, multi-pane layout for use at the top level
* of a UI. A left (or first) pane is treated as a content list or browser, subordinate to a
* primary detail view for displaying content.
*
* <p>Child views may overlap if their combined width exceeds the available width
* in the SlidingPaneLayout. When this occurs the user may slide the topmost view out of the way
* by dragging it, or by navigating in the direction of the overlapped view using a keyboard.
* If the content of the dragged child view is itself horizontally scrollable, the user may
* grab it by the very edge.</p>
*
* <p>Thanks to this sliding behavior, SlidingPaneLayout may be suitable for creating layouts
* that can smoothly adapt across many different screen sizes, expanding out fully on larger
* screens and collapsing on smaller screens.</p>
*
* <p>SlidingPaneLayout is distinct from a navigation drawer as described in the design
* guide and should not be used in the same scenarios. SlidingPaneLayout should be thought
* of only as a way to allow a two-pane layout normally used on larger screens to adapt to smaller
* screens in a natural way. The interaction patterns expressed by SlidingPaneLayout imply
* a physicality and direct information hierarchy between panes that does not necessarily exist
* in a scenario where a navigation drawer should be used instead.</p>
*
* <p>Appropriate uses of SlidingPaneLayout include pairings of panes such as a contact list and
* subordinate interactions with those contacts, or an email thread list with the content pane
* displaying the contents of the selected thread. Inappropriate uses of SlidingPaneLayout include
* switching between disparate functions of your app, such as jumping from a social stream view
* to a view of your personal profile - cases such as this should use the navigation drawer
* pattern instead. ({@link androidx.drawerlayout.widget.DrawerLayout DrawerLayout} implements this pattern.)</p>
*
* <p>Like {@link android.widget.LinearLayout LinearLayout}, SlidingPaneLayout supports
* the use of the layout parameter <code>layout_weight</code> on child views to determine
* how to divide leftover space after measurement is complete. It is only relevant for width.
* When views do not overlap weight behaves as it does in a LinearLayout.</p>
*
* <p>When views do overlap, weight on a slideable pane indicates that the pane should be
* sized to fill all available space in the closed state. Weight on a pane that becomes covered
* indicates that the pane should be sized to fill all available space except a small minimum strip
* that the user may use to grab the slideable view and pull it back over into a closed state.</p>
*/
public class SlidingPaneLayout extends ViewGroup {
private static final String TAG = "SlidingPaneLayout";
/**
* Default size of the overhang for a pane in the open state.
* At least this much of a sliding pane will remain visible.
* This indicates that there is more content available and provides
* a "physical" edge to grab to pull it closed.
*/
private static final int DEFAULT_OVERHANG_SIZE = 32; // dp;
/**
* If no fade color is given by default it will fade to 80% gray.
*/
private static final int DEFAULT_FADE_COLOR = 0xcccccccc;
/**
* The fade color used for the sliding panel. 0 = no fading.
*/
private int mSliderFadeColor = DEFAULT_FADE_COLOR;
/**
* Minimum velocity that will be detected as a fling
*/
private static final int MIN_FLING_VELOCITY = 400; // dips per second
/**
* The fade color used for the panel covered by the slider. 0 = no fading.
*/
private int mCoveredFadeColor;
/**
* Drawable used to draw the shadow between panes by default.
*/
private Drawable mShadowDrawableLeft;
/**
* Drawable used to draw the shadow between panes to support RTL (right to left language).
*/
private Drawable mShadowDrawableRight;
/**
* The size of the overhang in pixels.
* This is the minimum section of the sliding panel that will
* be visible in the open state to allow for a closing drag.
*/
private final int mOverhangSize;
/**
* True if a panel can slide with the current measurements
*/
private boolean mCanSlide;
/**
* The child view that can slide, if any.
*/
View mSlideableView;
/**
* How far the panel is offset from its closed position.
* range [0, 1] where 0 = closed, 1 = open.
*/
float mSlideOffset;
/**
* How far the non-sliding panel is parallaxed from its usual position when open.
* range [0, 1]
*/
private float mParallaxOffset;
/**
* How far in pixels the slideable panel may move.
*/
int mSlideRange;
/**
* A panel view is locked into internal scrolling or another condition that
* is preventing a drag.
*/
boolean mIsUnableToDrag;
/**
* Distance in pixels to parallax the fixed pane by when fully closed
*/
private int mParallaxBy;
private float mInitialMotionX;
private float mInitialMotionY;
private PanelSlideListener mPanelSlideListener;
final ViewDragHelper mDragHelper;
/**
* Stores whether or not the pane was open the last time it was slideable.
* If open/close operations are invoked this state is modified. Used by
* instance state save/restore.
*/
boolean mPreservedOpenState;
private boolean mFirstLayout = true;
private final Rect mTmpRect = new Rect();
final ArrayList<DisableLayerRunnable> mPostedRunnables = new ArrayList<>();
/**
* Listener for monitoring events about sliding panes.
*/
public interface PanelSlideListener {
/**
* Called when a sliding pane's position changes.
* @param panel The child view that was moved
* @param slideOffset The new offset of this sliding pane within its range, from 0-1
*/
void onPanelSlide(@NonNull View panel, float slideOffset);
/**
* Called when a sliding pane becomes slid completely open. The pane may or may not
* be interactive at this point depending on how much of the pane is visible.
* @param panel The child view that was slid to an open position, revealing other panes
*/
void onPanelOpened(@NonNull View panel);
/**
* Called when a sliding pane becomes slid completely closed. The pane is now guaranteed
* to be interactive. It may now obscure other views in the layout.
* @param panel The child view that was slid to a closed position
*/
void onPanelClosed(@NonNull View panel);
}
/**
* No-op stubs for {@link PanelSlideListener}. If you only want to implement a subset
* of the listener methods you can extend this instead of implement the full interface.
*/
public static class SimplePanelSlideListener implements PanelSlideListener {
@Override
public void onPanelSlide(View panel, float slideOffset) {
}
@Override
public void onPanelOpened(View panel) {
}
@Override
public void onPanelClosed(View panel) {
}
}
public SlidingPaneLayout(@NonNull Context context) {
this(context, null);
}
public SlidingPaneLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public SlidingPaneLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
final float density = context.getResources().getDisplayMetrics().density;
mOverhangSize = (int) (DEFAULT_OVERHANG_SIZE * density + 0.5f);
setWillNotDraw(false);
ViewCompat.setAccessibilityDelegate(this, new AccessibilityDelegate());
ViewCompat.setImportantForAccessibility(this, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES);
mDragHelper = ViewDragHelper.create(this, 0.5f, new DragHelperCallback());
mDragHelper.setMinVelocity(MIN_FLING_VELOCITY * density);
}
/**
* Set a distance to parallax the lower pane by when the upper pane is in its
* fully closed state. The lower pane will scroll between this position and
* its fully open state.
*
* @param parallaxBy Distance to parallax by in pixels
*/
public void setParallaxDistance(@Px int parallaxBy) {
mParallaxBy = parallaxBy;
requestLayout();
}
/**
* @return The distance the lower pane will parallax by when the upper pane is fully closed.
*
* @see #setParallaxDistance(int)
*/
@Px
public int getParallaxDistance() {
return mParallaxBy;
}
/**
* Set the color used to fade the sliding pane out when it is slid most of the way offscreen.
*
* @param color An ARGB-packed color value
*/
public void setSliderFadeColor(@ColorInt int color) {
mSliderFadeColor = color;
}
/**
* @return The ARGB-packed color value used to fade the sliding pane
*/
@ColorInt
public int getSliderFadeColor() {
return mSliderFadeColor;
}
/**
* Set the color used to fade the pane covered by the sliding pane out when the pane
* will become fully covered in the closed state.
*
* @param color An ARGB-packed color value
*/
public void setCoveredFadeColor(@ColorInt int color) {
mCoveredFadeColor = color;
}
/**
* @return The ARGB-packed color value used to fade the fixed pane
*/
@ColorInt
public int getCoveredFadeColor() {
return mCoveredFadeColor;
}
public void setPanelSlideListener(@Nullable PanelSlideListener listener) {
mPanelSlideListener = listener;
}
void dispatchOnPanelSlide(View panel) {
if (mPanelSlideListener != null) {
mPanelSlideListener.onPanelSlide(panel, mSlideOffset);
}
}
void dispatchOnPanelOpened(View panel) {
if (mPanelSlideListener != null) {
mPanelSlideListener.onPanelOpened(panel);
}
sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
}
void dispatchOnPanelClosed(View panel) {
if (mPanelSlideListener != null) {
mPanelSlideListener.onPanelClosed(panel);
}
sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
}
void updateObscuredViewsVisibility(View panel) {
final boolean isLayoutRtl = isLayoutRtlSupport();
final int startBound = isLayoutRtl ? (getWidth() - getPaddingRight()) : getPaddingLeft();
final int endBound = isLayoutRtl ? getPaddingLeft() : (getWidth() - getPaddingRight());
final int topBound = getPaddingTop();
final int bottomBound = getHeight() - getPaddingBottom();
final int left;
final int right;
final int top;
final int bottom;
if (panel != null && viewIsOpaque(panel)) {
left = panel.getLeft();
right = panel.getRight();
top = panel.getTop();
bottom = panel.getBottom();
} else {
left = right = top = bottom = 0;
}
for (int i = 0, childCount = getChildCount(); i < childCount; i++) {
final View child = getChildAt(i);
if (child == panel) {
// There are still more children above the panel but they won't be affected.
break;
} else if (child.getVisibility() == GONE) {
continue;
}
final int clampedChildLeft = Math.max(
(isLayoutRtl ? endBound : startBound), child.getLeft());
final int clampedChildTop = Math.max(topBound, child.getTop());
final int clampedChildRight = Math.min(
(isLayoutRtl ? startBound : endBound), child.getRight());
final int clampedChildBottom = Math.min(bottomBound, child.getBottom());
final int vis;
if (clampedChildLeft >= left && clampedChildTop >= top
&& clampedChildRight <= right && clampedChildBottom <= bottom) {
vis = INVISIBLE;
} else {
vis = VISIBLE;
}
child.setVisibility(vis);
}
}
void setAllChildrenVisible() {
for (int i = 0, childCount = getChildCount(); i < childCount; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == INVISIBLE) {
child.setVisibility(VISIBLE);
}
}
}
private static boolean viewIsOpaque(View v) {
if (v.isOpaque()) {
return true;
}
// View#isOpaque didn't take all valid opaque scrollbar modes into account
// before API 18 (JB-MR2). On newer devices rely solely on isOpaque above and return false
// here. On older devices, check the view's background drawable directly as a fallback.
if (Build.VERSION.SDK_INT >= 18) {
return false;
}
final Drawable bg = v.getBackground();
if (bg != null) {
return bg.getOpacity() == PixelFormat.OPAQUE;
}
return false;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mFirstLayout = true;
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mFirstLayout = true;
for (int i = 0, count = mPostedRunnables.size(); i < count; i++) {
final DisableLayerRunnable dlr = mPostedRunnables.get(i);
dlr.run();
}
mPostedRunnables.clear();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthMode != MeasureSpec.EXACTLY) {
if (isInEditMode()) {
// Don't crash the layout editor. Consume all of the space if specified
// or pick a magic number from thin air otherwise.
// TODO Better communication with tools of this bogus state.
// It will crash on a real device.
if (widthMode == MeasureSpec.AT_MOST) {
widthMode = MeasureSpec.EXACTLY;
} else if (widthMode == MeasureSpec.UNSPECIFIED) {
widthMode = MeasureSpec.EXACTLY;
widthSize = 300;
}
} else {
throw new IllegalStateException("Width must have an exact value or MATCH_PARENT");
}
} else if (heightMode == MeasureSpec.UNSPECIFIED) {
if (isInEditMode()) {
// Don't crash the layout editor. Pick a magic number from thin air instead.
// TODO Better communication with tools of this bogus state.
// It will crash on a real device.
if (heightMode == MeasureSpec.UNSPECIFIED) {
heightMode = MeasureSpec.AT_MOST;
heightSize = 300;
}
} else {
throw new IllegalStateException("Height must not be UNSPECIFIED");
}
}
int layoutHeight = 0;
int maxLayoutHeight = 0;
switch (heightMode) {
case MeasureSpec.EXACTLY:
layoutHeight = maxLayoutHeight = heightSize - getPaddingTop() - getPaddingBottom();
break;
case MeasureSpec.AT_MOST:
maxLayoutHeight = heightSize - getPaddingTop() - getPaddingBottom();
break;
}
float weightSum = 0;
boolean canSlide = false;
final int widthAvailable = widthSize - getPaddingLeft() - getPaddingRight();
int widthRemaining = widthAvailable;
final int childCount = getChildCount();
if (childCount > 2) {
Log.e(TAG, "onMeasure: More than two child views are not supported.");
}
// We'll find the current one below.
mSlideableView = null;
// First pass. Measure based on child LayoutParams width/height.
// Weight will incur a second pass.
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (child.getVisibility() == GONE) {
lp.dimWhenOffset = false;
continue;
}
if (lp.weight > 0) {
weightSum += lp.weight;
// If we have no width, weight is the only contributor to the final size.
// Measure this view on the weight pass only.
if (lp.width == 0) continue;
}
int childWidthSpec;
final int horizontalMargin = lp.leftMargin + lp.rightMargin;
if (lp.width == LayoutParams.WRAP_CONTENT) {
childWidthSpec = MeasureSpec.makeMeasureSpec(widthAvailable - horizontalMargin,
MeasureSpec.AT_MOST);
} else if (lp.width == LayoutParams.MATCH_PARENT) {
childWidthSpec = MeasureSpec.makeMeasureSpec(widthAvailable - horizontalMargin,
MeasureSpec.EXACTLY);
} else {
childWidthSpec = MeasureSpec.makeMeasureSpec(lp.width, MeasureSpec.EXACTLY);
}
int childHeightSpec;
if (lp.height == LayoutParams.WRAP_CONTENT) {
childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight, MeasureSpec.AT_MOST);
} else if (lp.height == LayoutParams.MATCH_PARENT) {
childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight, MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(lp.height, MeasureSpec.EXACTLY);
}
child.measure(childWidthSpec, childHeightSpec);
final int childWidth = child.getMeasuredWidth();
final int childHeight = child.getMeasuredHeight();
if (heightMode == MeasureSpec.AT_MOST && childHeight > layoutHeight) {
layoutHeight = Math.min(childHeight, maxLayoutHeight);
}
widthRemaining -= childWidth;
canSlide |= lp.slideable = widthRemaining < 0;
if (lp.slideable) {
mSlideableView = child;
}
}
// Resolve weight and make sure non-sliding panels are smaller than the full screen.
if (canSlide || weightSum > 0) {
final int fixedPanelWidthLimit = widthAvailable - mOverhangSize;
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (child.getVisibility() == GONE) {
continue;
}
final boolean skippedFirstPass = lp.width == 0 && lp.weight > 0;
final int measuredWidth = skippedFirstPass ? 0 : child.getMeasuredWidth();
if (canSlide && child != mSlideableView) {
if (lp.width < 0 && (measuredWidth > fixedPanelWidthLimit || lp.weight > 0)) {
// Fixed panels in a sliding configuration should
// be clamped to the fixed panel limit.
final int childHeightSpec;
if (skippedFirstPass) {
// Do initial height measurement if we skipped measuring this view
// the first time around.
if (lp.height == LayoutParams.WRAP_CONTENT) {
childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight,
MeasureSpec.AT_MOST);
} else if (lp.height == LayoutParams.MATCH_PARENT) {
childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight,
MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(lp.height,
MeasureSpec.EXACTLY);
}
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(
child.getMeasuredHeight(), MeasureSpec.EXACTLY);
}
final int childWidthSpec = MeasureSpec.makeMeasureSpec(
fixedPanelWidthLimit, MeasureSpec.EXACTLY);
child.measure(childWidthSpec, childHeightSpec);
}
} else if (lp.weight > 0) {
int childHeightSpec;
if (lp.width == 0) {
// This was skipped the first time; figure out a real height spec.
if (lp.height == LayoutParams.WRAP_CONTENT) {
childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight,
MeasureSpec.AT_MOST);
} else if (lp.height == LayoutParams.MATCH_PARENT) {
childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight,
MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(lp.height,
MeasureSpec.EXACTLY);
}
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(
child.getMeasuredHeight(), MeasureSpec.EXACTLY);
}
if (canSlide) {
// Consume available space
final int horizontalMargin = lp.leftMargin + lp.rightMargin;
final int newWidth = widthAvailable - horizontalMargin;
final int childWidthSpec = MeasureSpec.makeMeasureSpec(
newWidth, MeasureSpec.EXACTLY);
if (measuredWidth != newWidth) {
child.measure(childWidthSpec, childHeightSpec);
}
} else {
// Distribute the extra width proportionally similar to LinearLayout
final int widthToDistribute = Math.max(0, widthRemaining);
final int addedWidth = (int) (lp.weight * widthToDistribute / weightSum);
final int childWidthSpec = MeasureSpec.makeMeasureSpec(
measuredWidth + addedWidth, MeasureSpec.EXACTLY);
child.measure(childWidthSpec, childHeightSpec);
}
}
}
}
final int measuredWidth = widthSize;
final int measuredHeight = layoutHeight + getPaddingTop() + getPaddingBottom();
setMeasuredDimension(measuredWidth, measuredHeight);
mCanSlide = canSlide;
if (mDragHelper.getViewDragState() != ViewDragHelper.STATE_IDLE && !canSlide) {
// Cancel scrolling in progress, it's no longer relevant.
mDragHelper.abort();
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final boolean isLayoutRtl = isLayoutRtlSupport();
if (isLayoutRtl) {
mDragHelper.setEdgeTrackingEnabled(ViewDragHelper.EDGE_RIGHT);
} else {
mDragHelper.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT);
}
final int width = r - l;
final int paddingStart = isLayoutRtl ? getPaddingRight() : getPaddingLeft();
final int paddingEnd = isLayoutRtl ? getPaddingLeft() : getPaddingRight();
final int paddingTop = getPaddingTop();
final int childCount = getChildCount();
int xStart = paddingStart;
int nextXStart = xStart;
if (mFirstLayout) {
mSlideOffset = mCanSlide && mPreservedOpenState ? 1.f : 0.f;
}
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int childWidth = child.getMeasuredWidth();
int offset = 0;
if (lp.slideable) {
final int margin = lp.leftMargin + lp.rightMargin;
final int range = Math.min(nextXStart,
width - paddingEnd - mOverhangSize) - xStart - margin;
mSlideRange = range;
final int lpMargin = isLayoutRtl ? lp.rightMargin : lp.leftMargin;
lp.dimWhenOffset = xStart + lpMargin + range + childWidth / 2 > width - paddingEnd;
final int pos = (int) (range * mSlideOffset);
xStart += pos + lpMargin;
mSlideOffset = (float) pos / mSlideRange;
} else if (mCanSlide && mParallaxBy != 0) {
offset = (int) ((1 - mSlideOffset) * mParallaxBy);
xStart = nextXStart;
} else {
xStart = nextXStart;
}
final int childRight;
final int childLeft;
if (isLayoutRtl) {
childRight = width - xStart + offset;
childLeft = childRight - childWidth;
} else {
childLeft = xStart - offset;
childRight = childLeft + childWidth;
}
final int childTop = paddingTop;
final int childBottom = childTop + child.getMeasuredHeight();
child.layout(childLeft, paddingTop, childRight, childBottom);
nextXStart += child.getWidth();
}
if (mFirstLayout) {
if (mCanSlide) {
if (mParallaxBy != 0) {
parallaxOtherViews(mSlideOffset);
}
if (((LayoutParams) mSlideableView.getLayoutParams()).dimWhenOffset) {
dimChildView(mSlideableView, mSlideOffset, mSliderFadeColor);
}
} else {
// Reset the dim level of all children; it's irrelevant when nothing moves.
for (int i = 0; i < childCount; i++) {
dimChildView(getChildAt(i), 0, mSliderFadeColor);
}
}
updateObscuredViewsVisibility(mSlideableView);
}
mFirstLayout = false;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// Recalculate sliding panes and their details
if (w != oldw) {
mFirstLayout = true;
}
}
@Override
public void requestChildFocus(View child, View focused) {
super.requestChildFocus(child, focused);
if (!isInTouchMode() && !mCanSlide) {
mPreservedOpenState = child == mSlideableView;
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
final int action = ev.getActionMasked();
// Preserve the open state based on the last view that was touched.
if (!mCanSlide && action == MotionEvent.ACTION_DOWN && getChildCount() > 1) {
// After the first things will be slideable.
final View secondChild = getChildAt(1);
if (secondChild != null) {
mPreservedOpenState = !mDragHelper.isViewUnder(secondChild,
(int) ev.getX(), (int) ev.getY());
}
}
if (!mCanSlide || (mIsUnableToDrag && action != MotionEvent.ACTION_DOWN)) {
mDragHelper.cancel();
return super.onInterceptTouchEvent(ev);
}
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
mDragHelper.cancel();
return false;
}
boolean interceptTap = false;
switch (action) {
case MotionEvent.ACTION_DOWN: {
mIsUnableToDrag = false;
final float x = ev.getX();
final float y = ev.getY();
mInitialMotionX = x;
mInitialMotionY = y;
if (mDragHelper.isViewUnder(mSlideableView, (int) x, (int) y)
&& isDimmed(mSlideableView)) {
interceptTap = true;
}
break;
}
case MotionEvent.ACTION_MOVE: {
final float x = ev.getX();
final float y = ev.getY();
final float adx = Math.abs(x - mInitialMotionX);
final float ady = Math.abs(y - mInitialMotionY);
final int slop = mDragHelper.getTouchSlop();
if (adx > slop && ady > adx) {
mDragHelper.cancel();
mIsUnableToDrag = true;
return false;
}
}
}
final boolean interceptForDrag = mDragHelper.shouldInterceptTouchEvent(ev);
return interceptForDrag || interceptTap;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (!mCanSlide) {
return super.onTouchEvent(ev);
}
mDragHelper.processTouchEvent(ev);
boolean wantTouchEvents = true;
switch (ev.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
final float y = ev.getY();
mInitialMotionX = x;
mInitialMotionY = y;
break;
}
case MotionEvent.ACTION_UP: {
if (isDimmed(mSlideableView)) {
final float x = ev.getX();
final float y = ev.getY();
final float dx = x - mInitialMotionX;
final float dy = y - mInitialMotionY;
final int slop = mDragHelper.getTouchSlop();
if (dx * dx + dy * dy < slop * slop
&& mDragHelper.isViewUnder(mSlideableView, (int) x, (int) y)) {
// Taps close a dimmed open pane.
closePane(mSlideableView, 0);
break;
}
}
break;
}
}
return wantTouchEvents;
}
private boolean closePane(View pane, int initialVelocity) {
if (mFirstLayout || smoothSlideTo(0.f, initialVelocity)) {
mPreservedOpenState = false;
return true;
}
return false;
}
private boolean openPane(View pane, int initialVelocity) {
if (mFirstLayout || smoothSlideTo(1.f, initialVelocity)) {
mPreservedOpenState = true;
return true;
}
return false;
}
/**
* @deprecated Renamed to {@link #openPane()} - this method is going away soon!
*/
@Deprecated
public void smoothSlideOpen() {
openPane();
}
/**
* Open the sliding pane if it is currently slideable. If first layout
* has already completed this will animate.
*
* @return true if the pane was slideable and is now open/in the process of opening
*/
public boolean openPane() {
return openPane(mSlideableView, 0);
}
/**
* @deprecated Renamed to {@link #closePane()} - this method is going away soon!
*/
@Deprecated
public void smoothSlideClosed() {
closePane();
}
/**
* Close the sliding pane if it is currently slideable. If first layout
* has already completed this will animate.
*
* @return true if the pane was slideable and is now closed/in the process of closing
*/
public boolean closePane() {
return closePane(mSlideableView, 0);
}
/**
* Check if the layout is completely open. It can be open either because the slider
* itself is open revealing the left pane, or if all content fits without sliding.
*
* @return true if sliding panels are completely open
*/
public boolean isOpen() {
return !mCanSlide || mSlideOffset == 1;
}
/**
* @return true if content in this layout can be slid open and closed
* @deprecated Renamed to {@link #isSlideable()} - this method is going away soon!
*/
@Deprecated
public boolean canSlide() {
return mCanSlide;
}
/**
* Check if the content in this layout cannot fully fit side by side and therefore
* the content pane can be slid back and forth.
*
* @return true if content in this layout can be slid open and closed
*/
public boolean isSlideable() {
return mCanSlide;
}
void onPanelDragged(int newLeft) {
if (mSlideableView == null) {
// This can happen if we're aborting motion during layout because everything now fits.
mSlideOffset = 0;
return;
}
final boolean isLayoutRtl = isLayoutRtlSupport();
final LayoutParams lp = (LayoutParams) mSlideableView.getLayoutParams();
int childWidth = mSlideableView.getWidth();
final int newStart = isLayoutRtl ? getWidth() - newLeft - childWidth : newLeft;
final int paddingStart = isLayoutRtl ? getPaddingRight() : getPaddingLeft();
final int lpMargin = isLayoutRtl ? lp.rightMargin : lp.leftMargin;
final int startBound = paddingStart + lpMargin;
mSlideOffset = (float) (newStart - startBound) / mSlideRange;
if (mParallaxBy != 0) {
parallaxOtherViews(mSlideOffset);
}
if (lp.dimWhenOffset) {
dimChildView(mSlideableView, mSlideOffset, mSliderFadeColor);
}
dispatchOnPanelSlide(mSlideableView);
}
private void dimChildView(View v, float mag, int fadeColor) {
final LayoutParams lp = (LayoutParams) v.getLayoutParams();
if (mag > 0 && fadeColor != 0) {
final int baseAlpha = (fadeColor & 0xff000000) >>> 24;
int imag = (int) (baseAlpha * mag);
int color = imag << 24 | (fadeColor & 0xffffff);
if (lp.dimPaint == null) {
lp.dimPaint = new Paint();
}
lp.dimPaint.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_OVER));
if (v.getLayerType() != View.LAYER_TYPE_HARDWARE) {
v.setLayerType(View.LAYER_TYPE_HARDWARE, lp.dimPaint);
}
invalidateChildRegion(v);
} else if (v.getLayerType() != View.LAYER_TYPE_NONE) {
if (lp.dimPaint != null) {
lp.dimPaint.setColorFilter(null);
}
final DisableLayerRunnable dlr = new DisableLayerRunnable(v);
mPostedRunnables.add(dlr);
ViewCompat.postOnAnimation(this, dlr);
}
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
boolean result;
final int save = canvas.save();
if (mCanSlide && !lp.slideable && mSlideableView != null) {
// Clip against the slider; no sense drawing what will immediately be covered.
canvas.getClipBounds(mTmpRect);
if (isLayoutRtlSupport()) {
mTmpRect.left = Math.max(mTmpRect.left, mSlideableView.getRight());
} else {
mTmpRect.right = Math.min(mTmpRect.right, mSlideableView.getLeft());
}
canvas.clipRect(mTmpRect);
}
result = super.drawChild(canvas, child, drawingTime);
canvas.restoreToCount(save);
return result;
}
private Method mGetDisplayList;
private Field mRecreateDisplayList;
private boolean mDisplayListReflectionLoaded;
void invalidateChildRegion(View v) {
if (Build.VERSION.SDK_INT >= 17) {
ViewCompat.setLayerPaint(v, ((LayoutParams) v.getLayoutParams()).dimPaint);
return;
}
if (Build.VERSION.SDK_INT >= 16) {
// Private API hacks! Nasty! Bad!
//
// In Jellybean, some optimizations in the hardware UI renderer
// prevent a changed Paint on a View using a hardware layer from having
// the intended effect. This twiddles some internal bits on the view to force
// it to recreate the display list.
if (!mDisplayListReflectionLoaded) {
try {
mGetDisplayList = View.class.getDeclaredMethod("getDisplayList",
(Class[]) null);
} catch (NoSuchMethodException e) {
Log.e(TAG, "Couldn't fetch getDisplayList method; dimming won't work right.",
e);
}
try {
mRecreateDisplayList = View.class.getDeclaredField("mRecreateDisplayList");
mRecreateDisplayList.setAccessible(true);
} catch (NoSuchFieldException e) {
Log.e(TAG, "Couldn't fetch mRecreateDisplayList field; dimming will be slow.",
e);
}
mDisplayListReflectionLoaded = true;
}
if (mGetDisplayList == null || mRecreateDisplayList == null) {
// Slow path. REALLY slow path. Let's hope we don't get here.
v.invalidate();
return;
}
try {
mRecreateDisplayList.setBoolean(v, true);
mGetDisplayList.invoke(v, (Object[]) null);
} catch (Exception e) {
Log.e(TAG, "Error refreshing display list state", e);
}
}
ViewCompat.postInvalidateOnAnimation(this, v.getLeft(), v.getTop(), v.getRight(),
v.getBottom());
}
/**
* Smoothly animate mDraggingPane to the target X position within its range.
*
* @param slideOffset position to animate to
* @param velocity initial velocity in case of fling, or 0.
*/
boolean smoothSlideTo(float slideOffset, int velocity) {
if (!mCanSlide) {
// Nothing to do.
return false;
}
final boolean isLayoutRtl = isLayoutRtlSupport();
final LayoutParams lp = (LayoutParams) mSlideableView.getLayoutParams();
int x;
if (isLayoutRtl) {
int startBound = getPaddingRight() + lp.rightMargin;
int childWidth = mSlideableView.getWidth();
x = (int) (getWidth() - (startBound + slideOffset * mSlideRange + childWidth));
} else {
int startBound = getPaddingLeft() + lp.leftMargin;
x = (int) (startBound + slideOffset * mSlideRange);
}
if (mDragHelper.smoothSlideViewTo(mSlideableView, x, mSlideableView.getTop())) {
setAllChildrenVisible();
ViewCompat.postInvalidateOnAnimation(this);
return true;
}
return false;
}
@Override
public void computeScroll() {
if (mDragHelper.continueSettling(true)) {
if (!mCanSlide) {
mDragHelper.abort();
return;
}
ViewCompat.postInvalidateOnAnimation(this);
}
}
/**
* @deprecated Renamed to {@link #setShadowDrawableLeft(Drawable d)} to support LTR (left to
* right language) and {@link #setShadowDrawableRight(Drawable d)} to support RTL (right to left
* language) during opening/closing.
*
* @param d drawable to use as a shadow
*/
@Deprecated
public void setShadowDrawable(Drawable d) {
setShadowDrawableLeft(d);
}
/**
* Set a drawable to use as a shadow cast by the right pane onto the left pane
* during opening/closing.
*
* @param d drawable to use as a shadow
*/
public void setShadowDrawableLeft(@Nullable Drawable d) {
mShadowDrawableLeft = d;
}
/**
* Set a drawable to use as a shadow cast by the left pane onto the right pane
* during opening/closing to support right to left language.
*
* @param d drawable to use as a shadow
*/
public void setShadowDrawableRight(@Nullable Drawable d) {
mShadowDrawableRight = d;
}
/**
* Set a drawable to use as a shadow cast by the right pane onto the left pane
* during opening/closing.
*
* @param resId Resource ID of a drawable to use
* @deprecated Renamed to {@link #setShadowResourceLeft(int)} to support LTR (left to
* right language) and {@link #setShadowResourceRight(int)} to support RTL (right to left
* language) during opening/closing.
*/
@Deprecated
public void setShadowResource(@DrawableRes int resId) {
setShadowDrawable(getResources().getDrawable(resId));
}
/**
* Set a drawable to use as a shadow cast by the right pane onto the left pane
* during opening/closing.
*
* @param resId Resource ID of a drawable to use
*/
public void setShadowResourceLeft(int resId) {
setShadowDrawableLeft(ContextCompat.getDrawable(getContext(), resId));
}
/**
* Set a drawable to use as a shadow cast by the left pane onto the right pane
* during opening/closing to support right to left language.
*
* @param resId Resource ID of a drawable to use
*/
public void setShadowResourceRight(int resId) {
setShadowDrawableRight(ContextCompat.getDrawable(getContext(), resId));
}
@Override
public void draw(Canvas c) {
super.draw(c);
final boolean isLayoutRtl = isLayoutRtlSupport();
Drawable shadowDrawable;
if (isLayoutRtl) {
shadowDrawable = mShadowDrawableRight;
} else {
shadowDrawable = mShadowDrawableLeft;
}
final View shadowView = getChildCount() > 1 ? getChildAt(1) : null;
if (shadowView == null || shadowDrawable == null) {
// No need to draw a shadow if we don't have one.
return;
}
final int top = shadowView.getTop();
final int bottom = shadowView.getBottom();
final int shadowWidth = shadowDrawable.getIntrinsicWidth();
final int left;
final int right;
if (isLayoutRtlSupport()) {
left = shadowView.getRight();
right = left + shadowWidth;
} else {
right = shadowView.getLeft();
left = right - shadowWidth;
}
shadowDrawable.setBounds(left, top, right, bottom);
shadowDrawable.draw(c);
}
private void parallaxOtherViews(float slideOffset) {
final boolean isLayoutRtl = isLayoutRtlSupport();
final LayoutParams slideLp = (LayoutParams) mSlideableView.getLayoutParams();
final boolean dimViews = slideLp.dimWhenOffset
&& (isLayoutRtl ? slideLp.rightMargin : slideLp.leftMargin) <= 0;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View v = getChildAt(i);
if (v == mSlideableView) continue;
final int oldOffset = (int) ((1 - mParallaxOffset) * mParallaxBy);
mParallaxOffset = slideOffset;
final int newOffset = (int) ((1 - slideOffset) * mParallaxBy);
final int dx = oldOffset - newOffset;
v.offsetLeftAndRight(isLayoutRtl ? -dx : dx);
if (dimViews) {
dimChildView(v, isLayoutRtl ? mParallaxOffset - 1
: 1 - mParallaxOffset, mCoveredFadeColor);
}
}
}
/**
* Tests scrollability within child views of v given a delta of dx.
*
* @param v View to test for horizontal scrollability
* @param checkV Whether the view v passed should itself be checked for scrollability (true),
* or just its children (false).
* @param dx Delta scrolled in pixels
* @param x X coordinate of the active touch point
* @param y Y coordinate of the active touch point
* @return true if child views of v can be scrolled by delta of dx.
*/
protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
if (v instanceof ViewGroup) {
final ViewGroup group = (ViewGroup) v;
final int scrollX = v.getScrollX();
final int scrollY = v.getScrollY();
final int count = group.getChildCount();
// Count backwards - let topmost views consume scroll distance first.
for (int i = count - 1; i >= 0; i--) {
// TODO: Add versioned support here for transformed views.
// This will not work for transformed views in Honeycomb+
final View child = group.getChildAt(i);
if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight()
&& y + scrollY >= child.getTop() && y + scrollY < child.getBottom()
&& canScroll(child, true, dx, x + scrollX - child.getLeft(),
y + scrollY - child.getTop())) {
return true;
}
}
}
return checkV && v.canScrollHorizontally((isLayoutRtlSupport() ? dx : -dx));
}
boolean isDimmed(View child) {
if (child == null) {
return false;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
return mCanSlide && lp.dimWhenOffset && mSlideOffset > 0;
}
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
return new LayoutParams();
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof MarginLayoutParams
? new LayoutParams((MarginLayoutParams) p)
: new LayoutParams(p);
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams && super.checkLayoutParams(p);
}
@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.isOpen = isSlideable() ? isOpen() : mPreservedOpenState;
return ss;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
if (ss.isOpen) {
openPane();
} else {
closePane();
}
mPreservedOpenState = ss.isOpen;
}
private class DragHelperCallback extends ViewDragHelper.Callback {
DragHelperCallback() {
}
@Override
public boolean tryCaptureView(View child, int pointerId) {
if (mIsUnableToDrag) {
return false;
}
return ((LayoutParams) child.getLayoutParams()).slideable;
}
@Override
public void onViewDragStateChanged(int state) {
if (mDragHelper.getViewDragState() == ViewDragHelper.STATE_IDLE) {
if (mSlideOffset == 0) {
updateObscuredViewsVisibility(mSlideableView);
dispatchOnPanelClosed(mSlideableView);
mPreservedOpenState = false;
} else {
dispatchOnPanelOpened(mSlideableView);
mPreservedOpenState = true;
}
}
}
@Override
public void onViewCaptured(View capturedChild, int activePointerId) {
// Make all child views visible in preparation for sliding things around
setAllChildrenVisible();
}
@Override
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
onPanelDragged(left);
invalidate();
}
@Override
public void onViewReleased(View releasedChild, float xvel, float yvel) {
final LayoutParams lp = (LayoutParams) releasedChild.getLayoutParams();
int left;
if (isLayoutRtlSupport()) {
int startToRight = getPaddingRight() + lp.rightMargin;
if (xvel < 0 || (xvel == 0 && mSlideOffset > 0.5f)) {
startToRight += mSlideRange;
}
int childWidth = mSlideableView.getWidth();
left = getWidth() - startToRight - childWidth;
} else {
left = getPaddingLeft() + lp.leftMargin;
if (xvel > 0 || (xvel == 0 && mSlideOffset > 0.5f)) {
left += mSlideRange;
}
}
mDragHelper.settleCapturedViewAt(left, releasedChild.getTop());
invalidate();
}
@Override
public int getViewHorizontalDragRange(View child) {
return mSlideRange;
}
@Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
final LayoutParams lp = (LayoutParams) mSlideableView.getLayoutParams();
final int newLeft;
if (isLayoutRtlSupport()) {
int startBound = getWidth()
- (getPaddingRight() + lp.rightMargin + mSlideableView.getWidth());
int endBound = startBound - mSlideRange;
newLeft = Math.max(Math.min(left, startBound), endBound);
} else {
int startBound = getPaddingLeft() + lp.leftMargin;
int endBound = startBound + mSlideRange;
newLeft = Math.min(Math.max(left, startBound), endBound);
}
return newLeft;
}
@Override
public int clampViewPositionVertical(View child, int top, int dy) {
// Make sure we never move views vertically.
// This could happen if the child has less height than its parent.
return child.getTop();
}
@Override
public void onEdgeDragStarted(int edgeFlags, int pointerId) {
mDragHelper.captureChildView(mSlideableView, pointerId);
}
}
public static class LayoutParams extends ViewGroup.MarginLayoutParams {
private static final int[] ATTRS = new int[] {
android.R.attr.layout_weight
};
/**
* The weighted proportion of how much of the leftover space
* this child should consume after measurement.
*/
public float weight = 0;
/**
* True if this pane is the slideable pane in the layout.
*/
boolean slideable;
/**
* True if this view should be drawn dimmed
* when it's been offset from its default position.
*/
boolean dimWhenOffset;
Paint dimPaint;
public LayoutParams() {
super(MATCH_PARENT, MATCH_PARENT);
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(@NonNull android.view.ViewGroup.LayoutParams source) {
super(source);
}
public LayoutParams(@NonNull MarginLayoutParams source) {
super(source);
}
public LayoutParams(@NonNull LayoutParams source) {
super(source);
this.weight = source.weight;
}
public LayoutParams(@NonNull Context c, @Nullable AttributeSet attrs) {
super(c, attrs);
final TypedArray a = c.obtainStyledAttributes(attrs, ATTRS);
this.weight = a.getFloat(0, 0);
a.recycle();
}
}
static class SavedState extends AbsSavedState {
boolean isOpen;
SavedState(Parcelable superState) {
super(superState);
}
SavedState(Parcel in, ClassLoader loader) {
super(in, loader);
isOpen = in.readInt() != 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(isOpen ? 1 : 0);
}
public static final Creator<SavedState> CREATOR = new ClassLoaderCreator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel in, ClassLoader loader) {
return new SavedState(in, null);
}
@Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in, null);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
class AccessibilityDelegate extends AccessibilityDelegateCompat {
private final Rect mTmpRect = new Rect();
@Override
public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) {
final AccessibilityNodeInfoCompat superNode = AccessibilityNodeInfoCompat.obtain(info);
super.onInitializeAccessibilityNodeInfo(host, superNode);
copyNodeInfoNoChildren(info, superNode);
superNode.recycle();
info.setClassName(SlidingPaneLayout.class.getName());
info.setSource(host);
final ViewParent parent = ViewCompat.getParentForAccessibility(host);
if (parent instanceof View) {
info.setParent((View) parent);
}
// This is a best-approximation of addChildrenForAccessibility()
// that accounts for filtering.
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (!filter(child) && (child.getVisibility() == View.VISIBLE)) {
// Force importance to "yes" since we can't read the value.
ViewCompat.setImportantForAccessibility(
child, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES);
info.addChild(child);
}
}
}
@Override
public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
super.onInitializeAccessibilityEvent(host, event);
event.setClassName(SlidingPaneLayout.class.getName());
}
@Override
public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
AccessibilityEvent event) {
if (!filter(child)) {
return super.onRequestSendAccessibilityEvent(host, child, event);
}
return false;
}
public boolean filter(View child) {
return isDimmed(child);
}
/**
* This should really be in AccessibilityNodeInfoCompat, but there unfortunately
* seem to be a few elements that are not easily cloneable using the underlying API.
* Leave it private here as it's not general-purpose useful.
*/
private void copyNodeInfoNoChildren(AccessibilityNodeInfoCompat dest,
AccessibilityNodeInfoCompat src) {
final Rect rect = mTmpRect;
src.getBoundsInParent(rect);
dest.setBoundsInParent(rect);
src.getBoundsInScreen(rect);
dest.setBoundsInScreen(rect);
dest.setVisibleToUser(src.isVisibleToUser());
dest.setPackageName(src.getPackageName());
dest.setClassName(src.getClassName());
dest.setContentDescription(src.getContentDescription());
dest.setEnabled(src.isEnabled());
dest.setClickable(src.isClickable());
dest.setFocusable(src.isFocusable());
dest.setFocused(src.isFocused());
dest.setAccessibilityFocused(src.isAccessibilityFocused());
dest.setSelected(src.isSelected());
dest.setLongClickable(src.isLongClickable());
dest.addAction(src.getActions());
dest.setMovementGranularities(src.getMovementGranularities());
}
}
private class DisableLayerRunnable implements Runnable {
final View mChildView;
DisableLayerRunnable(View childView) {
mChildView = childView;
}
@Override
public void run() {
if (mChildView.getParent() == SlidingPaneLayout.this) {
mChildView.setLayerType(View.LAYER_TYPE_NONE, null);
invalidateChildRegion(mChildView);
}
mPostedRunnables.remove(this);
}
}
boolean isLayoutRtlSupport() {
return ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL;
}
}
| slidingpanelayout/src/main/java/androidx/slidingpanelayout/widget/SlidingPaneLayout.java | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.slidingpanelayout.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.accessibility.AccessibilityEvent;
import androidx.annotation.ColorInt;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.Px;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
import androidx.core.view.AccessibilityDelegateCompat;
import androidx.core.view.ViewCompat;
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
import androidx.customview.view.AbsSavedState;
import androidx.customview.widget.ViewDragHelper;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
/**
* SlidingPaneLayout provides a horizontal, multi-pane layout for use at the top level
* of a UI. A left (or first) pane is treated as a content list or browser, subordinate to a
* primary detail view for displaying content.
*
* <p>Child views may overlap if their combined width exceeds the available width
* in the SlidingPaneLayout. When this occurs the user may slide the topmost view out of the way
* by dragging it, or by navigating in the direction of the overlapped view using a keyboard.
* If the content of the dragged child view is itself horizontally scrollable, the user may
* grab it by the very edge.</p>
*
* <p>Thanks to this sliding behavior, SlidingPaneLayout may be suitable for creating layouts
* that can smoothly adapt across many different screen sizes, expanding out fully on larger
* screens and collapsing on smaller screens.</p>
*
* <p>SlidingPaneLayout is distinct from a navigation drawer as described in the design
* guide and should not be used in the same scenarios. SlidingPaneLayout should be thought
* of only as a way to allow a two-pane layout normally used on larger screens to adapt to smaller
* screens in a natural way. The interaction patterns expressed by SlidingPaneLayout imply
* a physicality and direct information hierarchy between panes that does not necessarily exist
* in a scenario where a navigation drawer should be used instead.</p>
*
* <p>Appropriate uses of SlidingPaneLayout include pairings of panes such as a contact list and
* subordinate interactions with those contacts, or an email thread list with the content pane
* displaying the contents of the selected thread. Inappropriate uses of SlidingPaneLayout include
* switching between disparate functions of your app, such as jumping from a social stream view
* to a view of your personal profile - cases such as this should use the navigation drawer
* pattern instead. ({@link androidx.drawerlayout.widget.DrawerLayout DrawerLayout} implements this pattern.)</p>
*
* <p>Like {@link android.widget.LinearLayout LinearLayout}, SlidingPaneLayout supports
* the use of the layout parameter <code>layout_weight</code> on child views to determine
* how to divide leftover space after measurement is complete. It is only relevant for width.
* When views do not overlap weight behaves as it does in a LinearLayout.</p>
*
* <p>When views do overlap, weight on a slideable pane indicates that the pane should be
* sized to fill all available space in the closed state. Weight on a pane that becomes covered
* indicates that the pane should be sized to fill all available space except a small minimum strip
* that the user may use to grab the slideable view and pull it back over into a closed state.</p>
*/
public class SlidingPaneLayout extends ViewGroup {
private static final String TAG = "SlidingPaneLayout";
/**
* Default size of the overhang for a pane in the open state.
* At least this much of a sliding pane will remain visible.
* This indicates that there is more content available and provides
* a "physical" edge to grab to pull it closed.
*/
private static final int DEFAULT_OVERHANG_SIZE = 32; // dp;
/**
* If no fade color is given by default it will fade to 80% gray.
*/
private static final int DEFAULT_FADE_COLOR = 0xcccccccc;
/**
* The fade color used for the sliding panel. 0 = no fading.
*/
private int mSliderFadeColor = DEFAULT_FADE_COLOR;
/**
* Minimum velocity that will be detected as a fling
*/
private static final int MIN_FLING_VELOCITY = 400; // dips per second
/**
* The fade color used for the panel covered by the slider. 0 = no fading.
*/
private int mCoveredFadeColor;
/**
* Drawable used to draw the shadow between panes by default.
*/
private Drawable mShadowDrawableLeft;
/**
* Drawable used to draw the shadow between panes to support RTL (right to left language).
*/
private Drawable mShadowDrawableRight;
/**
* The size of the overhang in pixels.
* This is the minimum section of the sliding panel that will
* be visible in the open state to allow for a closing drag.
*/
private final int mOverhangSize;
/**
* True if a panel can slide with the current measurements
*/
private boolean mCanSlide;
/**
* The child view that can slide, if any.
*/
View mSlideableView;
/**
* How far the panel is offset from its closed position.
* range [0, 1] where 0 = closed, 1 = open.
*/
float mSlideOffset;
/**
* How far the non-sliding panel is parallaxed from its usual position when open.
* range [0, 1]
*/
private float mParallaxOffset;
/**
* How far in pixels the slideable panel may move.
*/
int mSlideRange;
/**
* A panel view is locked into internal scrolling or another condition that
* is preventing a drag.
*/
boolean mIsUnableToDrag;
/**
* Distance in pixels to parallax the fixed pane by when fully closed
*/
private int mParallaxBy;
private float mInitialMotionX;
private float mInitialMotionY;
private PanelSlideListener mPanelSlideListener;
final ViewDragHelper mDragHelper;
/**
* Stores whether or not the pane was open the last time it was slideable.
* If open/close operations are invoked this state is modified. Used by
* instance state save/restore.
*/
boolean mPreservedOpenState;
private boolean mFirstLayout = true;
private final Rect mTmpRect = new Rect();
final ArrayList<DisableLayerRunnable> mPostedRunnables = new ArrayList<>();
static final SlidingPanelLayoutImpl IMPL;
static {
if (Build.VERSION.SDK_INT >= 17) {
IMPL = new SlidingPanelLayoutImplJBMR1();
} else if (Build.VERSION.SDK_INT >= 16) {
IMPL = new SlidingPanelLayoutImplJB();
} else {
IMPL = new SlidingPanelLayoutImplBase();
}
}
/**
* Listener for monitoring events about sliding panes.
*/
public interface PanelSlideListener {
/**
* Called when a sliding pane's position changes.
* @param panel The child view that was moved
* @param slideOffset The new offset of this sliding pane within its range, from 0-1
*/
void onPanelSlide(@NonNull View panel, float slideOffset);
/**
* Called when a sliding pane becomes slid completely open. The pane may or may not
* be interactive at this point depending on how much of the pane is visible.
* @param panel The child view that was slid to an open position, revealing other panes
*/
void onPanelOpened(@NonNull View panel);
/**
* Called when a sliding pane becomes slid completely closed. The pane is now guaranteed
* to be interactive. It may now obscure other views in the layout.
* @param panel The child view that was slid to a closed position
*/
void onPanelClosed(@NonNull View panel);
}
/**
* No-op stubs for {@link PanelSlideListener}. If you only want to implement a subset
* of the listener methods you can extend this instead of implement the full interface.
*/
public static class SimplePanelSlideListener implements PanelSlideListener {
@Override
public void onPanelSlide(View panel, float slideOffset) {
}
@Override
public void onPanelOpened(View panel) {
}
@Override
public void onPanelClosed(View panel) {
}
}
public SlidingPaneLayout(@NonNull Context context) {
this(context, null);
}
public SlidingPaneLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public SlidingPaneLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
final float density = context.getResources().getDisplayMetrics().density;
mOverhangSize = (int) (DEFAULT_OVERHANG_SIZE * density + 0.5f);
setWillNotDraw(false);
ViewCompat.setAccessibilityDelegate(this, new AccessibilityDelegate());
ViewCompat.setImportantForAccessibility(this, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES);
mDragHelper = ViewDragHelper.create(this, 0.5f, new DragHelperCallback());
mDragHelper.setMinVelocity(MIN_FLING_VELOCITY * density);
}
/**
* Set a distance to parallax the lower pane by when the upper pane is in its
* fully closed state. The lower pane will scroll between this position and
* its fully open state.
*
* @param parallaxBy Distance to parallax by in pixels
*/
public void setParallaxDistance(@Px int parallaxBy) {
mParallaxBy = parallaxBy;
requestLayout();
}
/**
* @return The distance the lower pane will parallax by when the upper pane is fully closed.
*
* @see #setParallaxDistance(int)
*/
@Px
public int getParallaxDistance() {
return mParallaxBy;
}
/**
* Set the color used to fade the sliding pane out when it is slid most of the way offscreen.
*
* @param color An ARGB-packed color value
*/
public void setSliderFadeColor(@ColorInt int color) {
mSliderFadeColor = color;
}
/**
* @return The ARGB-packed color value used to fade the sliding pane
*/
@ColorInt
public int getSliderFadeColor() {
return mSliderFadeColor;
}
/**
* Set the color used to fade the pane covered by the sliding pane out when the pane
* will become fully covered in the closed state.
*
* @param color An ARGB-packed color value
*/
public void setCoveredFadeColor(@ColorInt int color) {
mCoveredFadeColor = color;
}
/**
* @return The ARGB-packed color value used to fade the fixed pane
*/
@ColorInt
public int getCoveredFadeColor() {
return mCoveredFadeColor;
}
public void setPanelSlideListener(@Nullable PanelSlideListener listener) {
mPanelSlideListener = listener;
}
void dispatchOnPanelSlide(View panel) {
if (mPanelSlideListener != null) {
mPanelSlideListener.onPanelSlide(panel, mSlideOffset);
}
}
void dispatchOnPanelOpened(View panel) {
if (mPanelSlideListener != null) {
mPanelSlideListener.onPanelOpened(panel);
}
sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
}
void dispatchOnPanelClosed(View panel) {
if (mPanelSlideListener != null) {
mPanelSlideListener.onPanelClosed(panel);
}
sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
}
void updateObscuredViewsVisibility(View panel) {
final boolean isLayoutRtl = isLayoutRtlSupport();
final int startBound = isLayoutRtl ? (getWidth() - getPaddingRight()) : getPaddingLeft();
final int endBound = isLayoutRtl ? getPaddingLeft() : (getWidth() - getPaddingRight());
final int topBound = getPaddingTop();
final int bottomBound = getHeight() - getPaddingBottom();
final int left;
final int right;
final int top;
final int bottom;
if (panel != null && viewIsOpaque(panel)) {
left = panel.getLeft();
right = panel.getRight();
top = panel.getTop();
bottom = panel.getBottom();
} else {
left = right = top = bottom = 0;
}
for (int i = 0, childCount = getChildCount(); i < childCount; i++) {
final View child = getChildAt(i);
if (child == panel) {
// There are still more children above the panel but they won't be affected.
break;
} else if (child.getVisibility() == GONE) {
continue;
}
final int clampedChildLeft = Math.max(
(isLayoutRtl ? endBound : startBound), child.getLeft());
final int clampedChildTop = Math.max(topBound, child.getTop());
final int clampedChildRight = Math.min(
(isLayoutRtl ? startBound : endBound), child.getRight());
final int clampedChildBottom = Math.min(bottomBound, child.getBottom());
final int vis;
if (clampedChildLeft >= left && clampedChildTop >= top
&& clampedChildRight <= right && clampedChildBottom <= bottom) {
vis = INVISIBLE;
} else {
vis = VISIBLE;
}
child.setVisibility(vis);
}
}
void setAllChildrenVisible() {
for (int i = 0, childCount = getChildCount(); i < childCount; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == INVISIBLE) {
child.setVisibility(VISIBLE);
}
}
}
private static boolean viewIsOpaque(View v) {
if (v.isOpaque()) {
return true;
}
// View#isOpaque didn't take all valid opaque scrollbar modes into account
// before API 18 (JB-MR2). On newer devices rely solely on isOpaque above and return false
// here. On older devices, check the view's background drawable directly as a fallback.
if (Build.VERSION.SDK_INT >= 18) {
return false;
}
final Drawable bg = v.getBackground();
if (bg != null) {
return bg.getOpacity() == PixelFormat.OPAQUE;
}
return false;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mFirstLayout = true;
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mFirstLayout = true;
for (int i = 0, count = mPostedRunnables.size(); i < count; i++) {
final DisableLayerRunnable dlr = mPostedRunnables.get(i);
dlr.run();
}
mPostedRunnables.clear();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthMode != MeasureSpec.EXACTLY) {
if (isInEditMode()) {
// Don't crash the layout editor. Consume all of the space if specified
// or pick a magic number from thin air otherwise.
// TODO Better communication with tools of this bogus state.
// It will crash on a real device.
if (widthMode == MeasureSpec.AT_MOST) {
widthMode = MeasureSpec.EXACTLY;
} else if (widthMode == MeasureSpec.UNSPECIFIED) {
widthMode = MeasureSpec.EXACTLY;
widthSize = 300;
}
} else {
throw new IllegalStateException("Width must have an exact value or MATCH_PARENT");
}
} else if (heightMode == MeasureSpec.UNSPECIFIED) {
if (isInEditMode()) {
// Don't crash the layout editor. Pick a magic number from thin air instead.
// TODO Better communication with tools of this bogus state.
// It will crash on a real device.
if (heightMode == MeasureSpec.UNSPECIFIED) {
heightMode = MeasureSpec.AT_MOST;
heightSize = 300;
}
} else {
throw new IllegalStateException("Height must not be UNSPECIFIED");
}
}
int layoutHeight = 0;
int maxLayoutHeight = 0;
switch (heightMode) {
case MeasureSpec.EXACTLY:
layoutHeight = maxLayoutHeight = heightSize - getPaddingTop() - getPaddingBottom();
break;
case MeasureSpec.AT_MOST:
maxLayoutHeight = heightSize - getPaddingTop() - getPaddingBottom();
break;
}
float weightSum = 0;
boolean canSlide = false;
final int widthAvailable = widthSize - getPaddingLeft() - getPaddingRight();
int widthRemaining = widthAvailable;
final int childCount = getChildCount();
if (childCount > 2) {
Log.e(TAG, "onMeasure: More than two child views are not supported.");
}
// We'll find the current one below.
mSlideableView = null;
// First pass. Measure based on child LayoutParams width/height.
// Weight will incur a second pass.
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (child.getVisibility() == GONE) {
lp.dimWhenOffset = false;
continue;
}
if (lp.weight > 0) {
weightSum += lp.weight;
// If we have no width, weight is the only contributor to the final size.
// Measure this view on the weight pass only.
if (lp.width == 0) continue;
}
int childWidthSpec;
final int horizontalMargin = lp.leftMargin + lp.rightMargin;
if (lp.width == LayoutParams.WRAP_CONTENT) {
childWidthSpec = MeasureSpec.makeMeasureSpec(widthAvailable - horizontalMargin,
MeasureSpec.AT_MOST);
} else if (lp.width == LayoutParams.MATCH_PARENT) {
childWidthSpec = MeasureSpec.makeMeasureSpec(widthAvailable - horizontalMargin,
MeasureSpec.EXACTLY);
} else {
childWidthSpec = MeasureSpec.makeMeasureSpec(lp.width, MeasureSpec.EXACTLY);
}
int childHeightSpec;
if (lp.height == LayoutParams.WRAP_CONTENT) {
childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight, MeasureSpec.AT_MOST);
} else if (lp.height == LayoutParams.MATCH_PARENT) {
childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight, MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(lp.height, MeasureSpec.EXACTLY);
}
child.measure(childWidthSpec, childHeightSpec);
final int childWidth = child.getMeasuredWidth();
final int childHeight = child.getMeasuredHeight();
if (heightMode == MeasureSpec.AT_MOST && childHeight > layoutHeight) {
layoutHeight = Math.min(childHeight, maxLayoutHeight);
}
widthRemaining -= childWidth;
canSlide |= lp.slideable = widthRemaining < 0;
if (lp.slideable) {
mSlideableView = child;
}
}
// Resolve weight and make sure non-sliding panels are smaller than the full screen.
if (canSlide || weightSum > 0) {
final int fixedPanelWidthLimit = widthAvailable - mOverhangSize;
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (child.getVisibility() == GONE) {
continue;
}
final boolean skippedFirstPass = lp.width == 0 && lp.weight > 0;
final int measuredWidth = skippedFirstPass ? 0 : child.getMeasuredWidth();
if (canSlide && child != mSlideableView) {
if (lp.width < 0 && (measuredWidth > fixedPanelWidthLimit || lp.weight > 0)) {
// Fixed panels in a sliding configuration should
// be clamped to the fixed panel limit.
final int childHeightSpec;
if (skippedFirstPass) {
// Do initial height measurement if we skipped measuring this view
// the first time around.
if (lp.height == LayoutParams.WRAP_CONTENT) {
childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight,
MeasureSpec.AT_MOST);
} else if (lp.height == LayoutParams.MATCH_PARENT) {
childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight,
MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(lp.height,
MeasureSpec.EXACTLY);
}
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(
child.getMeasuredHeight(), MeasureSpec.EXACTLY);
}
final int childWidthSpec = MeasureSpec.makeMeasureSpec(
fixedPanelWidthLimit, MeasureSpec.EXACTLY);
child.measure(childWidthSpec, childHeightSpec);
}
} else if (lp.weight > 0) {
int childHeightSpec;
if (lp.width == 0) {
// This was skipped the first time; figure out a real height spec.
if (lp.height == LayoutParams.WRAP_CONTENT) {
childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight,
MeasureSpec.AT_MOST);
} else if (lp.height == LayoutParams.MATCH_PARENT) {
childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight,
MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(lp.height,
MeasureSpec.EXACTLY);
}
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(
child.getMeasuredHeight(), MeasureSpec.EXACTLY);
}
if (canSlide) {
// Consume available space
final int horizontalMargin = lp.leftMargin + lp.rightMargin;
final int newWidth = widthAvailable - horizontalMargin;
final int childWidthSpec = MeasureSpec.makeMeasureSpec(
newWidth, MeasureSpec.EXACTLY);
if (measuredWidth != newWidth) {
child.measure(childWidthSpec, childHeightSpec);
}
} else {
// Distribute the extra width proportionally similar to LinearLayout
final int widthToDistribute = Math.max(0, widthRemaining);
final int addedWidth = (int) (lp.weight * widthToDistribute / weightSum);
final int childWidthSpec = MeasureSpec.makeMeasureSpec(
measuredWidth + addedWidth, MeasureSpec.EXACTLY);
child.measure(childWidthSpec, childHeightSpec);
}
}
}
}
final int measuredWidth = widthSize;
final int measuredHeight = layoutHeight + getPaddingTop() + getPaddingBottom();
setMeasuredDimension(measuredWidth, measuredHeight);
mCanSlide = canSlide;
if (mDragHelper.getViewDragState() != ViewDragHelper.STATE_IDLE && !canSlide) {
// Cancel scrolling in progress, it's no longer relevant.
mDragHelper.abort();
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final boolean isLayoutRtl = isLayoutRtlSupport();
if (isLayoutRtl) {
mDragHelper.setEdgeTrackingEnabled(ViewDragHelper.EDGE_RIGHT);
} else {
mDragHelper.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT);
}
final int width = r - l;
final int paddingStart = isLayoutRtl ? getPaddingRight() : getPaddingLeft();
final int paddingEnd = isLayoutRtl ? getPaddingLeft() : getPaddingRight();
final int paddingTop = getPaddingTop();
final int childCount = getChildCount();
int xStart = paddingStart;
int nextXStart = xStart;
if (mFirstLayout) {
mSlideOffset = mCanSlide && mPreservedOpenState ? 1.f : 0.f;
}
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int childWidth = child.getMeasuredWidth();
int offset = 0;
if (lp.slideable) {
final int margin = lp.leftMargin + lp.rightMargin;
final int range = Math.min(nextXStart,
width - paddingEnd - mOverhangSize) - xStart - margin;
mSlideRange = range;
final int lpMargin = isLayoutRtl ? lp.rightMargin : lp.leftMargin;
lp.dimWhenOffset = xStart + lpMargin + range + childWidth / 2 > width - paddingEnd;
final int pos = (int) (range * mSlideOffset);
xStart += pos + lpMargin;
mSlideOffset = (float) pos / mSlideRange;
} else if (mCanSlide && mParallaxBy != 0) {
offset = (int) ((1 - mSlideOffset) * mParallaxBy);
xStart = nextXStart;
} else {
xStart = nextXStart;
}
final int childRight;
final int childLeft;
if (isLayoutRtl) {
childRight = width - xStart + offset;
childLeft = childRight - childWidth;
} else {
childLeft = xStart - offset;
childRight = childLeft + childWidth;
}
final int childTop = paddingTop;
final int childBottom = childTop + child.getMeasuredHeight();
child.layout(childLeft, paddingTop, childRight, childBottom);
nextXStart += child.getWidth();
}
if (mFirstLayout) {
if (mCanSlide) {
if (mParallaxBy != 0) {
parallaxOtherViews(mSlideOffset);
}
if (((LayoutParams) mSlideableView.getLayoutParams()).dimWhenOffset) {
dimChildView(mSlideableView, mSlideOffset, mSliderFadeColor);
}
} else {
// Reset the dim level of all children; it's irrelevant when nothing moves.
for (int i = 0; i < childCount; i++) {
dimChildView(getChildAt(i), 0, mSliderFadeColor);
}
}
updateObscuredViewsVisibility(mSlideableView);
}
mFirstLayout = false;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// Recalculate sliding panes and their details
if (w != oldw) {
mFirstLayout = true;
}
}
@Override
public void requestChildFocus(View child, View focused) {
super.requestChildFocus(child, focused);
if (!isInTouchMode() && !mCanSlide) {
mPreservedOpenState = child == mSlideableView;
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
final int action = ev.getActionMasked();
// Preserve the open state based on the last view that was touched.
if (!mCanSlide && action == MotionEvent.ACTION_DOWN && getChildCount() > 1) {
// After the first things will be slideable.
final View secondChild = getChildAt(1);
if (secondChild != null) {
mPreservedOpenState = !mDragHelper.isViewUnder(secondChild,
(int) ev.getX(), (int) ev.getY());
}
}
if (!mCanSlide || (mIsUnableToDrag && action != MotionEvent.ACTION_DOWN)) {
mDragHelper.cancel();
return super.onInterceptTouchEvent(ev);
}
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
mDragHelper.cancel();
return false;
}
boolean interceptTap = false;
switch (action) {
case MotionEvent.ACTION_DOWN: {
mIsUnableToDrag = false;
final float x = ev.getX();
final float y = ev.getY();
mInitialMotionX = x;
mInitialMotionY = y;
if (mDragHelper.isViewUnder(mSlideableView, (int) x, (int) y)
&& isDimmed(mSlideableView)) {
interceptTap = true;
}
break;
}
case MotionEvent.ACTION_MOVE: {
final float x = ev.getX();
final float y = ev.getY();
final float adx = Math.abs(x - mInitialMotionX);
final float ady = Math.abs(y - mInitialMotionY);
final int slop = mDragHelper.getTouchSlop();
if (adx > slop && ady > adx) {
mDragHelper.cancel();
mIsUnableToDrag = true;
return false;
}
}
}
final boolean interceptForDrag = mDragHelper.shouldInterceptTouchEvent(ev);
return interceptForDrag || interceptTap;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (!mCanSlide) {
return super.onTouchEvent(ev);
}
mDragHelper.processTouchEvent(ev);
boolean wantTouchEvents = true;
switch (ev.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
final float y = ev.getY();
mInitialMotionX = x;
mInitialMotionY = y;
break;
}
case MotionEvent.ACTION_UP: {
if (isDimmed(mSlideableView)) {
final float x = ev.getX();
final float y = ev.getY();
final float dx = x - mInitialMotionX;
final float dy = y - mInitialMotionY;
final int slop = mDragHelper.getTouchSlop();
if (dx * dx + dy * dy < slop * slop
&& mDragHelper.isViewUnder(mSlideableView, (int) x, (int) y)) {
// Taps close a dimmed open pane.
closePane(mSlideableView, 0);
break;
}
}
break;
}
}
return wantTouchEvents;
}
private boolean closePane(View pane, int initialVelocity) {
if (mFirstLayout || smoothSlideTo(0.f, initialVelocity)) {
mPreservedOpenState = false;
return true;
}
return false;
}
private boolean openPane(View pane, int initialVelocity) {
if (mFirstLayout || smoothSlideTo(1.f, initialVelocity)) {
mPreservedOpenState = true;
return true;
}
return false;
}
/**
* @deprecated Renamed to {@link #openPane()} - this method is going away soon!
*/
@Deprecated
public void smoothSlideOpen() {
openPane();
}
/**
* Open the sliding pane if it is currently slideable. If first layout
* has already completed this will animate.
*
* @return true if the pane was slideable and is now open/in the process of opening
*/
public boolean openPane() {
return openPane(mSlideableView, 0);
}
/**
* @deprecated Renamed to {@link #closePane()} - this method is going away soon!
*/
@Deprecated
public void smoothSlideClosed() {
closePane();
}
/**
* Close the sliding pane if it is currently slideable. If first layout
* has already completed this will animate.
*
* @return true if the pane was slideable and is now closed/in the process of closing
*/
public boolean closePane() {
return closePane(mSlideableView, 0);
}
/**
* Check if the layout is completely open. It can be open either because the slider
* itself is open revealing the left pane, or if all content fits without sliding.
*
* @return true if sliding panels are completely open
*/
public boolean isOpen() {
return !mCanSlide || mSlideOffset == 1;
}
/**
* @return true if content in this layout can be slid open and closed
* @deprecated Renamed to {@link #isSlideable()} - this method is going away soon!
*/
@Deprecated
public boolean canSlide() {
return mCanSlide;
}
/**
* Check if the content in this layout cannot fully fit side by side and therefore
* the content pane can be slid back and forth.
*
* @return true if content in this layout can be slid open and closed
*/
public boolean isSlideable() {
return mCanSlide;
}
void onPanelDragged(int newLeft) {
if (mSlideableView == null) {
// This can happen if we're aborting motion during layout because everything now fits.
mSlideOffset = 0;
return;
}
final boolean isLayoutRtl = isLayoutRtlSupport();
final LayoutParams lp = (LayoutParams) mSlideableView.getLayoutParams();
int childWidth = mSlideableView.getWidth();
final int newStart = isLayoutRtl ? getWidth() - newLeft - childWidth : newLeft;
final int paddingStart = isLayoutRtl ? getPaddingRight() : getPaddingLeft();
final int lpMargin = isLayoutRtl ? lp.rightMargin : lp.leftMargin;
final int startBound = paddingStart + lpMargin;
mSlideOffset = (float) (newStart - startBound) / mSlideRange;
if (mParallaxBy != 0) {
parallaxOtherViews(mSlideOffset);
}
if (lp.dimWhenOffset) {
dimChildView(mSlideableView, mSlideOffset, mSliderFadeColor);
}
dispatchOnPanelSlide(mSlideableView);
}
private void dimChildView(View v, float mag, int fadeColor) {
final LayoutParams lp = (LayoutParams) v.getLayoutParams();
if (mag > 0 && fadeColor != 0) {
final int baseAlpha = (fadeColor & 0xff000000) >>> 24;
int imag = (int) (baseAlpha * mag);
int color = imag << 24 | (fadeColor & 0xffffff);
if (lp.dimPaint == null) {
lp.dimPaint = new Paint();
}
lp.dimPaint.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_OVER));
if (v.getLayerType() != View.LAYER_TYPE_HARDWARE) {
v.setLayerType(View.LAYER_TYPE_HARDWARE, lp.dimPaint);
}
invalidateChildRegion(v);
} else if (v.getLayerType() != View.LAYER_TYPE_NONE) {
if (lp.dimPaint != null) {
lp.dimPaint.setColorFilter(null);
}
final DisableLayerRunnable dlr = new DisableLayerRunnable(v);
mPostedRunnables.add(dlr);
ViewCompat.postOnAnimation(this, dlr);
}
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
boolean result;
final int save = canvas.save();
if (mCanSlide && !lp.slideable && mSlideableView != null) {
// Clip against the slider; no sense drawing what will immediately be covered.
canvas.getClipBounds(mTmpRect);
if (isLayoutRtlSupport()) {
mTmpRect.left = Math.max(mTmpRect.left, mSlideableView.getRight());
} else {
mTmpRect.right = Math.min(mTmpRect.right, mSlideableView.getLeft());
}
canvas.clipRect(mTmpRect);
}
result = super.drawChild(canvas, child, drawingTime);
canvas.restoreToCount(save);
return result;
}
void invalidateChildRegion(View v) {
IMPL.invalidateChildRegion(this, v);
}
/**
* Smoothly animate mDraggingPane to the target X position within its range.
*
* @param slideOffset position to animate to
* @param velocity initial velocity in case of fling, or 0.
*/
boolean smoothSlideTo(float slideOffset, int velocity) {
if (!mCanSlide) {
// Nothing to do.
return false;
}
final boolean isLayoutRtl = isLayoutRtlSupport();
final LayoutParams lp = (LayoutParams) mSlideableView.getLayoutParams();
int x;
if (isLayoutRtl) {
int startBound = getPaddingRight() + lp.rightMargin;
int childWidth = mSlideableView.getWidth();
x = (int) (getWidth() - (startBound + slideOffset * mSlideRange + childWidth));
} else {
int startBound = getPaddingLeft() + lp.leftMargin;
x = (int) (startBound + slideOffset * mSlideRange);
}
if (mDragHelper.smoothSlideViewTo(mSlideableView, x, mSlideableView.getTop())) {
setAllChildrenVisible();
ViewCompat.postInvalidateOnAnimation(this);
return true;
}
return false;
}
@Override
public void computeScroll() {
if (mDragHelper.continueSettling(true)) {
if (!mCanSlide) {
mDragHelper.abort();
return;
}
ViewCompat.postInvalidateOnAnimation(this);
}
}
/**
* @deprecated Renamed to {@link #setShadowDrawableLeft(Drawable d)} to support LTR (left to
* right language) and {@link #setShadowDrawableRight(Drawable d)} to support RTL (right to left
* language) during opening/closing.
*
* @param d drawable to use as a shadow
*/
@Deprecated
public void setShadowDrawable(Drawable d) {
setShadowDrawableLeft(d);
}
/**
* Set a drawable to use as a shadow cast by the right pane onto the left pane
* during opening/closing.
*
* @param d drawable to use as a shadow
*/
public void setShadowDrawableLeft(@Nullable Drawable d) {
mShadowDrawableLeft = d;
}
/**
* Set a drawable to use as a shadow cast by the left pane onto the right pane
* during opening/closing to support right to left language.
*
* @param d drawable to use as a shadow
*/
public void setShadowDrawableRight(@Nullable Drawable d) {
mShadowDrawableRight = d;
}
/**
* Set a drawable to use as a shadow cast by the right pane onto the left pane
* during opening/closing.
*
* @param resId Resource ID of a drawable to use
* @deprecated Renamed to {@link #setShadowResourceLeft(int)} to support LTR (left to
* right language) and {@link #setShadowResourceRight(int)} to support RTL (right to left
* language) during opening/closing.
*/
@Deprecated
public void setShadowResource(@DrawableRes int resId) {
setShadowDrawable(getResources().getDrawable(resId));
}
/**
* Set a drawable to use as a shadow cast by the right pane onto the left pane
* during opening/closing.
*
* @param resId Resource ID of a drawable to use
*/
public void setShadowResourceLeft(int resId) {
setShadowDrawableLeft(ContextCompat.getDrawable(getContext(), resId));
}
/**
* Set a drawable to use as a shadow cast by the left pane onto the right pane
* during opening/closing to support right to left language.
*
* @param resId Resource ID of a drawable to use
*/
public void setShadowResourceRight(int resId) {
setShadowDrawableRight(ContextCompat.getDrawable(getContext(), resId));
}
@Override
public void draw(Canvas c) {
super.draw(c);
final boolean isLayoutRtl = isLayoutRtlSupport();
Drawable shadowDrawable;
if (isLayoutRtl) {
shadowDrawable = mShadowDrawableRight;
} else {
shadowDrawable = mShadowDrawableLeft;
}
final View shadowView = getChildCount() > 1 ? getChildAt(1) : null;
if (shadowView == null || shadowDrawable == null) {
// No need to draw a shadow if we don't have one.
return;
}
final int top = shadowView.getTop();
final int bottom = shadowView.getBottom();
final int shadowWidth = shadowDrawable.getIntrinsicWidth();
final int left;
final int right;
if (isLayoutRtlSupport()) {
left = shadowView.getRight();
right = left + shadowWidth;
} else {
right = shadowView.getLeft();
left = right - shadowWidth;
}
shadowDrawable.setBounds(left, top, right, bottom);
shadowDrawable.draw(c);
}
private void parallaxOtherViews(float slideOffset) {
final boolean isLayoutRtl = isLayoutRtlSupport();
final LayoutParams slideLp = (LayoutParams) mSlideableView.getLayoutParams();
final boolean dimViews = slideLp.dimWhenOffset
&& (isLayoutRtl ? slideLp.rightMargin : slideLp.leftMargin) <= 0;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View v = getChildAt(i);
if (v == mSlideableView) continue;
final int oldOffset = (int) ((1 - mParallaxOffset) * mParallaxBy);
mParallaxOffset = slideOffset;
final int newOffset = (int) ((1 - slideOffset) * mParallaxBy);
final int dx = oldOffset - newOffset;
v.offsetLeftAndRight(isLayoutRtl ? -dx : dx);
if (dimViews) {
dimChildView(v, isLayoutRtl ? mParallaxOffset - 1
: 1 - mParallaxOffset, mCoveredFadeColor);
}
}
}
/**
* Tests scrollability within child views of v given a delta of dx.
*
* @param v View to test for horizontal scrollability
* @param checkV Whether the view v passed should itself be checked for scrollability (true),
* or just its children (false).
* @param dx Delta scrolled in pixels
* @param x X coordinate of the active touch point
* @param y Y coordinate of the active touch point
* @return true if child views of v can be scrolled by delta of dx.
*/
protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
if (v instanceof ViewGroup) {
final ViewGroup group = (ViewGroup) v;
final int scrollX = v.getScrollX();
final int scrollY = v.getScrollY();
final int count = group.getChildCount();
// Count backwards - let topmost views consume scroll distance first.
for (int i = count - 1; i >= 0; i--) {
// TODO: Add versioned support here for transformed views.
// This will not work for transformed views in Honeycomb+
final View child = group.getChildAt(i);
if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight()
&& y + scrollY >= child.getTop() && y + scrollY < child.getBottom()
&& canScroll(child, true, dx, x + scrollX - child.getLeft(),
y + scrollY - child.getTop())) {
return true;
}
}
}
return checkV && v.canScrollHorizontally((isLayoutRtlSupport() ? dx : -dx));
}
boolean isDimmed(View child) {
if (child == null) {
return false;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
return mCanSlide && lp.dimWhenOffset && mSlideOffset > 0;
}
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
return new LayoutParams();
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof MarginLayoutParams
? new LayoutParams((MarginLayoutParams) p)
: new LayoutParams(p);
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams && super.checkLayoutParams(p);
}
@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.isOpen = isSlideable() ? isOpen() : mPreservedOpenState;
return ss;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
if (ss.isOpen) {
openPane();
} else {
closePane();
}
mPreservedOpenState = ss.isOpen;
}
private class DragHelperCallback extends ViewDragHelper.Callback {
DragHelperCallback() {
}
@Override
public boolean tryCaptureView(View child, int pointerId) {
if (mIsUnableToDrag) {
return false;
}
return ((LayoutParams) child.getLayoutParams()).slideable;
}
@Override
public void onViewDragStateChanged(int state) {
if (mDragHelper.getViewDragState() == ViewDragHelper.STATE_IDLE) {
if (mSlideOffset == 0) {
updateObscuredViewsVisibility(mSlideableView);
dispatchOnPanelClosed(mSlideableView);
mPreservedOpenState = false;
} else {
dispatchOnPanelOpened(mSlideableView);
mPreservedOpenState = true;
}
}
}
@Override
public void onViewCaptured(View capturedChild, int activePointerId) {
// Make all child views visible in preparation for sliding things around
setAllChildrenVisible();
}
@Override
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
onPanelDragged(left);
invalidate();
}
@Override
public void onViewReleased(View releasedChild, float xvel, float yvel) {
final LayoutParams lp = (LayoutParams) releasedChild.getLayoutParams();
int left;
if (isLayoutRtlSupport()) {
int startToRight = getPaddingRight() + lp.rightMargin;
if (xvel < 0 || (xvel == 0 && mSlideOffset > 0.5f)) {
startToRight += mSlideRange;
}
int childWidth = mSlideableView.getWidth();
left = getWidth() - startToRight - childWidth;
} else {
left = getPaddingLeft() + lp.leftMargin;
if (xvel > 0 || (xvel == 0 && mSlideOffset > 0.5f)) {
left += mSlideRange;
}
}
mDragHelper.settleCapturedViewAt(left, releasedChild.getTop());
invalidate();
}
@Override
public int getViewHorizontalDragRange(View child) {
return mSlideRange;
}
@Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
final LayoutParams lp = (LayoutParams) mSlideableView.getLayoutParams();
final int newLeft;
if (isLayoutRtlSupport()) {
int startBound = getWidth()
- (getPaddingRight() + lp.rightMargin + mSlideableView.getWidth());
int endBound = startBound - mSlideRange;
newLeft = Math.max(Math.min(left, startBound), endBound);
} else {
int startBound = getPaddingLeft() + lp.leftMargin;
int endBound = startBound + mSlideRange;
newLeft = Math.min(Math.max(left, startBound), endBound);
}
return newLeft;
}
@Override
public int clampViewPositionVertical(View child, int top, int dy) {
// Make sure we never move views vertically.
// This could happen if the child has less height than its parent.
return child.getTop();
}
@Override
public void onEdgeDragStarted(int edgeFlags, int pointerId) {
mDragHelper.captureChildView(mSlideableView, pointerId);
}
}
public static class LayoutParams extends ViewGroup.MarginLayoutParams {
private static final int[] ATTRS = new int[] {
android.R.attr.layout_weight
};
/**
* The weighted proportion of how much of the leftover space
* this child should consume after measurement.
*/
public float weight = 0;
/**
* True if this pane is the slideable pane in the layout.
*/
boolean slideable;
/**
* True if this view should be drawn dimmed
* when it's been offset from its default position.
*/
boolean dimWhenOffset;
Paint dimPaint;
public LayoutParams() {
super(MATCH_PARENT, MATCH_PARENT);
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(@NonNull android.view.ViewGroup.LayoutParams source) {
super(source);
}
public LayoutParams(@NonNull MarginLayoutParams source) {
super(source);
}
public LayoutParams(@NonNull LayoutParams source) {
super(source);
this.weight = source.weight;
}
public LayoutParams(@NonNull Context c, @Nullable AttributeSet attrs) {
super(c, attrs);
final TypedArray a = c.obtainStyledAttributes(attrs, ATTRS);
this.weight = a.getFloat(0, 0);
a.recycle();
}
}
static class SavedState extends AbsSavedState {
boolean isOpen;
SavedState(Parcelable superState) {
super(superState);
}
SavedState(Parcel in, ClassLoader loader) {
super(in, loader);
isOpen = in.readInt() != 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(isOpen ? 1 : 0);
}
public static final Creator<SavedState> CREATOR = new ClassLoaderCreator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel in, ClassLoader loader) {
return new SavedState(in, null);
}
@Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in, null);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
interface SlidingPanelLayoutImpl {
void invalidateChildRegion(SlidingPaneLayout parent, View child);
}
static class SlidingPanelLayoutImplBase implements SlidingPanelLayoutImpl {
@Override
public void invalidateChildRegion(SlidingPaneLayout parent, View child) {
ViewCompat.postInvalidateOnAnimation(parent, child.getLeft(), child.getTop(),
child.getRight(), child.getBottom());
}
}
@RequiresApi(16)
static class SlidingPanelLayoutImplJB extends SlidingPanelLayoutImplBase {
/*
* Private API hacks! Nasty! Bad!
*
* In Jellybean, some optimizations in the hardware UI renderer
* prevent a changed Paint on a View using a hardware layer from having
* the intended effect. This twiddles some internal bits on the view to force
* it to recreate the display list.
*/
private Method mGetDisplayList;
private Field mRecreateDisplayList;
SlidingPanelLayoutImplJB() {
try {
mGetDisplayList = View.class.getDeclaredMethod("getDisplayList", (Class[]) null);
} catch (NoSuchMethodException e) {
Log.e(TAG, "Couldn't fetch getDisplayList method; dimming won't work right.", e);
}
try {
mRecreateDisplayList = View.class.getDeclaredField("mRecreateDisplayList");
mRecreateDisplayList.setAccessible(true);
} catch (NoSuchFieldException e) {
Log.e(TAG, "Couldn't fetch mRecreateDisplayList field; dimming will be slow.", e);
}
}
@Override
public void invalidateChildRegion(SlidingPaneLayout parent, View child) {
if (mGetDisplayList != null && mRecreateDisplayList != null) {
try {
mRecreateDisplayList.setBoolean(child, true);
mGetDisplayList.invoke(child, (Object[]) null);
} catch (Exception e) {
Log.e(TAG, "Error refreshing display list state", e);
}
} else {
// Slow path. REALLY slow path. Let's hope we don't get here.
child.invalidate();
return;
}
super.invalidateChildRegion(parent, child);
}
}
@RequiresApi(17)
static class SlidingPanelLayoutImplJBMR1 extends SlidingPanelLayoutImplBase {
@Override
public void invalidateChildRegion(SlidingPaneLayout parent, View child) {
ViewCompat.setLayerPaint(child, ((LayoutParams) child.getLayoutParams()).dimPaint);
}
}
class AccessibilityDelegate extends AccessibilityDelegateCompat {
private final Rect mTmpRect = new Rect();
@Override
public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) {
final AccessibilityNodeInfoCompat superNode = AccessibilityNodeInfoCompat.obtain(info);
super.onInitializeAccessibilityNodeInfo(host, superNode);
copyNodeInfoNoChildren(info, superNode);
superNode.recycle();
info.setClassName(SlidingPaneLayout.class.getName());
info.setSource(host);
final ViewParent parent = ViewCompat.getParentForAccessibility(host);
if (parent instanceof View) {
info.setParent((View) parent);
}
// This is a best-approximation of addChildrenForAccessibility()
// that accounts for filtering.
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (!filter(child) && (child.getVisibility() == View.VISIBLE)) {
// Force importance to "yes" since we can't read the value.
ViewCompat.setImportantForAccessibility(
child, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES);
info.addChild(child);
}
}
}
@Override
public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
super.onInitializeAccessibilityEvent(host, event);
event.setClassName(SlidingPaneLayout.class.getName());
}
@Override
public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
AccessibilityEvent event) {
if (!filter(child)) {
return super.onRequestSendAccessibilityEvent(host, child, event);
}
return false;
}
public boolean filter(View child) {
return isDimmed(child);
}
/**
* This should really be in AccessibilityNodeInfoCompat, but there unfortunately
* seem to be a few elements that are not easily cloneable using the underlying API.
* Leave it private here as it's not general-purpose useful.
*/
private void copyNodeInfoNoChildren(AccessibilityNodeInfoCompat dest,
AccessibilityNodeInfoCompat src) {
final Rect rect = mTmpRect;
src.getBoundsInParent(rect);
dest.setBoundsInParent(rect);
src.getBoundsInScreen(rect);
dest.setBoundsInScreen(rect);
dest.setVisibleToUser(src.isVisibleToUser());
dest.setPackageName(src.getPackageName());
dest.setClassName(src.getClassName());
dest.setContentDescription(src.getContentDescription());
dest.setEnabled(src.isEnabled());
dest.setClickable(src.isClickable());
dest.setFocusable(src.isFocusable());
dest.setFocused(src.isFocused());
dest.setAccessibilityFocused(src.isAccessibilityFocused());
dest.setSelected(src.isSelected());
dest.setLongClickable(src.isLongClickable());
dest.addAction(src.getActions());
dest.setMovementGranularities(src.getMovementGranularities());
}
}
private class DisableLayerRunnable implements Runnable {
final View mChildView;
DisableLayerRunnable(View childView) {
mChildView = childView;
}
@Override
public void run() {
if (mChildView.getParent() == SlidingPaneLayout.this) {
mChildView.setLayerType(View.LAYER_TYPE_NONE, null);
invalidateChildRegion(mChildView);
}
mPostedRunnables.remove(this);
}
}
boolean isLayoutRtlSupport() {
return ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL;
}
}
| Remove SlidingPaneLayout API abstractions.
Bug: 75289452
Test: ./gradlew :slidingpanelayout:build
Change-Id: I0a92f17dc0d62a1aa63143e43f8f6baf525c26e3
| slidingpanelayout/src/main/java/androidx/slidingpanelayout/widget/SlidingPaneLayout.java | Remove SlidingPaneLayout API abstractions. | |
Java | apache-2.0 | c274cb530979f29ea3683539c29f32ed42423e0d | 0 | apache/solr,apache/solr,apache/solr,apache/solr,apache/solr | package org.apache.lucene.store.instantiated;
/**
* Copyright 2006 The Apache Software Foundation
*
* 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.
*/
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Comparator;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.FieldSelector;
import org.apache.lucene.index.*;
import org.apache.lucene.index.codecs.PerDocValues;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BitVector;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.Bits;
/**
* An InstantiatedIndexReader is not a snapshot in time, it is completely in
* sync with the latest commit to the store!
* <p>
* Consider using InstantiatedIndex as if it was immutable.
*/
public class InstantiatedIndexReader extends IndexReader {
private final InstantiatedIndex index;
private ReaderContext context = new AtomicReaderContext(this);
public InstantiatedIndexReader(InstantiatedIndex index) {
super();
this.index = index;
readerFinishedListeners = Collections.synchronizedSet(new HashSet<ReaderFinishedListener>());
}
/**
* @return always true.
*/
@Override
public boolean isOptimized() {
return true;
}
/**
* An InstantiatedIndexReader is not a snapshot in time, it is completely in
* sync with the latest commit to the store!
*
* @return output from {@link InstantiatedIndex#getVersion()} in associated instantiated index.
*/
@Override
public long getVersion() {
return index.getVersion();
}
@Override
public Directory directory() {
throw new UnsupportedOperationException();
}
/**
* An InstantiatedIndexReader is always current!
*
* Check whether this IndexReader is still using the current (i.e., most
* recently committed) version of the index. If a writer has committed any
* changes to the index since this reader was opened, this will return
* <code>false</code>, in which case you must open a new IndexReader in
* order to see the changes. See the description of the <a
* href="IndexWriter.html#autoCommit"><code>autoCommit</code></a> flag
* which controls when the {@link IndexWriter} actually commits changes to the
* index.
*
* @return always true
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
* @throws UnsupportedOperationException unless overridden in subclass
*/
@Override
public boolean isCurrent() throws IOException {
return true;
}
public InstantiatedIndex getIndex() {
return index;
}
@Override
public Bits getLiveDocs() {
return new Bits() {
public boolean get(int n) {
return !(index.getDeletedDocuments() != null && index.getDeletedDocuments().get(n))
&& !(uncommittedDeletedDocuments != null && uncommittedDeletedDocuments.get(n));
}
public int length() {
return maxDoc();
}
};
}
private BitVector uncommittedDeletedDocuments;
private Map<String,List<NormUpdate>> uncommittedNormsByFieldNameAndDocumentNumber = null;
private static class NormUpdate {
private int doc;
private byte value;
public NormUpdate(int doc, byte value) {
this.doc = doc;
this.value = value;
}
}
@Override
public int numDocs() {
// todo i suppose this value could be cached, but array#length and bitvector#count is fast.
int numDocs = getIndex().getDocumentsByNumber().length;
if (uncommittedDeletedDocuments != null) {
numDocs -= uncommittedDeletedDocuments.count();
}
if (index.getDeletedDocuments() != null) {
numDocs -= index.getDeletedDocuments().count();
}
return numDocs;
}
@Override
public int maxDoc() {
return getIndex().getDocumentsByNumber().length;
}
@Override
public boolean hasDeletions() {
return index.getDeletedDocuments() != null || uncommittedDeletedDocuments != null;
}
@Override
protected void doDelete(int docNum) throws IOException {
// dont delete if already deleted
if ((index.getDeletedDocuments() != null && index.getDeletedDocuments().get(docNum))
|| (uncommittedDeletedDocuments != null && uncommittedDeletedDocuments.get(docNum))) {
return;
}
if (uncommittedDeletedDocuments == null) {
uncommittedDeletedDocuments = new BitVector(maxDoc());
}
uncommittedDeletedDocuments.set(docNum);
}
@Override
protected void doUndeleteAll() throws IOException {
// todo: read/write lock
uncommittedDeletedDocuments = null;
// todo: read/write unlock
}
@Override
protected void doCommit(Map<String,String> commitUserData) throws IOException {
// todo: read/write lock
// 1. update norms
if (uncommittedNormsByFieldNameAndDocumentNumber != null) {
for (Map.Entry<String,List<NormUpdate>> e : uncommittedNormsByFieldNameAndDocumentNumber.entrySet()) {
byte[] norms = getIndex().getNormsByFieldNameAndDocumentNumber().get(e.getKey());
for (NormUpdate normUpdate : e.getValue()) {
norms[normUpdate.doc] = normUpdate.value;
}
}
uncommittedNormsByFieldNameAndDocumentNumber = null;
}
// 2. remove deleted documents
if (uncommittedDeletedDocuments != null) {
if (index.getDeletedDocuments() == null) {
index.setDeletedDocuments(uncommittedDeletedDocuments);
} else {
for (int d = 0; d< uncommittedDeletedDocuments.size(); d++) {
if (uncommittedDeletedDocuments.get(d)) {
index.getDeletedDocuments().set(d);
}
}
}
uncommittedDeletedDocuments = null;
}
// todo unlock read/writelock
}
@Override
protected void doClose() throws IOException {
// ignored
// todo perhaps release all associated instances?
}
@Override
public Collection<String> getFieldNames(FieldOption fieldOption) {
Set<String> fieldSet = new HashSet<String>();
for (FieldSetting fi : index.getFieldSettings().values()) {
if (fieldOption == IndexReader.FieldOption.ALL) {
fieldSet.add(fi.fieldName);
} else if (!fi.indexed && fieldOption == IndexReader.FieldOption.UNINDEXED) {
fieldSet.add(fi.fieldName);
} else if (fi.storePayloads && fieldOption == IndexReader.FieldOption.STORES_PAYLOADS) {
fieldSet.add(fi.fieldName);
} else if (fi.indexed && fieldOption == IndexReader.FieldOption.INDEXED) {
fieldSet.add(fi.fieldName);
} else if (fi.indexed && fi.storeTermVector == false && fieldOption == IndexReader.FieldOption.INDEXED_NO_TERMVECTOR) {
fieldSet.add(fi.fieldName);
} else if (fi.storeTermVector == true && fi.storePositionWithTermVector == false && fi.storeOffsetWithTermVector == false
&& fieldOption == IndexReader.FieldOption.TERMVECTOR) {
fieldSet.add(fi.fieldName);
} else if (fi.indexed && fi.storeTermVector && fieldOption == IndexReader.FieldOption.INDEXED_WITH_TERMVECTOR) {
fieldSet.add(fi.fieldName);
} else if (fi.storePositionWithTermVector && fi.storeOffsetWithTermVector == false
&& fieldOption == IndexReader.FieldOption.TERMVECTOR_WITH_POSITION) {
fieldSet.add(fi.fieldName);
} else if (fi.storeOffsetWithTermVector && fi.storePositionWithTermVector == false
&& fieldOption == IndexReader.FieldOption.TERMVECTOR_WITH_OFFSET) {
fieldSet.add(fi.fieldName);
} else if ((fi.storeOffsetWithTermVector && fi.storePositionWithTermVector)
&& fieldOption == IndexReader.FieldOption.TERMVECTOR_WITH_POSITION_OFFSET) {
fieldSet.add(fi.fieldName);
}
}
return fieldSet;
}
/**
* Return the {@link org.apache.lucene.document.Document} at the <code>n</code><sup>th</sup>
* position.
<p>
* <b>Warning!</b>
* The resulting document is the actual stored document instance
* and not a deserialized clone as retuned by an IndexReader
* over a {@link org.apache.lucene.store.Directory}.
* I.e., if you need to touch the document, clone it first!
* <p>
* This can also be seen as a feature for live changes of stored values,
* but be careful! Adding a field with an name unknown to the index
* or to a field with previously no stored values will make
* {@link org.apache.lucene.store.instantiated.InstantiatedIndexReader#getFieldNames(org.apache.lucene.index.IndexReader.FieldOption)}
* out of sync, causing problems for instance when merging the
* instantiated index to another index.
<p>
* This implementation ignores the field selector! All stored fields are always returned!
* <p>
*
* @param n document number
* @param fieldSelector ignored
* @return The stored fields of the {@link org.apache.lucene.document.Document} at the nth position
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*
* @see org.apache.lucene.document.Fieldable
* @see org.apache.lucene.document.FieldSelector
* @see org.apache.lucene.document.SetBasedFieldSelector
* @see org.apache.lucene.document.LoadFirstFieldSelector
*/
@Override
public Document document(int n, FieldSelector fieldSelector) throws CorruptIndexException, IOException {
return document(n);
}
/**
* Returns the stored fields of the <code>n</code><sup>th</sup>
* <code>Document</code> in this index.
* <p>
* <b>Warning!</b>
* The resulting document is the actual stored document instance
* and not a deserialized clone as retuned by an IndexReader
* over a {@link org.apache.lucene.store.Directory}.
* I.e., if you need to touch the document, clone it first!
* <p>
* This can also be seen as a feature for live changes of stored values,
* but be careful! Adding a field with an name unknown to the index
* or to a field with previously no stored values will make
* {@link org.apache.lucene.store.instantiated.InstantiatedIndexReader#getFieldNames(org.apache.lucene.index.IndexReader.FieldOption)}
* out of sync, causing problems for instance when merging the
* instantiated index to another index.
*
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*/
@Override
public Document document(int n) throws IOException {
return getIndex().getDocumentsByNumber()[n].getDocument();
}
/**
* never ever touch these values. it is the true values, unless norms have
* been touched.
*/
@Override
public byte[] norms(String field) throws IOException {
byte[] norms = getIndex().getNormsByFieldNameAndDocumentNumber().get(field);
if (norms == null) {
return new byte[0]; // todo a static final zero length attribute?
}
if (uncommittedNormsByFieldNameAndDocumentNumber != null) {
norms = norms.clone();
List<NormUpdate> updated = uncommittedNormsByFieldNameAndDocumentNumber.get(field);
if (updated != null) {
for (NormUpdate normUpdate : updated) {
norms[normUpdate.doc] = normUpdate.value;
}
}
}
return norms;
}
@Override
protected void doSetNorm(int doc, String field, byte value) throws IOException {
if (uncommittedNormsByFieldNameAndDocumentNumber == null) {
uncommittedNormsByFieldNameAndDocumentNumber = new HashMap<String,List<NormUpdate>>(getIndex().getNormsByFieldNameAndDocumentNumber().size());
}
List<NormUpdate> list = uncommittedNormsByFieldNameAndDocumentNumber.get(field);
if (list == null) {
list = new LinkedList<NormUpdate>();
uncommittedNormsByFieldNameAndDocumentNumber.put(field, list);
}
list.add(new NormUpdate(doc, value));
}
@Override
public int docFreq(Term t) throws IOException {
InstantiatedTerm term = getIndex().findTerm(t);
if (term == null) {
return 0;
} else {
return term.getAssociatedDocuments().length;
}
}
@Override
public Fields fields() {
if (getIndex().getOrderedTerms().length == 0) {
return null;
}
return new Fields() {
@Override
public FieldsEnum iterator() {
final InstantiatedTerm[] orderedTerms = getIndex().getOrderedTerms();
return new FieldsEnum() {
int upto = -1;
String currentField;
@Override
public String next() {
do {
upto++;
if (upto >= orderedTerms.length) {
return null;
}
} while(orderedTerms[upto].field().equals(currentField));
currentField = orderedTerms[upto].field();
return currentField;
}
@Override
public TermsEnum terms() {
return new InstantiatedTermsEnum(orderedTerms, upto, currentField);
}
};
}
@Override
public Terms terms(final String field) {
final InstantiatedTerm[] orderedTerms = getIndex().getOrderedTerms();
int i = Arrays.binarySearch(orderedTerms, new Term(field), InstantiatedTerm.termComparator);
if (i < 0) {
i = -i - 1;
}
if (i >= orderedTerms.length || !orderedTerms[i].field().equals(field)) {
// field does not exist
return null;
}
final int startLoc = i;
// TODO: heavy to do this here; would be better to
// do it up front & cache
long sum = 0;
int upto = i;
while(upto < orderedTerms.length && orderedTerms[i].field().equals(field)) {
sum += orderedTerms[i].getTotalTermFreq();
upto++;
}
final long sumTotalTermFreq = sum;
return new Terms() {
@Override
public TermsEnum iterator() {
return new InstantiatedTermsEnum(orderedTerms, startLoc, field);
}
@Override
public long getSumTotalTermFreq() {
return sumTotalTermFreq;
}
@Override
public Comparator<BytesRef> getComparator() {
return BytesRef.getUTF8SortedAsUnicodeComparator();
}
};
}
};
}
@Override
public ReaderContext getTopReaderContext() {
return context;
}
@Override
public TermFreqVector[] getTermFreqVectors(int docNumber) throws IOException {
InstantiatedDocument doc = getIndex().getDocumentsByNumber()[docNumber];
if (doc.getVectorSpace() == null) {
return null;
}
TermFreqVector[] ret = new TermFreqVector[doc.getVectorSpace().size()];
Iterator<String> it = doc.getVectorSpace().keySet().iterator();
for (int i = 0; i < ret.length; i++) {
ret[i] = new InstantiatedTermPositionVector(getIndex().getDocumentsByNumber()[docNumber], it.next());
}
return ret;
}
@Override
public TermFreqVector getTermFreqVector(int docNumber, String field) throws IOException {
InstantiatedDocument doc = getIndex().getDocumentsByNumber()[docNumber];
if (doc.getVectorSpace() == null || doc.getVectorSpace().get(field) == null) {
return null;
} else {
return new InstantiatedTermPositionVector(doc, field);
}
}
@Override
public void getTermFreqVector(int docNumber, String field, TermVectorMapper mapper) throws IOException {
InstantiatedDocument doc = getIndex().getDocumentsByNumber()[docNumber];
if (doc.getVectorSpace() != null && doc.getVectorSpace().get(field) == null) {
List<InstantiatedTermDocumentInformation> tv = doc.getVectorSpace().get(field);
mapper.setExpectations(field, tv.size(), true, true);
for (InstantiatedTermDocumentInformation tdi : tv) {
mapper.map(tdi.getTerm().getTerm().bytes(), tdi.getTermPositions().length, tdi.getTermOffsets(), tdi.getTermPositions());
}
}
}
@Override
public void getTermFreqVector(int docNumber, TermVectorMapper mapper) throws IOException {
InstantiatedDocument doc = getIndex().getDocumentsByNumber()[docNumber];
for (Map.Entry<String, List<InstantiatedTermDocumentInformation>> e : doc.getVectorSpace().entrySet()) {
mapper.setExpectations(e.getKey(), e.getValue().size(), true, true);
for (InstantiatedTermDocumentInformation tdi : e.getValue()) {
mapper.map(tdi.getTerm().getTerm().bytes(), tdi.getTermPositions().length, tdi.getTermOffsets(), tdi.getTermPositions());
}
}
}
@Override
public PerDocValues perDocValues() throws IOException {
return null;
}
}
| lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedIndexReader.java | package org.apache.lucene.store.instantiated;
/**
* Copyright 2006 The Apache Software Foundation
*
* 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.
*/
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Comparator;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.FieldSelector;
import org.apache.lucene.index.*;
import org.apache.lucene.index.codecs.PerDocValues;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BitVector;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.Bits;
/**
* An InstantiatedIndexReader is not a snapshot in time, it is completely in
* sync with the latest commit to the store!
* <p>
* Consider using InstantiatedIndex as if it was immutable.
*/
public class InstantiatedIndexReader extends IndexReader {
private final InstantiatedIndex index;
private ReaderContext context = new AtomicReaderContext(this);
public InstantiatedIndexReader(InstantiatedIndex index) {
super();
this.index = index;
readerFinishedListeners = Collections.synchronizedSet(new HashSet<ReaderFinishedListener>());
}
/**
* @return always true.
*/
@Override
public boolean isOptimized() {
return true;
}
/**
* An InstantiatedIndexReader is not a snapshot in time, it is completely in
* sync with the latest commit to the store!
*
* @return output from {@link InstantiatedIndex#getVersion()} in associated instantiated index.
*/
@Override
public long getVersion() {
return index.getVersion();
}
@Override
public Directory directory() {
throw new UnsupportedOperationException();
}
/**
* An InstantiatedIndexReader is always current!
*
* Check whether this IndexReader is still using the current (i.e., most
* recently committed) version of the index. If a writer has committed any
* changes to the index since this reader was opened, this will return
* <code>false</code>, in which case you must open a new IndexReader in
* order to see the changes. See the description of the <a
* href="IndexWriter.html#autoCommit"><code>autoCommit</code></a> flag
* which controls when the {@link IndexWriter} actually commits changes to the
* index.
*
* @return always true
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
* @throws UnsupportedOperationException unless overridden in subclass
*/
@Override
public boolean isCurrent() throws IOException {
return true;
}
public InstantiatedIndex getIndex() {
return index;
}
@Override
public Bits getLiveDocs() {
return new Bits() {
public boolean get(int n) {
return !(index.getDeletedDocuments() != null && index.getDeletedDocuments().get(n))
&& !(uncommittedDeletedDocuments != null && uncommittedDeletedDocuments.get(n));
}
public int length() {
return maxDoc();
}
};
}
private BitVector uncommittedDeletedDocuments;
private Map<String,List<NormUpdate>> uncommittedNormsByFieldNameAndDocumentNumber = null;
private static class NormUpdate {
private int doc;
private byte value;
public NormUpdate(int doc, byte value) {
this.doc = doc;
this.value = value;
}
}
@Override
public int numDocs() {
// todo i suppose this value could be cached, but array#length and bitvector#count is fast.
int numDocs = getIndex().getDocumentsByNumber().length;
if (uncommittedDeletedDocuments != null) {
numDocs -= uncommittedDeletedDocuments.count();
}
if (index.getDeletedDocuments() != null) {
numDocs -= index.getDeletedDocuments().count();
}
return numDocs;
}
@Override
public int maxDoc() {
return getIndex().getDocumentsByNumber().length;
}
@Override
public boolean hasDeletions() {
return index.getDeletedDocuments() != null || uncommittedDeletedDocuments != null;
}
@Override
protected void doDelete(int docNum) throws IOException {
// dont delete if already deleted
if ((index.getDeletedDocuments() != null && index.getDeletedDocuments().get(docNum))
|| (uncommittedDeletedDocuments != null && uncommittedDeletedDocuments.get(docNum))) {
return;
}
if (uncommittedDeletedDocuments == null) {
uncommittedDeletedDocuments = new BitVector(maxDoc());
}
uncommittedDeletedDocuments.set(docNum);
}
@Override
protected void doUndeleteAll() throws IOException {
// todo: read/write lock
uncommittedDeletedDocuments = null;
// todo: read/write unlock
}
@Override
protected void doCommit(Map<String,String> commitUserData) throws IOException {
// todo: read/write lock
// 1. update norms
if (uncommittedNormsByFieldNameAndDocumentNumber != null) {
for (Map.Entry<String,List<NormUpdate>> e : uncommittedNormsByFieldNameAndDocumentNumber.entrySet()) {
byte[] norms = getIndex().getNormsByFieldNameAndDocumentNumber().get(e.getKey());
for (NormUpdate normUpdate : e.getValue()) {
norms[normUpdate.doc] = normUpdate.value;
}
}
uncommittedNormsByFieldNameAndDocumentNumber = null;
}
// 2. remove deleted documents
if (uncommittedDeletedDocuments != null) {
if (index.getDeletedDocuments() == null) {
index.setDeletedDocuments(uncommittedDeletedDocuments);
} else {
for (int d = 0; d< uncommittedDeletedDocuments.size(); d++) {
if (uncommittedDeletedDocuments.get(d)) {
index.getDeletedDocuments().set(d);
}
}
}
uncommittedDeletedDocuments = null;
}
// todo unlock read/writelock
}
@Override
protected void doClose() throws IOException {
// ignored
// todo perhaps release all associated instances?
}
@Override
public Collection<String> getFieldNames(FieldOption fieldOption) {
Set<String> fieldSet = new HashSet<String>();
for (FieldSetting fi : index.getFieldSettings().values()) {
if (fieldOption == IndexReader.FieldOption.ALL) {
fieldSet.add(fi.fieldName);
} else if (!fi.indexed && fieldOption == IndexReader.FieldOption.UNINDEXED) {
fieldSet.add(fi.fieldName);
} else if (fi.storePayloads && fieldOption == IndexReader.FieldOption.STORES_PAYLOADS) {
fieldSet.add(fi.fieldName);
} else if (fi.indexed && fieldOption == IndexReader.FieldOption.INDEXED) {
fieldSet.add(fi.fieldName);
} else if (fi.indexed && fi.storeTermVector == false && fieldOption == IndexReader.FieldOption.INDEXED_NO_TERMVECTOR) {
fieldSet.add(fi.fieldName);
} else if (fi.storeTermVector == true && fi.storePositionWithTermVector == false && fi.storeOffsetWithTermVector == false
&& fieldOption == IndexReader.FieldOption.TERMVECTOR) {
fieldSet.add(fi.fieldName);
} else if (fi.indexed && fi.storeTermVector && fieldOption == IndexReader.FieldOption.INDEXED_WITH_TERMVECTOR) {
fieldSet.add(fi.fieldName);
} else if (fi.storePositionWithTermVector && fi.storeOffsetWithTermVector == false
&& fieldOption == IndexReader.FieldOption.TERMVECTOR_WITH_POSITION) {
fieldSet.add(fi.fieldName);
} else if (fi.storeOffsetWithTermVector && fi.storePositionWithTermVector == false
&& fieldOption == IndexReader.FieldOption.TERMVECTOR_WITH_OFFSET) {
fieldSet.add(fi.fieldName);
} else if ((fi.storeOffsetWithTermVector && fi.storePositionWithTermVector)
&& fieldOption == IndexReader.FieldOption.TERMVECTOR_WITH_POSITION_OFFSET) {
fieldSet.add(fi.fieldName);
}
}
return fieldSet;
}
/**
* Return the {@link org.apache.lucene.document.Document} at the <code>n</code><sup>th</sup>
* position.
<p>
* <b>Warning!</b>
* The resulting document is the actual stored document instance
* and not a deserialized clone as retuned by an IndexReader
* over a {@link org.apache.lucene.store.Directory}.
* I.e., if you need to touch the document, clone it first!
* <p>
* This can also be seen as a feature for live changes of stored values,
* but be careful! Adding a field with an name unknown to the index
* or to a field with previously no stored values will make
* {@link org.apache.lucene.store.instantiated.InstantiatedIndexReader#getFieldNames(org.apache.lucene.index.IndexReader.FieldOption)}
* out of sync, causing problems for instance when merging the
* instantiated index to another index.
<p>
* This implementation ignores the field selector! All stored fields are always returned!
* <p>
*
* @param n document number
* @param fieldSelector ignored
* @return The stored fields of the {@link org.apache.lucene.document.Document} at the nth position
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*
* @see org.apache.lucene.document.Fieldable
* @see org.apache.lucene.document.FieldSelector
* @see org.apache.lucene.document.SetBasedFieldSelector
* @see org.apache.lucene.document.LoadFirstFieldSelector
*/
@Override
public Document document(int n, FieldSelector fieldSelector) throws CorruptIndexException, IOException {
return document(n);
}
/**
* Returns the stored fields of the <code>n</code><sup>th</sup>
* <code>Document</code> in this index.
* <p>
* <b>Warning!</b>
* The resulting document is the actual stored document instance
* and not a deserialized clone as retuned by an IndexReader
* over a {@link org.apache.lucene.store.Directory}.
* I.e., if you need to touch the document, clone it first!
* <p>
* This can also be seen as a feature for live changes of stored values,
* but be careful! Adding a field with an name unknown to the index
* or to a field with previously no stored values will make
* {@link org.apache.lucene.store.instantiated.InstantiatedIndexReader#getFieldNames(org.apache.lucene.index.IndexReader.FieldOption)}
* out of sync, causing problems for instance when merging the
* instantiated index to another index.
*
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*/
@Override
public Document document(int n) throws IOException {
return getIndex().getDocumentsByNumber()[n].getDocument();
}
/**
* never ever touch these values. it is the true values, unless norms have
* been touched.
*/
@Override
public byte[] norms(String field) throws IOException {
byte[] norms = getIndex().getNormsByFieldNameAndDocumentNumber().get(field);
if (norms == null) {
return new byte[0]; // todo a static final zero length attribute?
}
if (uncommittedNormsByFieldNameAndDocumentNumber != null) {
norms = norms.clone();
List<NormUpdate> updated = uncommittedNormsByFieldNameAndDocumentNumber.get(field);
if (updated != null) {
for (NormUpdate normUpdate : updated) {
norms[normUpdate.doc] = normUpdate.value;
}
}
}
return norms;
}
@Override
protected void doSetNorm(int doc, String field, byte value) throws IOException {
if (uncommittedNormsByFieldNameAndDocumentNumber == null) {
uncommittedNormsByFieldNameAndDocumentNumber = new HashMap<String,List<NormUpdate>>(getIndex().getNormsByFieldNameAndDocumentNumber().size());
}
List<NormUpdate> list = uncommittedNormsByFieldNameAndDocumentNumber.get(field);
if (list == null) {
list = new LinkedList<NormUpdate>();
uncommittedNormsByFieldNameAndDocumentNumber.put(field, list);
}
list.add(new NormUpdate(doc, value));
}
@Override
public int docFreq(Term t) throws IOException {
InstantiatedTerm term = getIndex().findTerm(t);
if (term == null) {
return 0;
} else {
return term.getAssociatedDocuments().length;
}
}
@Override
public Fields fields() {
if (getIndex().getOrderedTerms().length == 0) {
return null;
}
return new Fields() {
@Override
public FieldsEnum iterator() {
final InstantiatedTerm[] orderedTerms = getIndex().getOrderedTerms();
return new FieldsEnum() {
int upto = -1;
String currentField;
@Override
public String next() {
do {
upto++;
if (upto >= orderedTerms.length) {
return null;
}
} while(orderedTerms[upto].field().equals(currentField));
currentField = orderedTerms[upto].field();
return currentField;
}
@Override
public TermsEnum terms() {
return new InstantiatedTermsEnum(orderedTerms, upto, currentField);
}
};
}
@Override
public Terms terms(final String field) {
final InstantiatedTerm[] orderedTerms = getIndex().getOrderedTerms();
int i = Arrays.binarySearch(orderedTerms, new Term(field), InstantiatedTerm.termComparator);
if (i < 0) {
i = -i - 1;
}
if (i >= orderedTerms.length || !orderedTerms[i].field().equals(field)) {
// field does not exist
return null;
}
final int startLoc = i;
// TODO: heavy to do this here; would be better to
// do it up front & cache
long sum = 0;
int upto = i;
while(upto < orderedTerms.length && orderedTerms[i].equals(field)) {
sum += orderedTerms[i].getTotalTermFreq();
upto++;
}
final long sumTotalTermFreq = sum;
return new Terms() {
@Override
public TermsEnum iterator() {
return new InstantiatedTermsEnum(orderedTerms, startLoc, field);
}
@Override
public long getSumTotalTermFreq() {
return sumTotalTermFreq;
}
@Override
public Comparator<BytesRef> getComparator() {
return BytesRef.getUTF8SortedAsUnicodeComparator();
}
};
}
};
}
@Override
public ReaderContext getTopReaderContext() {
return context;
}
@Override
public TermFreqVector[] getTermFreqVectors(int docNumber) throws IOException {
InstantiatedDocument doc = getIndex().getDocumentsByNumber()[docNumber];
if (doc.getVectorSpace() == null) {
return null;
}
TermFreqVector[] ret = new TermFreqVector[doc.getVectorSpace().size()];
Iterator<String> it = doc.getVectorSpace().keySet().iterator();
for (int i = 0; i < ret.length; i++) {
ret[i] = new InstantiatedTermPositionVector(getIndex().getDocumentsByNumber()[docNumber], it.next());
}
return ret;
}
@Override
public TermFreqVector getTermFreqVector(int docNumber, String field) throws IOException {
InstantiatedDocument doc = getIndex().getDocumentsByNumber()[docNumber];
if (doc.getVectorSpace() == null || doc.getVectorSpace().get(field) == null) {
return null;
} else {
return new InstantiatedTermPositionVector(doc, field);
}
}
@Override
public void getTermFreqVector(int docNumber, String field, TermVectorMapper mapper) throws IOException {
InstantiatedDocument doc = getIndex().getDocumentsByNumber()[docNumber];
if (doc.getVectorSpace() != null && doc.getVectorSpace().get(field) == null) {
List<InstantiatedTermDocumentInformation> tv = doc.getVectorSpace().get(field);
mapper.setExpectations(field, tv.size(), true, true);
for (InstantiatedTermDocumentInformation tdi : tv) {
mapper.map(tdi.getTerm().getTerm().bytes(), tdi.getTermPositions().length, tdi.getTermOffsets(), tdi.getTermPositions());
}
}
}
@Override
public void getTermFreqVector(int docNumber, TermVectorMapper mapper) throws IOException {
InstantiatedDocument doc = getIndex().getDocumentsByNumber()[docNumber];
for (Map.Entry<String, List<InstantiatedTermDocumentInformation>> e : doc.getVectorSpace().entrySet()) {
mapper.setExpectations(e.getKey(), e.getValue().size(), true, true);
for (InstantiatedTermDocumentInformation tdi : e.getValue()) {
mapper.map(tdi.getTerm().getTerm().bytes(), tdi.getTermPositions().length, tdi.getTermOffsets(), tdi.getTermPositions());
}
}
}
@Override
public PerDocValues perDocValues() throws IOException {
return null;
}
}
| fixed previous commit
git-svn-id: 308d55f399f3bd9aa0560a10e81a003040006c48@1144304 13f79535-47bb-0310-9956-ffa450edef68
| lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedIndexReader.java | fixed previous commit | |
Java | apache-2.0 | d55bdd72633849ce9ded2bfc5606990ea74624db | 0 | joskarthic/chatsecure,eighthave/ChatSecureAndroid,ChatSecure/ChatSecureAndroid,guardianproject/ChatSecureAndroid,prive/prive-android,OnlyInAmerica/ChatSecureAndroid,kden/ChatSecureAndroid,h2ri/ChatSecureAndroid,Heart2009/ChatSecureAndroid,prembasumatary/ChatSecureAndroid,eighthave/ChatSecureAndroid,kden/ChatSecureAndroid,guardianproject/ChatSecureAndroid,prive/prive-android,n8fr8/AwesomeApp,10045125/ChatSecureAndroid,31H0B1eV/ChatSecureAndroid,OnlyInAmerica/ChatSecureAndroid,maheshwarishivam/ChatSecureAndroid,prive/prive-android,bonashen/ChatSecureAndroid,kden/ChatSecureAndroid,h2ri/ChatSecureAndroid,n8fr8/ChatSecureAndroid,n8fr8/AwesomeApp,maheshwarishivam/ChatSecureAndroid,n8fr8/ChatSecureAndroid,Heart2009/ChatSecureAndroid,eighthave/ChatSecureAndroid,bonashen/ChatSecureAndroid,ChatSecure/ChatSecureAndroid,OnlyInAmerica/ChatSecureAndroid,n8fr8/AwesomeApp,n8fr8/ChatSecureAndroid,prive/prive-android,joskarthic/chatsecure,10045125/ChatSecureAndroid,joskarthic/chatsecure,h2ri/ChatSecureAndroid,anvayarai/my-ChatSecure,31H0B1eV/ChatSecureAndroid,anvayarai/my-ChatSecure,OnlyInAmerica/ChatSecureAndroid,anvayarai/my-ChatSecure,10045125/ChatSecureAndroid,Heart2009/ChatSecureAndroid,ChatSecure/ChatSecureAndroid,ChatSecure/ChatSecureAndroid,prembasumatary/ChatSecureAndroid,prembasumatary/ChatSecureAndroid,31H0B1eV/ChatSecureAndroid,maheshwarishivam/ChatSecureAndroid,guardianproject/ChatSecureAndroid,bonashen/ChatSecureAndroid | package info.guardianproject.otr.app.im.plugin.xmpp;
import info.guardianproject.otr.app.im.app.ImApp;
import info.guardianproject.otr.app.im.engine.Address;
import info.guardianproject.otr.app.im.engine.ChatGroupManager;
import info.guardianproject.otr.app.im.engine.ChatSession;
import info.guardianproject.otr.app.im.engine.ChatSessionManager;
import info.guardianproject.otr.app.im.engine.Contact;
import info.guardianproject.otr.app.im.engine.ContactList;
import info.guardianproject.otr.app.im.engine.ContactListListener;
import info.guardianproject.otr.app.im.engine.ContactListManager;
import info.guardianproject.otr.app.im.engine.ImConnection;
import info.guardianproject.otr.app.im.engine.ImErrorInfo;
import info.guardianproject.otr.app.im.engine.ImException;
import info.guardianproject.otr.app.im.engine.LoginInfo;
import info.guardianproject.otr.app.im.engine.Message;
import info.guardianproject.otr.app.im.engine.Presence;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.RosterGroup;
import org.jivesoftware.smack.RosterListener;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence.Mode;
import org.jivesoftware.smack.packet.Presence.Type;
import org.jivesoftware.smack.proxy.ProxyInfo;
import org.jivesoftware.smack.proxy.ProxyInfo.ProxyType;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Parcel;
import android.preference.PreferenceManager;
import android.util.Log;
public class XmppConnection extends ImConnection {
private final static String TAG = "XmppConnection";
private XmppContactList mContactListManager;
private Contact mUser;
// watch out, this is a different XMPPConnection class than XmppConnection! ;)
private MyXMPPConnection mConnection;
private XmppChatSessionManager mSessionManager;
private ConnectionConfiguration mConfig;
private boolean mNeedReconnect;
private LoginInfo mLoginInfo;
private boolean mRetryLogin;
private Executor mExecutor;
private ProxyInfo mProxyInfo = null;
private final static int XMPP_DEFAULT_PORT = 5222;
public XmppConnection(Context context) {
super(context);
Log.w(TAG, "created");
//ReconnectionManager.activate();
//SmackConfiguration.setKeepAliveInterval(-1);
mExecutor = Executors.newSingleThreadExecutor();
}
public void sendMessage(org.jivesoftware.smack.packet.Message msg) {
mConnection.sendPacket(msg);
}
@Override
protected void doUpdateUserPresenceAsync(Presence presence) {
String statusText = presence.getStatusText();
Type type = Type.available;
Mode mode = Mode.available;
int priority = 20;
if (presence.getStatus() == Presence.AWAY) {
priority = 10;
mode = Mode.away;
}
else if (presence.getStatus() == Presence.IDLE) {
priority = 15;
mode = Mode.away;
}
else if (presence.getStatus() == Presence.DO_NOT_DISTURB) {
priority = 5;
mode = Mode.dnd;
}
else if (presence.getStatus() == Presence.OFFLINE) {
priority = 0;
type = Type.unavailable;
statusText = "Offline";
}
org.jivesoftware.smack.packet.Presence packet =
new org.jivesoftware.smack.packet.Presence(type, statusText, priority, mode);
mConnection.sendPacket(packet);
mUserPresence = presence;
notifyUserPresenceUpdated();
}
@Override
public int getCapability() {
// TODO chat groups
return 0;
}
@Override
public ChatGroupManager getChatGroupManager() {
// TODO chat groups
return null;
}
@Override
public ChatSessionManager getChatSessionManager() {
mSessionManager = new XmppChatSessionManager();
return mSessionManager;
}
@Override
public ContactListManager getContactListManager() {
mContactListManager = new XmppContactList();
return mContactListManager;
}
@Override
public Contact getLoginUser() {
return mUser;
}
@Override
public HashMap<String, String> getSessionContext() {
return null;
}
@Override
public int[] getSupportedPresenceStatus() {
return new int[] {
Presence.AVAILABLE,
Presence.AWAY,
Presence.IDLE,
Presence.OFFLINE,
Presence.DO_NOT_DISTURB,
};
}
@Override
public void loginAsync(final LoginInfo loginInfo, boolean retry) {
mLoginInfo = loginInfo;
mRetryLogin = retry;
mExecutor.execute(new Runnable() {
@Override
public void run() {
do_login();
}
});
}
private void do_login() {
if (mConnection != null) {
setState(getState(), new ImErrorInfo(ImErrorInfo.CANT_CONNECT_TO_SERVER, "still trying..."));
return;
}
Log.i(TAG, "logging in " + mLoginInfo.getUserName());
mNeedReconnect = true;
setState(LOGGING_IN, null);
mUserPresence = new Presence(Presence.AVAILABLE, "Online", null, null, Presence.CLIENT_TYPE_DEFAULT);
String username = mLoginInfo.getUserName();
String []comps = username.split("@");
if (comps.length != 2) {
disconnected(new ImErrorInfo(ImErrorInfo.INVALID_USERNAME, "username should be user@host"));
mRetryLogin = false;
mNeedReconnect = false;
return;
}
try {
String sUsername = java.net.URLDecoder.decode(comps[0]);
String serverInfo[] = comps[1].split(":");
if (serverInfo.length == 0)
throw new XMPPException("invalid host setting");
String serverHost = serverInfo[0];
int serverPort = Integer.parseInt(serverInfo[1]);
initConnection(serverHost, serverPort, sUsername, mLoginInfo.getPassword(), "Gibberbot");
} catch (XMPPException e) {
Log.e(TAG, "login failed", e);
mConnection = null;
ImErrorInfo info = new ImErrorInfo(ImErrorInfo.CANT_CONNECT_TO_SERVER, e.getMessage());
if (e.getMessage().contains("not-authorized")) {
Log.w(TAG, "not authorized - will not retry");
info = new ImErrorInfo(ImErrorInfo.INVALID_USERNAME, "invalid user/password");
disconnected(info);
mRetryLogin = false;
}
else if (mRetryLogin) {
Log.w(TAG, "will retry");
setState(LOGGING_IN, info);
}
else {
Log.w(TAG, "will not retry");
mConnection = null;
disconnected(info);
}
return;
} finally {
mNeedReconnect = false;
}
username = username.split(":")[0];//remove any port mentions
mUser = new Contact(new XmppAddress(username, username), username);
setState(LOGGED_IN, null);
Log.i(TAG, "logged in");
}
public void setProxy (String type, String host, int port)
{
if (type == null)
{
mProxyInfo = ProxyInfo.forNoProxy();
}
else
{
ProxyInfo.ProxyType pType = ProxyType.valueOf(type);
mProxyInfo = new ProxyInfo(pType, host, port,"","");
}
}
private void initConnection(String serverHost, int serverPort, String login, String password, String resource) throws XMPPException {
// TODO these booleans should be set in the preferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
boolean doTLS = prefs.getBoolean("pref_security_tls", true);
boolean doSRV = prefs.getBoolean("pref_security_do_srv", false);
boolean doCertVerification = prefs.getBoolean("pref_security_tls_very", true);
Log.i(TAG, "TLS required? " + doTLS);
Log.i(TAG, "Do SRV check? " + doSRV);
Log.i(TAG, "cert verification? " + doCertVerification);
boolean allowSelfSignedCerts = !doCertVerification;
boolean doVerifyDomain = doCertVerification;
if (mProxyInfo == null)
mProxyInfo = ProxyInfo.forNoProxy();
// TODO how should we handle special ConnectionConfiguration for hosts like google?
//we want to make it easy for users - maybe this shouldn't be here though
if (serverHost.equals("gmail.com") || serverHost.equals("googlemail.com")) {
// Google only supports a certain configuration for XMPP:
// http://code.google.com/apis/talk/open_communications.html
// only use the @host.com serverHost name so that ConnectionConfiguration does a DNS SRV lookup
// is always talk.google.com
mConfig = new ConnectionConfiguration("talk.google.com", 5222, serverHost, mProxyInfo);
mConfig.setSecurityMode(SecurityMode.required); // Gtalk requires TLS always
mConfig.setSASLAuthenticationEnabled(true);
// Google only supports SASL/PLAIN so disable the rest just in case
SASLAuthentication.supportSASLMechanism("PLAIN", 0);
SASLAuthentication.unsupportSASLMechanism("DIGEST-MD5");
SASLAuthentication.unregisterSASLMechanism("KERBEROS_V4"); // never supported
if (login.indexOf("@")==-1)
login = login + "@" + serverHost;
mConfig.setVerifyRootCAEnabled(false); //TODO we have to disable this for now with Gmail
mConfig.setVerifyChainEnabled(doCertVerification); //but we still can verify the chain
mConfig.setExpiredCertificatesCheckEnabled(doCertVerification);
mConfig.setNotMatchingDomainCheckEnabled(doVerifyDomain);
} else {
// TODO test first only using serverHost to use the DNS SRV lookup, otherwise try all the saved settings
// set the priority of auth methods, 0 being the first tried
if (doSRV)
mConfig = new ConnectionConfiguration(serverHost, mProxyInfo);
else
mConfig = new ConnectionConfiguration(serverHost, serverPort, serverHost, mProxyInfo);
if (doTLS)
mConfig.setSecurityMode(SecurityMode.required);
else
mConfig.setSecurityMode(SecurityMode.enabled);
mConfig.setSASLAuthenticationEnabled(true);
//set at equal priority
SASLAuthentication.supportSASLMechanism("PLAIN", 0);
SASLAuthentication.supportSASLMechanism("DIGEST-MD5", 1);
mConfig.setVerifyChainEnabled(doCertVerification);
mConfig.setVerifyRootCAEnabled(doCertVerification);
mConfig.setExpiredCertificatesCheckEnabled(doCertVerification);
mConfig.setNotMatchingDomainCheckEnabled(doVerifyDomain);
}
// Android doesn't support the default "jks" Java Key Store, it uses "bks" instead
mConfig.setTruststoreType("BKS");
mConfig.setTruststorePath("/system/etc/security/cacerts.bks");
// this should probably be set to our own, if we are going to save self-signed certs
//mConfig.setKeystoreType("bks");
//mConfig.setKeystorePath("/system/etc/security/cacerts.bks");
if (allowSelfSignedCerts) {
Log.i(TAG, "allowing self-signed certs");
mConfig.setSelfSignedCertificateEnabled(true);
}
//reconnect please
mConfig.setReconnectionAllowed(true);
mConfig.setRosterLoadedAtLogin(true);
mConfig.setSendPresence(true);
Log.i(TAG, "ConnnectionConfiguration.getHost: " + mConfig.getHost() + " getPort: " + mConfig.getPort() + " getServiceName: " + mConfig.getServiceName());
mConnection = new MyXMPPConnection(mConfig);
mConnection.connect();
Log.i(TAG,"is secure connection? " + mConnection.isSecureConnection());
Log.i(TAG,"is using TLS? " + mConnection.isUsingTLS());
mConnection.addPacketListener(new PacketListener() {
@Override
public void processPacket(Packet packet) {
org.jivesoftware.smack.packet.Message smackMessage = (org.jivesoftware.smack.packet.Message) packet;
Message rec = new Message(smackMessage.getBody());
String address = parseAddressBase(smackMessage.getFrom());
ChatSession session = findOrCreateSession(address);
rec.setTo(mUser.getAddress());
rec.setFrom(session.getParticipant().getAddress());
rec.setDateTime(new Date());
session.onReceiveMessage(rec);
}
}, new MessageTypeFilter(org.jivesoftware.smack.packet.Message.Type.chat));
mConnection.addPacketListener(new PacketListener() {
@Override
public void processPacket(Packet packet) {
org.jivesoftware.smack.packet.Presence presence = (org.jivesoftware.smack.packet.Presence)packet;
String address = parseAddressBase(presence.getFrom());
Contact contact = findOrCreateContact(address);
if (presence.getType() == Type.subscribe) {
Log.i(TAG, "sub request from " + address);
mContactListManager.getSubscriptionRequestListener().onSubScriptionRequest(contact);
}
else
{
int type = Presence.AVAILABLE;
Mode rmode = presence.getMode();
Type rtype = presence.getType();
if (rmode == Mode.away || rmode == Mode.xa)
type = Presence.AWAY;
if (rmode == Mode.dnd)
type = Presence.DO_NOT_DISTURB;
if (rtype == Type.unavailable)
type = Presence.OFFLINE;
contact.setPresence(new Presence(type, presence.getStatus(), null, null, Presence.CLIENT_TYPE_DEFAULT));
}
}
}, new PacketTypeFilter(org.jivesoftware.smack.packet.Presence.class));
mConnection.addConnectionListener(new ConnectionListener() {
@Override
public void reconnectionSuccessful() {
Log.i(TAG, "reconnection success");
setState(LOGGED_IN, null);
}
@Override
public void reconnectionFailed(Exception e) {
Log.i(TAG, "reconnection failed", e);
forced_disconnect(new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, e.getMessage()));
}
@Override
public void reconnectingIn(int seconds) {
/*
* Reconnect happens:
* - due to network error
* - but not if connectionClosed is fired
*/
Log.i(TAG, "reconnecting in " + seconds);
setState(LOGGING_IN, null);
}
@Override
public void connectionClosedOnError(Exception e) {
/*
* This fires when:
* - Packet reader or writer detect an error
* - Stream compression failed
* - TLS fails but is required
*/
Log.i(TAG, "reconnect on error", e);
if (e.getMessage().contains("conflict")) {
disconnect();
disconnected(new ImErrorInfo(ImErrorInfo.CANT_CONNECT_TO_SERVER, "logged in from another location"));
}
else {
setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, e.getMessage()));
mExecutor.execute(new Runnable() {
@Override
public void run() {
maybe_reconnect();
}
});
}
}
@Override
public void connectionClosed() {
/*
* This can be called in these cases:
* - Connection is shutting down
* - because we are calling disconnect
* - in do_logout
*
* - NOT (fixed in smack)
* - because server disconnected "normally"
* - we were trying to log in (initConnection), but are failing
* - due to network error
* - in forced disconnect
* - due to login failing
*/
Log.i(TAG, "connection closed");
}
});
mConnection.login(login, password, resource);
org.jivesoftware.smack.packet.Presence presence =
new org.jivesoftware.smack.packet.Presence(org.jivesoftware.smack.packet.Presence.Type.available);
mConnection.sendPacket(presence);
}
void disconnected(ImErrorInfo info) {
Log.w(TAG, "disconnected");
setState(DISCONNECTED, info);
}
void forced_disconnect(ImErrorInfo info) {
// UNUSED
Log.w(TAG, "forced disconnect");
try {
if (mConnection!= null) {
XMPPConnection conn = mConnection;
mConnection = null;
conn.disconnect();
}
}
catch (Exception e) {
// Ignore
}
disconnected(info);
}
protected static String parseAddressBase(String from) {
return from.replaceFirst("/.*", "");
}
protected static String parseAddressUser(String from) {
return from.replaceFirst("@.*", "");
}
@Override
public void logoutAsync() {
mExecutor.execute(new Runnable() {
@Override
public void run() {
do_logout();
}
});
}
private void do_logout() {
Log.w(TAG, "logout");
setState(LOGGING_OUT, null);
disconnect();
setState(DISCONNECTED, null);
}
private void disconnect() {
clearHeartbeat();
XMPPConnection conn = mConnection;
mConnection = null;
try {
conn.disconnect();
} catch (Throwable th) {
// ignore
}
mNeedReconnect = false;
mRetryLogin = false;
}
@Override
public void reestablishSessionAsync(HashMap<String, String> sessionContext) {
}
@Override
public void suspend() {
}
private ChatSession findOrCreateSession(String address) {
ChatSession session = mSessionManager.findSession(address);
if (session == null) {
Contact contact = findOrCreateContact(address);
session = mSessionManager.createChatSession(contact);
}
return session;
}
Contact findOrCreateContact(String address) {
Contact contact = mContactListManager.getContact(address);
if (contact == null) {
contact = makeContact(address);
}
return contact;
}
private static String makeNameFromAddress(String address) {
return address;
}
private static Contact makeContact(String address) {
Contact contact = new Contact(new XmppAddress(address), address);
return contact;
}
private final class XmppChatSessionManager extends ChatSessionManager {
@Override
public void sendMessageAsync(ChatSession session, Message message) {
org.jivesoftware.smack.packet.Message msg =
new org.jivesoftware.smack.packet.Message(
message.getTo().getFullName(),
org.jivesoftware.smack.packet.Message.Type.chat
);
msg.setBody(message.getBody());
mConnection.sendPacket(msg);
}
ChatSession findSession(String address) {
for (Iterator<ChatSession> iter = mSessions.iterator(); iter.hasNext();) {
ChatSession session = iter.next();
if (session.getParticipant().getAddress().getFullName().equals(address))
return session;
}
return null;
}
}
public ChatSession findSession (String address)
{
return mSessionManager.findSession(address);
}
public ChatSession createChatSession (Contact contact)
{
return mSessionManager.createChatSession(contact);
}
private final class XmppContactList extends ContactListManager {
private Hashtable<String, org.jivesoftware.smack.packet.Presence> unprocdPresence = new Hashtable<String, org.jivesoftware.smack.packet.Presence>();
@Override
protected void setListNameAsync(final String name, final ContactList list) {
mExecutor.execute(new Runnable() {
@Override
public void run() {
do_setListName(name, list);
}
});
}
private void do_setListName(String name, ContactList list) {
Log.d(TAG, "set list name");
mConnection.getRoster().getGroup(list.getName()).setName(name);
notifyContactListNameUpdated(list, name);
}
@Override
public String normalizeAddress(String address) {
return address;
}
@Override
public void loadContactListsAsync() {
mExecutor.execute(new Runnable() {
@Override
public void run() {
do_loadContactLists();
}
});
}
/**
* Create new list of contacts from roster entries.
*
* @param entryIter iterator of roster entries to add to contact list
* @param skipList list of contacts which should be omitted; new contacts are added to this list automatically
* @return contacts from roster which were not present in skiplist.
*/
private Collection<Contact> fillContacts(Iterator<RosterEntry> entryIter, Set<String> skipList) {
Collection<Contact> contacts = new ArrayList<Contact>();
for (; entryIter.hasNext();) {
RosterEntry entry = entryIter.next();
String address = parseAddressBase(entry.getUser());
/* Skip entries present in the skip list */
if (skipList != null && !skipList.add(address))
continue;
String name = entry.getName();
if (name == null)
name = address;
XmppAddress xaddress = new XmppAddress(name, address);
Contact contact = new Contact(xaddress, name);
contacts.add(contact);
}
return contacts;
}
private void do_loadContactLists() {
Log.d(TAG, "load contact lists");
Roster roster = mConnection.getRoster();
roster.setSubscriptionMode(Roster.SubscriptionMode.manual);
listenToRoster(roster);
Set<String> seen = new HashSet<String>();
for (Iterator<RosterGroup> giter = roster.getGroups().iterator(); giter.hasNext();) {
RosterGroup group = giter.next();
Collection<Contact> contacts = fillContacts(group.getEntries().iterator(), seen);
ContactList cl = new ContactList(mUser.getAddress(), group.getName(), true, contacts, this);
mContactLists.add(cl);
if (mDefaultContactList == null)
mDefaultContactList = cl;
notifyContactListLoaded(cl);
notifyContactsPresenceUpdated(contacts.toArray(new Contact[0]));
processQueuedPresenceNotifications (contacts);
}
if (roster.getUnfiledEntryCount() > 0) {
String generalGroupName = "General";
RosterGroup group = roster.getGroup(generalGroupName);
if (group == null)
group = roster.createGroup(generalGroupName);
Collection<Contact> contacts = fillContacts(roster.getUnfiledEntries().iterator(), null);
ContactList cl = new ContactList(mUser.getAddress(), generalGroupName , true, contacts, this);
//n8fr8: adding this contact list to the master list manager seems like the righ thing to do
mContactLists.add(cl);
mDefaultContactList = cl;
notifyContactListLoaded(cl);
processQueuedPresenceNotifications(contacts);
//n8fr8: also needs to ping the presence status change, too!
notifyContactsPresenceUpdated(contacts.toArray(new Contact[0]));
}
notifyContactListsLoaded();
}
/*
* iterators through a list of contacts to see if there were any Presence
* notifications sent before the contact was loaded
*/
private void processQueuedPresenceNotifications (Collection<Contact> contacts)
{
//now iterate through the list of queued up unprocessed presence changes
for (Contact contact : contacts)
{
String address = parseAddressBase(contact.getAddress().getFullName());
org.jivesoftware.smack.packet.Presence presence = unprocdPresence.get(address);
if (presence != null)
{
unprocdPresence.remove(address);
int type = Presence.AVAILABLE;
Mode rmode = presence.getMode();
Type rtype = presence.getType();
if (rmode == Mode.away || rmode == Mode.xa)
type = Presence.AWAY;
if (rmode == Mode.dnd)
type = Presence.DO_NOT_DISTURB;
if (rtype == Type.unavailable)
type = Presence.OFFLINE;
contact.setPresence(new Presence(type, presence.getStatus(), null, null, Presence.CLIENT_TYPE_DEFAULT));
}
}
}
private void listenToRoster(final Roster roster) {
roster.addRosterListener(new RosterListener() {
@Override
public void presenceChanged(org.jivesoftware.smack.packet.Presence presence) {
handlePresenceChanged(presence, roster);
}
@Override
public void entriesUpdated(Collection<String> addresses) {
// TODO update contact list entries from remote
Log.d(TAG, "roster entries updated");
}
@Override
public void entriesDeleted(Collection<String> addresses) {
// TODO delete contacts from remote
Log.d(TAG, "roster entries deleted");
}
@Override
public void entriesAdded(Collection<String> addresses) {
// TODO add contacts from remote
Log.d(TAG, "roster entries added");
}
});
}
private void handlePresenceChanged (org.jivesoftware.smack.packet.Presence presence, Roster roster)
{
String user = parseAddressBase(presence.getFrom());
Contact contact = mContactListManager.getContact(user);
if (contact == null)
{
//Log.d(TAG, "Got present update for NULL user: " + user);
//store the latest presence notification for this user in this queue
unprocdPresence.put(user, presence);
return;
}
Contact []contacts = new Contact[] { contact };
// Get it from the roster - it handles priorities, etc.
presence = roster.getPresence(user);
int type = Presence.AVAILABLE;
Mode rmode = presence.getMode();
Type rtype = presence.getType();
if (rmode == Mode.away || rmode == Mode.xa)
type = Presence.AWAY;
if (rmode == Mode.dnd)
type = Presence.DO_NOT_DISTURB;
if (rtype == Type.unavailable)
type = Presence.OFFLINE;
contact.setPresence(new Presence(type, presence.getStatus(), null, null, Presence.CLIENT_TYPE_DEFAULT));
notifyContactsPresenceUpdated(contacts);
}
@Override
protected ImConnection getConnection() {
return XmppConnection.this;
}
@Override
protected void doRemoveContactFromListAsync(Contact contact,
ContactList list) {
Roster roster = mConnection.getRoster();
String address = contact.getAddress().getFullName();
try {
RosterGroup group = roster.getGroup(list.getName());
if (group == null) {
Log.e(TAG, "could not find group " + list.getName() + " in roster");
return;
}
RosterEntry entry = roster.getEntry(address);
if (entry == null) {
Log.e(TAG, "could not find entry " + address + " in group " + list.getName());
return;
}
group.removeEntry(entry);
} catch (XMPPException e) {
Log.e(TAG, "remove entry failed", e);
throw new RuntimeException(e);
}
org.jivesoftware.smack.packet.Presence response =
new org.jivesoftware.smack.packet.Presence(org.jivesoftware.smack.packet.Presence.Type.unsubscribed);
response.setTo(address);
mConnection.sendPacket(response);
notifyContactListUpdated(list, ContactListListener.LIST_CONTACT_REMOVED, contact);
}
@Override
protected void doDeleteContactListAsync(ContactList list) {
// TODO delete contact list
Log.i(TAG, "delete contact list " + list.getName());
}
@Override
protected void doCreateContactListAsync(String name,
Collection<Contact> contacts, boolean isDefault) {
// TODO create contact list
Log.i(TAG, "create contact list " + name + " default " + isDefault);
}
@Override
protected void doBlockContactAsync(String address, boolean block) {
// TODO block contact
}
@Override
protected void doAddContactToListAsync(String address, ContactList list)
throws ImException {
Log.i(TAG, "add contact to " + list.getName());
org.jivesoftware.smack.packet.Presence response =
new org.jivesoftware.smack.packet.Presence(org.jivesoftware.smack.packet.Presence.Type.subscribed);
response.setTo(address);
mConnection.sendPacket(response);
Roster roster = mConnection.getRoster();
String[] groups = new String[] { list.getName() };
try {
roster.createEntry(address, makeNameFromAddress(address), groups);
} catch (XMPPException e) {
throw new RuntimeException(e);
}
Contact contact = makeContact(address);
notifyContactListUpdated(list, ContactListListener.LIST_CONTACT_ADDED, contact);
}
@Override
public void declineSubscriptionRequest(String contact) {
Log.d(TAG, "decline subscription");
org.jivesoftware.smack.packet.Presence response =
new org.jivesoftware.smack.packet.Presence(org.jivesoftware.smack.packet.Presence.Type.unsubscribed);
response.setTo(contact);
mConnection.sendPacket(response);
mContactListManager.getSubscriptionRequestListener().onSubscriptionDeclined(contact);
}
@Override
public void approveSubscriptionRequest(String contact) {
Log.d(TAG, "approve subscription");
try {
// FIXME maybe need to check if already in another contact list
mContactListManager.doAddContactToListAsync(contact, getDefaultContactList());
} catch (ImException e) {
Log.e(TAG, "failed to add " + contact + " to default list");
}
mContactListManager.getSubscriptionRequestListener().onSubscriptionApproved(contact);
}
@Override
public Contact createTemporaryContact(String address) {
Log.d(TAG, "create temporary " + address);
return makeContact(address);
}
}
public static class XmppAddress extends Address {
private String address;
private String name;
public XmppAddress() {
}
public XmppAddress(String name, String address) {
this.name = name;
this.address = address;
}
public XmppAddress(String address) {
this.name = makeNameFromAddress(address);
this.address = address;
}
@Override
public String getFullName() {
return address;
}
@Override
public String getScreenName() {
return name;
}
@Override
public void readFromParcel(Parcel source) {
name = source.readString();
address = source.readString();
}
@Override
public void writeToParcel(Parcel dest) {
dest.writeString(name);
dest.writeString(address);
}
}
private PacketCollector mPingCollector;
/*
* Alarm event fired
* @see info.guardianproject.otr.app.im.engine.ImConnection#sendHeartbeat()
*/
public void sendHeartbeat() {
mExecutor.execute(new Runnable() {
@Override
public void run() {
doHeartbeat();
}
});
}
public void doHeartbeat() {
if (mConnection == null && mRetryLogin && mLoginInfo != null) {
Log.i(TAG, "reconnect with login");
do_login();
}
if (mConnection == null)
return;
if (mNeedReconnect) {
retry_reconnect();
}
else if (mConnection.isConnected() && getState() == LOGGED_IN) {
Log.d(TAG, "ping");
if (!sendPing()) {
if (getState() == LOGGED_IN)
setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, "network timeout"));
Log.w(TAG, "reconnect on ping failed");
force_reconnect();
}
}
}
private void clearHeartbeat() {
Log.d(TAG, "clear heartbeat");
mPingCollector = null;
}
private boolean sendPing() {
// Check ping result from previous send
if (mPingCollector != null) {
IQ result = (IQ)mPingCollector.nextResult(0);
mPingCollector.cancel();
if (result == null)
{
clearHeartbeat();
Log.e(TAG, "ping timeout");
return false;
}
}
IQ req = new IQ() {
public String getChildElementXML() {
return "<ping xmlns='urn:xmpp:ping'/>";
}
};
req.setType(IQ.Type.GET);
PacketFilter filter = new AndFilter(new PacketIDFilter(req.getPacketID()),
new PacketTypeFilter(IQ.class));
mPingCollector = mConnection.createPacketCollector(filter);
mConnection.sendPacket(req);
return true;
}
// watch out, this is a different XMPPConnection class than XmppConnection! ;)
// org.jivesoftware.smack.XMPPConnection
// - vs -
// info.guardianproject.otr.app.im.plugin.xmpp.XmppConnection
static class MyXMPPConnection extends XMPPConnection {
public MyXMPPConnection(ConnectionConfiguration config) {
super(config);
//this.getConfiguration().setSocketFactory(arg0)
}
}
@Override
public void networkTypeChanged() {
super.networkTypeChanged();
if (getState() == LOGGED_IN)
setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, "network changed"));
if (getState() != LOGGED_IN && getState() != LOGGING_IN)
return;
if (mNeedReconnect)
return;
Log.w(TAG, "reconnect on network change");
force_reconnect();
}
/*
* Force a disconnect and reconnect, unless we are already reconnecting.
*/
private void force_reconnect() {
Log.d(TAG, "force_reconnect need=" + mNeedReconnect);
if (mConnection == null)
return;
if (mNeedReconnect)
return;
mConnection.disconnect();
mNeedReconnect = true;
reconnect();
}
/*
* Reconnect unless we are already in the process of doing so.
*/
private void maybe_reconnect() {
// If we already know we don't have a good connection, the heartbeat will take care of this
Log.d(TAG, "maybe_reconnect need=" + mNeedReconnect);
if (mNeedReconnect)
return;
mNeedReconnect = true;
reconnect();
}
/*
* Retry a reconnect on alarm event
*/
private void retry_reconnect() {
// Retry reconnecting if we still need to
Log.d(TAG, "retry_reconnect need=" + mNeedReconnect);
if (mConnection != null && mNeedReconnect)
reconnect();
}
/*
* Retry connecting
*/
private void reconnect() {
Log.i(TAG, "reconnect");
clearHeartbeat();
try {
mConnection.connect();
mNeedReconnect = false;
Log.i(TAG, "reconnected");
setState(LOGGED_IN, null);
} catch (XMPPException e) {
Log.e(TAG, "reconnection on network change failed", e);
setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, e.getMessage()));
}
}
}
| src/info/guardianproject/otr/app/im/plugin/xmpp/XmppConnection.java | package info.guardianproject.otr.app.im.plugin.xmpp;
import info.guardianproject.otr.app.im.app.ImApp;
import info.guardianproject.otr.app.im.engine.Address;
import info.guardianproject.otr.app.im.engine.ChatGroupManager;
import info.guardianproject.otr.app.im.engine.ChatSession;
import info.guardianproject.otr.app.im.engine.ChatSessionManager;
import info.guardianproject.otr.app.im.engine.Contact;
import info.guardianproject.otr.app.im.engine.ContactList;
import info.guardianproject.otr.app.im.engine.ContactListListener;
import info.guardianproject.otr.app.im.engine.ContactListManager;
import info.guardianproject.otr.app.im.engine.ImConnection;
import info.guardianproject.otr.app.im.engine.ImErrorInfo;
import info.guardianproject.otr.app.im.engine.ImException;
import info.guardianproject.otr.app.im.engine.LoginInfo;
import info.guardianproject.otr.app.im.engine.Message;
import info.guardianproject.otr.app.im.engine.Presence;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.RosterGroup;
import org.jivesoftware.smack.RosterListener;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence.Mode;
import org.jivesoftware.smack.packet.Presence.Type;
import org.jivesoftware.smack.proxy.ProxyInfo;
import org.jivesoftware.smack.proxy.ProxyInfo.ProxyType;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Parcel;
import android.preference.PreferenceManager;
import android.util.Log;
public class XmppConnection extends ImConnection {
private final static String TAG = "XmppConnection";
private XmppContactList mContactListManager;
private Contact mUser;
// watch out, this is a different XMPPConnection class than XmppConnection! ;)
private MyXMPPConnection mConnection;
private XmppChatSessionManager mSessionManager;
private ConnectionConfiguration mConfig;
private boolean mNeedReconnect;
private LoginInfo mLoginInfo;
private boolean mRetryLogin;
private Executor mExecutor;
private ProxyInfo mProxyInfo = null;
private final static int XMPP_DEFAULT_PORT = 5222;
public XmppConnection(Context context) {
super(context);
Log.w(TAG, "created");
//ReconnectionManager.activate();
//SmackConfiguration.setKeepAliveInterval(-1);
mExecutor = Executors.newSingleThreadExecutor();
}
public void sendMessage(org.jivesoftware.smack.packet.Message msg) {
mConnection.sendPacket(msg);
}
@Override
protected void doUpdateUserPresenceAsync(Presence presence) {
String statusText = presence.getStatusText();
Type type = Type.available;
Mode mode = Mode.available;
int priority = 20;
if (presence.getStatus() == Presence.AWAY) {
priority = 10;
mode = Mode.away;
}
else if (presence.getStatus() == Presence.IDLE) {
priority = 15;
mode = Mode.away;
}
else if (presence.getStatus() == Presence.DO_NOT_DISTURB) {
priority = 5;
mode = Mode.dnd;
}
else if (presence.getStatus() == Presence.OFFLINE) {
priority = 0;
type = Type.unavailable;
statusText = "Offline";
}
org.jivesoftware.smack.packet.Presence packet =
new org.jivesoftware.smack.packet.Presence(type, statusText, priority, mode);
mConnection.sendPacket(packet);
mUserPresence = presence;
notifyUserPresenceUpdated();
}
@Override
public int getCapability() {
// TODO chat groups
return 0;
}
@Override
public ChatGroupManager getChatGroupManager() {
// TODO chat groups
return null;
}
@Override
public ChatSessionManager getChatSessionManager() {
mSessionManager = new XmppChatSessionManager();
return mSessionManager;
}
@Override
public ContactListManager getContactListManager() {
mContactListManager = new XmppContactList();
return mContactListManager;
}
@Override
public Contact getLoginUser() {
return mUser;
}
@Override
public HashMap<String, String> getSessionContext() {
return null;
}
@Override
public int[] getSupportedPresenceStatus() {
return new int[] {
Presence.AVAILABLE,
Presence.AWAY,
Presence.IDLE,
Presence.OFFLINE,
Presence.DO_NOT_DISTURB,
};
}
@Override
public void loginAsync(final LoginInfo loginInfo, boolean retry) {
mLoginInfo = loginInfo;
mRetryLogin = retry;
mExecutor.execute(new Runnable() {
@Override
public void run() {
do_login();
}
});
}
private void do_login() {
if (mConnection != null) {
setState(getState(), new ImErrorInfo(ImErrorInfo.CANT_CONNECT_TO_SERVER, "still trying..."));
return;
}
Log.i(TAG, "logging in " + mLoginInfo.getUserName());
mNeedReconnect = true;
setState(LOGGING_IN, null);
mUserPresence = new Presence(Presence.AVAILABLE, "Online", null, null, Presence.CLIENT_TYPE_DEFAULT);
String username = mLoginInfo.getUserName();
String []comps = username.split("@");
if (comps.length != 2) {
disconnected(new ImErrorInfo(ImErrorInfo.INVALID_USERNAME, "username should be user@host"));
mRetryLogin = false;
mNeedReconnect = false;
return;
}
try {
String sUsername = java.net.URLDecoder.decode(comps[0]);
String serverInfo[] = comps[1].split(":");
if (serverInfo.length == 0)
throw new XMPPException("invalid host setting");
String serverHost = serverInfo[0];
int serverPort = Integer.parseInt(serverInfo[1]);
initConnection(serverHost, serverPort, sUsername, mLoginInfo.getPassword(), "Gibberbot");
} catch (XMPPException e) {
Log.e(TAG, "login failed", e);
mConnection = null;
ImErrorInfo info = new ImErrorInfo(ImErrorInfo.CANT_CONNECT_TO_SERVER, e.getMessage());
if (e.getMessage().contains("not-authorized")) {
Log.w(TAG, "not authorized - will not retry");
info = new ImErrorInfo(ImErrorInfo.INVALID_USERNAME, "invalid user/password");
disconnected(info);
mRetryLogin = false;
}
else if (mRetryLogin) {
Log.w(TAG, "will retry");
setState(LOGGING_IN, info);
}
else {
Log.w(TAG, "will not retry");
mConnection = null;
disconnected(info);
}
return;
} finally {
mNeedReconnect = false;
}
username = username.split(":")[0];//remove any port mentions
mUser = new Contact(new XmppAddress(username, username), username);
setState(LOGGED_IN, null);
Log.i(TAG, "logged in");
}
public void setProxy (String type, String host, int port)
{
if (type == null)
{
mProxyInfo = ProxyInfo.forNoProxy();
}
else
{
ProxyInfo.ProxyType pType = ProxyType.valueOf(type);
mProxyInfo = new ProxyInfo(pType, host, port,"","");
}
}
private void initConnection(String serverHost, int serverPort, String login, String password, String resource) throws XMPPException {
// TODO these booleans should be set in the preferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
boolean doTLS = prefs.getBoolean("pref_security_tls", true);
boolean doSRV = prefs.getBoolean("pref_security_do_srv", false);
boolean doCertVerification = prefs.getBoolean("pref_security_tls_very", true);
Log.i(TAG, "TLS required? " + doTLS);
Log.i(TAG, "Do SRV check? " + doSRV);
Log.i(TAG, "cert verification? " + doCertVerification);
boolean allowSelfSignedCerts = !doCertVerification;
boolean doVerifyDomain = doCertVerification;
if (mProxyInfo == null)
mProxyInfo = ProxyInfo.forNoProxy();
// TODO how should we handle special ConnectionConfiguration for hosts like google?
//we want to make it easy for users - maybe this shouldn't be here though
if (serverHost.equals("gmail.com") || serverHost.equals("googlemail.com")) {
// only use the @host.com serverHost name so that ConnectionConfiguration does a DNS SRV lookup
// is always talk.google.com
mConfig = new ConnectionConfiguration("talk.google.com", 5222, serverHost, mProxyInfo);
if (doTLS)
mConfig.setSecurityMode(SecurityMode.required);
else
mConfig.setSecurityMode(SecurityMode.enabled);
mConfig.setSASLAuthenticationEnabled(true);
SASLAuthentication.supportSASLMechanism("PLAIN", 0); //Gtalk only supports PLAIN
if (login.indexOf("@")==-1)
login = login + "@" + serverHost;
mConfig.setVerifyRootCAEnabled(false); //TODO we have to disable this for now with Gmail
mConfig.setVerifyChainEnabled(doCertVerification); //but we still can verify the chain
mConfig.setExpiredCertificatesCheckEnabled(doCertVerification);
mConfig.setNotMatchingDomainCheckEnabled(doVerifyDomain);
} else {
// TODO test first only using serverHost to use the DNS SRV lookup, otherwise try all the saved settings
// set the priority of auth methods, 0 being the first tried
if (doSRV)
mConfig = new ConnectionConfiguration(serverHost, mProxyInfo);
else
mConfig = new ConnectionConfiguration(serverHost, serverPort, serverHost, mProxyInfo);
if (doTLS)
mConfig.setSecurityMode(SecurityMode.required);
else
mConfig.setSecurityMode(SecurityMode.enabled);
mConfig.setSASLAuthenticationEnabled(true);
//set at equal priority
SASLAuthentication.supportSASLMechanism("PLAIN", 0);
SASLAuthentication.supportSASLMechanism("DIGEST-MD5", 1);
mConfig.setVerifyChainEnabled(doCertVerification);
mConfig.setVerifyRootCAEnabled(doCertVerification);
mConfig.setExpiredCertificatesCheckEnabled(doCertVerification);
mConfig.setNotMatchingDomainCheckEnabled(doVerifyDomain);
}
// Android doesn't support the default "jks" Java Key Store, it uses "bks" instead
mConfig.setTruststoreType("BKS");
mConfig.setTruststorePath("/system/etc/security/cacerts.bks");
// this should probably be set to our own, if we are going to save self-signed certs
//mConfig.setKeystoreType("bks");
//mConfig.setKeystorePath("/system/etc/security/cacerts.bks");
if (allowSelfSignedCerts) {
Log.i(TAG, "allowing self-signed certs");
mConfig.setSelfSignedCertificateEnabled(true);
}
//reconnect please
mConfig.setReconnectionAllowed(true);
mConfig.setRosterLoadedAtLogin(true);
mConfig.setSendPresence(true);
Log.i(TAG, "ConnnectionConfiguration.getHost: " + mConfig.getHost() + " getPort: " + mConfig.getPort() + " getServiceName: " + mConfig.getServiceName());
mConnection = new MyXMPPConnection(mConfig);
mConnection.connect();
Log.i(TAG,"is secure connection? " + mConnection.isSecureConnection());
Log.i(TAG,"is using TLS? " + mConnection.isUsingTLS());
mConnection.addPacketListener(new PacketListener() {
@Override
public void processPacket(Packet packet) {
org.jivesoftware.smack.packet.Message smackMessage = (org.jivesoftware.smack.packet.Message) packet;
Message rec = new Message(smackMessage.getBody());
String address = parseAddressBase(smackMessage.getFrom());
ChatSession session = findOrCreateSession(address);
rec.setTo(mUser.getAddress());
rec.setFrom(session.getParticipant().getAddress());
rec.setDateTime(new Date());
session.onReceiveMessage(rec);
}
}, new MessageTypeFilter(org.jivesoftware.smack.packet.Message.Type.chat));
mConnection.addPacketListener(new PacketListener() {
@Override
public void processPacket(Packet packet) {
org.jivesoftware.smack.packet.Presence presence = (org.jivesoftware.smack.packet.Presence)packet;
String address = parseAddressBase(presence.getFrom());
Contact contact = findOrCreateContact(address);
if (presence.getType() == Type.subscribe) {
Log.i(TAG, "sub request from " + address);
mContactListManager.getSubscriptionRequestListener().onSubScriptionRequest(contact);
}
else
{
int type = Presence.AVAILABLE;
Mode rmode = presence.getMode();
Type rtype = presence.getType();
if (rmode == Mode.away || rmode == Mode.xa)
type = Presence.AWAY;
if (rmode == Mode.dnd)
type = Presence.DO_NOT_DISTURB;
if (rtype == Type.unavailable)
type = Presence.OFFLINE;
contact.setPresence(new Presence(type, presence.getStatus(), null, null, Presence.CLIENT_TYPE_DEFAULT));
}
}
}, new PacketTypeFilter(org.jivesoftware.smack.packet.Presence.class));
mConnection.addConnectionListener(new ConnectionListener() {
@Override
public void reconnectionSuccessful() {
Log.i(TAG, "reconnection success");
setState(LOGGED_IN, null);
}
@Override
public void reconnectionFailed(Exception e) {
Log.i(TAG, "reconnection failed", e);
forced_disconnect(new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, e.getMessage()));
}
@Override
public void reconnectingIn(int seconds) {
/*
* Reconnect happens:
* - due to network error
* - but not if connectionClosed is fired
*/
Log.i(TAG, "reconnecting in " + seconds);
setState(LOGGING_IN, null);
}
@Override
public void connectionClosedOnError(Exception e) {
/*
* This fires when:
* - Packet reader or writer detect an error
* - Stream compression failed
* - TLS fails but is required
*/
Log.i(TAG, "reconnect on error", e);
if (e.getMessage().contains("conflict")) {
disconnect();
disconnected(new ImErrorInfo(ImErrorInfo.CANT_CONNECT_TO_SERVER, "logged in from another location"));
}
else {
setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, e.getMessage()));
mExecutor.execute(new Runnable() {
@Override
public void run() {
maybe_reconnect();
}
});
}
}
@Override
public void connectionClosed() {
/*
* This can be called in these cases:
* - Connection is shutting down
* - because we are calling disconnect
* - in do_logout
*
* - NOT (fixed in smack)
* - because server disconnected "normally"
* - we were trying to log in (initConnection), but are failing
* - due to network error
* - in forced disconnect
* - due to login failing
*/
Log.i(TAG, "connection closed");
}
});
mConnection.login(login, password, resource);
org.jivesoftware.smack.packet.Presence presence =
new org.jivesoftware.smack.packet.Presence(org.jivesoftware.smack.packet.Presence.Type.available);
mConnection.sendPacket(presence);
}
void disconnected(ImErrorInfo info) {
Log.w(TAG, "disconnected");
setState(DISCONNECTED, info);
}
void forced_disconnect(ImErrorInfo info) {
// UNUSED
Log.w(TAG, "forced disconnect");
try {
if (mConnection!= null) {
XMPPConnection conn = mConnection;
mConnection = null;
conn.disconnect();
}
}
catch (Exception e) {
// Ignore
}
disconnected(info);
}
protected static String parseAddressBase(String from) {
return from.replaceFirst("/.*", "");
}
protected static String parseAddressUser(String from) {
return from.replaceFirst("@.*", "");
}
@Override
public void logoutAsync() {
mExecutor.execute(new Runnable() {
@Override
public void run() {
do_logout();
}
});
}
private void do_logout() {
Log.w(TAG, "logout");
setState(LOGGING_OUT, null);
disconnect();
setState(DISCONNECTED, null);
}
private void disconnect() {
clearHeartbeat();
XMPPConnection conn = mConnection;
mConnection = null;
try {
conn.disconnect();
} catch (Throwable th) {
// ignore
}
mNeedReconnect = false;
mRetryLogin = false;
}
@Override
public void reestablishSessionAsync(HashMap<String, String> sessionContext) {
}
@Override
public void suspend() {
}
private ChatSession findOrCreateSession(String address) {
ChatSession session = mSessionManager.findSession(address);
if (session == null) {
Contact contact = findOrCreateContact(address);
session = mSessionManager.createChatSession(contact);
}
return session;
}
Contact findOrCreateContact(String address) {
Contact contact = mContactListManager.getContact(address);
if (contact == null) {
contact = makeContact(address);
}
return contact;
}
private static String makeNameFromAddress(String address) {
return address;
}
private static Contact makeContact(String address) {
Contact contact = new Contact(new XmppAddress(address), address);
return contact;
}
private final class XmppChatSessionManager extends ChatSessionManager {
@Override
public void sendMessageAsync(ChatSession session, Message message) {
org.jivesoftware.smack.packet.Message msg =
new org.jivesoftware.smack.packet.Message(
message.getTo().getFullName(),
org.jivesoftware.smack.packet.Message.Type.chat
);
msg.setBody(message.getBody());
mConnection.sendPacket(msg);
}
ChatSession findSession(String address) {
for (Iterator<ChatSession> iter = mSessions.iterator(); iter.hasNext();) {
ChatSession session = iter.next();
if (session.getParticipant().getAddress().getFullName().equals(address))
return session;
}
return null;
}
}
public ChatSession findSession (String address)
{
return mSessionManager.findSession(address);
}
public ChatSession createChatSession (Contact contact)
{
return mSessionManager.createChatSession(contact);
}
private final class XmppContactList extends ContactListManager {
private Hashtable<String, org.jivesoftware.smack.packet.Presence> unprocdPresence = new Hashtable<String, org.jivesoftware.smack.packet.Presence>();
@Override
protected void setListNameAsync(final String name, final ContactList list) {
mExecutor.execute(new Runnable() {
@Override
public void run() {
do_setListName(name, list);
}
});
}
private void do_setListName(String name, ContactList list) {
Log.d(TAG, "set list name");
mConnection.getRoster().getGroup(list.getName()).setName(name);
notifyContactListNameUpdated(list, name);
}
@Override
public String normalizeAddress(String address) {
return address;
}
@Override
public void loadContactListsAsync() {
mExecutor.execute(new Runnable() {
@Override
public void run() {
do_loadContactLists();
}
});
}
/**
* Create new list of contacts from roster entries.
*
* @param entryIter iterator of roster entries to add to contact list
* @param skipList list of contacts which should be omitted; new contacts are added to this list automatically
* @return contacts from roster which were not present in skiplist.
*/
private Collection<Contact> fillContacts(Iterator<RosterEntry> entryIter, Set<String> skipList) {
Collection<Contact> contacts = new ArrayList<Contact>();
for (; entryIter.hasNext();) {
RosterEntry entry = entryIter.next();
String address = parseAddressBase(entry.getUser());
/* Skip entries present in the skip list */
if (skipList != null && !skipList.add(address))
continue;
String name = entry.getName();
if (name == null)
name = address;
XmppAddress xaddress = new XmppAddress(name, address);
Contact contact = new Contact(xaddress, name);
contacts.add(contact);
}
return contacts;
}
private void do_loadContactLists() {
Log.d(TAG, "load contact lists");
Roster roster = mConnection.getRoster();
roster.setSubscriptionMode(Roster.SubscriptionMode.manual);
listenToRoster(roster);
Set<String> seen = new HashSet<String>();
for (Iterator<RosterGroup> giter = roster.getGroups().iterator(); giter.hasNext();) {
RosterGroup group = giter.next();
Collection<Contact> contacts = fillContacts(group.getEntries().iterator(), seen);
ContactList cl = new ContactList(mUser.getAddress(), group.getName(), true, contacts, this);
mContactLists.add(cl);
if (mDefaultContactList == null)
mDefaultContactList = cl;
notifyContactListLoaded(cl);
notifyContactsPresenceUpdated(contacts.toArray(new Contact[0]));
processQueuedPresenceNotifications (contacts);
}
if (roster.getUnfiledEntryCount() > 0) {
String generalGroupName = "General";
RosterGroup group = roster.getGroup(generalGroupName);
if (group == null)
group = roster.createGroup(generalGroupName);
Collection<Contact> contacts = fillContacts(roster.getUnfiledEntries().iterator(), null);
ContactList cl = new ContactList(mUser.getAddress(), generalGroupName , true, contacts, this);
//n8fr8: adding this contact list to the master list manager seems like the righ thing to do
mContactLists.add(cl);
mDefaultContactList = cl;
notifyContactListLoaded(cl);
processQueuedPresenceNotifications(contacts);
//n8fr8: also needs to ping the presence status change, too!
notifyContactsPresenceUpdated(contacts.toArray(new Contact[0]));
}
notifyContactListsLoaded();
}
/*
* iterators through a list of contacts to see if there were any Presence
* notifications sent before the contact was loaded
*/
private void processQueuedPresenceNotifications (Collection<Contact> contacts)
{
//now iterate through the list of queued up unprocessed presence changes
for (Contact contact : contacts)
{
String address = parseAddressBase(contact.getAddress().getFullName());
org.jivesoftware.smack.packet.Presence presence = unprocdPresence.get(address);
if (presence != null)
{
unprocdPresence.remove(address);
int type = Presence.AVAILABLE;
Mode rmode = presence.getMode();
Type rtype = presence.getType();
if (rmode == Mode.away || rmode == Mode.xa)
type = Presence.AWAY;
if (rmode == Mode.dnd)
type = Presence.DO_NOT_DISTURB;
if (rtype == Type.unavailable)
type = Presence.OFFLINE;
contact.setPresence(new Presence(type, presence.getStatus(), null, null, Presence.CLIENT_TYPE_DEFAULT));
}
}
}
private void listenToRoster(final Roster roster) {
roster.addRosterListener(new RosterListener() {
@Override
public void presenceChanged(org.jivesoftware.smack.packet.Presence presence) {
handlePresenceChanged(presence, roster);
}
@Override
public void entriesUpdated(Collection<String> addresses) {
// TODO update contact list entries from remote
Log.d(TAG, "roster entries updated");
}
@Override
public void entriesDeleted(Collection<String> addresses) {
// TODO delete contacts from remote
Log.d(TAG, "roster entries deleted");
}
@Override
public void entriesAdded(Collection<String> addresses) {
// TODO add contacts from remote
Log.d(TAG, "roster entries added");
}
});
}
private void handlePresenceChanged (org.jivesoftware.smack.packet.Presence presence, Roster roster)
{
String user = parseAddressBase(presence.getFrom());
Contact contact = mContactListManager.getContact(user);
if (contact == null)
{
//Log.d(TAG, "Got present update for NULL user: " + user);
//store the latest presence notification for this user in this queue
unprocdPresence.put(user, presence);
return;
}
Contact []contacts = new Contact[] { contact };
// Get it from the roster - it handles priorities, etc.
presence = roster.getPresence(user);
int type = Presence.AVAILABLE;
Mode rmode = presence.getMode();
Type rtype = presence.getType();
if (rmode == Mode.away || rmode == Mode.xa)
type = Presence.AWAY;
if (rmode == Mode.dnd)
type = Presence.DO_NOT_DISTURB;
if (rtype == Type.unavailable)
type = Presence.OFFLINE;
contact.setPresence(new Presence(type, presence.getStatus(), null, null, Presence.CLIENT_TYPE_DEFAULT));
notifyContactsPresenceUpdated(contacts);
}
@Override
protected ImConnection getConnection() {
return XmppConnection.this;
}
@Override
protected void doRemoveContactFromListAsync(Contact contact,
ContactList list) {
Roster roster = mConnection.getRoster();
String address = contact.getAddress().getFullName();
try {
RosterGroup group = roster.getGroup(list.getName());
if (group == null) {
Log.e(TAG, "could not find group " + list.getName() + " in roster");
return;
}
RosterEntry entry = roster.getEntry(address);
if (entry == null) {
Log.e(TAG, "could not find entry " + address + " in group " + list.getName());
return;
}
group.removeEntry(entry);
} catch (XMPPException e) {
Log.e(TAG, "remove entry failed", e);
throw new RuntimeException(e);
}
org.jivesoftware.smack.packet.Presence response =
new org.jivesoftware.smack.packet.Presence(org.jivesoftware.smack.packet.Presence.Type.unsubscribed);
response.setTo(address);
mConnection.sendPacket(response);
notifyContactListUpdated(list, ContactListListener.LIST_CONTACT_REMOVED, contact);
}
@Override
protected void doDeleteContactListAsync(ContactList list) {
// TODO delete contact list
Log.i(TAG, "delete contact list " + list.getName());
}
@Override
protected void doCreateContactListAsync(String name,
Collection<Contact> contacts, boolean isDefault) {
// TODO create contact list
Log.i(TAG, "create contact list " + name + " default " + isDefault);
}
@Override
protected void doBlockContactAsync(String address, boolean block) {
// TODO block contact
}
@Override
protected void doAddContactToListAsync(String address, ContactList list)
throws ImException {
Log.i(TAG, "add contact to " + list.getName());
org.jivesoftware.smack.packet.Presence response =
new org.jivesoftware.smack.packet.Presence(org.jivesoftware.smack.packet.Presence.Type.subscribed);
response.setTo(address);
mConnection.sendPacket(response);
Roster roster = mConnection.getRoster();
String[] groups = new String[] { list.getName() };
try {
roster.createEntry(address, makeNameFromAddress(address), groups);
} catch (XMPPException e) {
throw new RuntimeException(e);
}
Contact contact = makeContact(address);
notifyContactListUpdated(list, ContactListListener.LIST_CONTACT_ADDED, contact);
}
@Override
public void declineSubscriptionRequest(String contact) {
Log.d(TAG, "decline subscription");
org.jivesoftware.smack.packet.Presence response =
new org.jivesoftware.smack.packet.Presence(org.jivesoftware.smack.packet.Presence.Type.unsubscribed);
response.setTo(contact);
mConnection.sendPacket(response);
mContactListManager.getSubscriptionRequestListener().onSubscriptionDeclined(contact);
}
@Override
public void approveSubscriptionRequest(String contact) {
Log.d(TAG, "approve subscription");
try {
// FIXME maybe need to check if already in another contact list
mContactListManager.doAddContactToListAsync(contact, getDefaultContactList());
} catch (ImException e) {
Log.e(TAG, "failed to add " + contact + " to default list");
}
mContactListManager.getSubscriptionRequestListener().onSubscriptionApproved(contact);
}
@Override
public Contact createTemporaryContact(String address) {
Log.d(TAG, "create temporary " + address);
return makeContact(address);
}
}
public static class XmppAddress extends Address {
private String address;
private String name;
public XmppAddress() {
}
public XmppAddress(String name, String address) {
this.name = name;
this.address = address;
}
public XmppAddress(String address) {
this.name = makeNameFromAddress(address);
this.address = address;
}
@Override
public String getFullName() {
return address;
}
@Override
public String getScreenName() {
return name;
}
@Override
public void readFromParcel(Parcel source) {
name = source.readString();
address = source.readString();
}
@Override
public void writeToParcel(Parcel dest) {
dest.writeString(name);
dest.writeString(address);
}
}
private PacketCollector mPingCollector;
/*
* Alarm event fired
* @see info.guardianproject.otr.app.im.engine.ImConnection#sendHeartbeat()
*/
public void sendHeartbeat() {
mExecutor.execute(new Runnable() {
@Override
public void run() {
doHeartbeat();
}
});
}
public void doHeartbeat() {
if (mConnection == null && mRetryLogin && mLoginInfo != null) {
Log.i(TAG, "reconnect with login");
do_login();
}
if (mConnection == null)
return;
if (mNeedReconnect) {
retry_reconnect();
}
else if (mConnection.isConnected() && getState() == LOGGED_IN) {
Log.d(TAG, "ping");
if (!sendPing()) {
if (getState() == LOGGED_IN)
setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, "network timeout"));
Log.w(TAG, "reconnect on ping failed");
force_reconnect();
}
}
}
private void clearHeartbeat() {
Log.d(TAG, "clear heartbeat");
mPingCollector = null;
}
private boolean sendPing() {
// Check ping result from previous send
if (mPingCollector != null) {
IQ result = (IQ)mPingCollector.nextResult(0);
mPingCollector.cancel();
if (result == null)
{
clearHeartbeat();
Log.e(TAG, "ping timeout");
return false;
}
}
IQ req = new IQ() {
public String getChildElementXML() {
return "<ping xmlns='urn:xmpp:ping'/>";
}
};
req.setType(IQ.Type.GET);
PacketFilter filter = new AndFilter(new PacketIDFilter(req.getPacketID()),
new PacketTypeFilter(IQ.class));
mPingCollector = mConnection.createPacketCollector(filter);
mConnection.sendPacket(req);
return true;
}
// watch out, this is a different XMPPConnection class than XmppConnection! ;)
// org.jivesoftware.smack.XMPPConnection
// - vs -
// info.guardianproject.otr.app.im.plugin.xmpp.XmppConnection
static class MyXMPPConnection extends XMPPConnection {
public MyXMPPConnection(ConnectionConfiguration config) {
super(config);
//this.getConfiguration().setSocketFactory(arg0)
}
}
@Override
public void networkTypeChanged() {
super.networkTypeChanged();
if (getState() == LOGGED_IN)
setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, "network changed"));
if (getState() != LOGGED_IN && getState() != LOGGING_IN)
return;
if (mNeedReconnect)
return;
Log.w(TAG, "reconnect on network change");
force_reconnect();
}
/*
* Force a disconnect and reconnect, unless we are already reconnecting.
*/
private void force_reconnect() {
Log.d(TAG, "force_reconnect need=" + mNeedReconnect);
if (mConnection == null)
return;
if (mNeedReconnect)
return;
mConnection.disconnect();
mNeedReconnect = true;
reconnect();
}
/*
* Reconnect unless we are already in the process of doing so.
*/
private void maybe_reconnect() {
// If we already know we don't have a good connection, the heartbeat will take care of this
Log.d(TAG, "maybe_reconnect need=" + mNeedReconnect);
if (mNeedReconnect)
return;
mNeedReconnect = true;
reconnect();
}
/*
* Retry a reconnect on alarm event
*/
private void retry_reconnect() {
// Retry reconnecting if we still need to
Log.d(TAG, "retry_reconnect need=" + mNeedReconnect);
if (mConnection != null && mNeedReconnect)
reconnect();
}
/*
* Retry connecting
*/
private void reconnect() {
Log.i(TAG, "reconnect");
clearHeartbeat();
try {
mConnection.connect();
mNeedReconnect = false;
Log.i(TAG, "reconnected");
setState(LOGGED_IN, null);
} catch (XMPPException e) {
Log.e(TAG, "reconnection on network change failed", e);
setState(LOGGING_IN, new ImErrorInfo(ImErrorInfo.NETWORK_ERROR, e.getMessage()));
}
}
}
| pedantic SASL and TLS settings for talk.google.com and link to their specs
| src/info/guardianproject/otr/app/im/plugin/xmpp/XmppConnection.java | pedantic SASL and TLS settings for talk.google.com and link to their specs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.